import { useRouter, type Router } from '../../external/useRouter';
import { type Picture } from '../../model/Picture';
import { BlockWrapper } from '../../ui-kit/BlockWrapper';
import { RichText } from '../../ui-kit/RichText/RichText';
import { UniBlock } from '../../UniBlock/UniBlock';
import { type UniBlockProps } from '../../UniBlock/UniBlockProps';
import { style } from '../../utils/style';
import { Headline } from '../Headline/Headline';
import {
  type AttachmentDocDef,
  type DocBlockDef,
  type LinkColumnsMode,
  type LinkDocDef,
  type LinkDocsContent,
} from './LinkDocsContent';
import { renderDefaultItem } from './renderDefaultItem';
import { ReportDialogButton } from './ReportDialogButton';

const linkColumnsModeStyleMap: Record<LinkColumnsMode, string> = {
  double: 'sm:flex-wrap sm:flex-row',
  single: 'sm:flex-col',
};

export interface LinkDocsProps extends LinkDocsContent, UniBlockProps {}

export const LinkDocs = UniBlock<LinkDocsProps>(
  ({
    className = '',
    title,
    description,
    align = 'text-center',
    documents,
    icon = { icon: 'DocIcon' },
    columnsMode = 'double',
    ...rest
  }) => {
    const router = useRouter();

    return (
      <BlockWrapper className={style('space-y-lg', className)} defaultPadding="p-6xl" {...rest}>
        <Headline
          title={title}
          description={description}
          align={align}
          headlineVersion="M"
          as="h2"
          isEmbedded={true}
        />
        {documents?.length ? (
          <div
            className={style(
              'grid gap-xl',
              columnsMode === 'double' ? '@md:grid-cols-2' : 'grid-cols-1',
              linkColumnsModeStyleMap[columnsMode],
            )}
            role="list"
          >
            {documents.map(renderLinkDocItem(router, icon))}
          </div>
        ) : null}
      </BlockWrapper>
    );
  },
);

const renderLinkDocItem =
  (router: Router, icon: Picture) => (docBlockDef: DocBlockDef, i: number) => {
    const docType = docBlockDef?.docType;

    if (docType === '') {
      return null;
    }

    if ('reportSource' in docBlockDef && docBlockDef?.reportSource?.__html) {
      return renderModalItem(icon)(docBlockDef, i);
    }

    return renderDefaultItem(router, icon)(docBlockDef, i);
  };

const renderModalItem = (icon: Picture) => (props: LinkDocDef | AttachmentDocDef, i: number) => {
  const commonProps = {
    text: props.text,
    target: props.target,
    __html: props.reportSource?.__html,
  };

  return props.reportSource?.__html && props.text ? (
    <div role="listitem" key={String(i)}>
      <ReportDialogButton
        {...commonProps}
        icon={icon}
        href={isLinkDoc(props) ? props?.href : props?.attachment?.src}
      />
      <RichText __html={props?.__html} />
    </div>
  ) : null;
};

const isLinkDoc = (data: LinkDocDef | AttachmentDocDef): data is LinkDocDef => 'href' in data;
