import { FormContext } from './context/form-context';
import type { Props } from './types';
import type * as IUS from '@/api/ius/types';
import { ArrowDownTrayIcon } from '@heroicons/react/24/solid';
import Link from 'next/link';
import { useContext } from 'react';
import { Heading, InputFile } from 'ui';

type DownloadDocumentProps = Pick<FileProps, 'document'>;

function DownloadDocument({ document }: DownloadDocumentProps) {
  return document ? (
    <Link
      href={'/api/ius' + document?.href}
      target="_blank"
      rel="noopener noreferrer"
      className="text-primary-600 h-10 px-5 py-2.5 text-sm font-medium hover:underline"
    >
      <div className="flex flex-row items-center gap-1">
        <ArrowDownTrayIcon className="h-4 w-4" />
        Скачать
      </div>
    </Link>
  ) : (
    false
  );
}

type FileProps = {
  readonly document: IUS.Document | undefined;
  readonly documentType: IUS.DocumentType;
};

function File({ document, documentType }: FileProps) {
  const { documentTypeId, name } = documentType;
  const { formFiles, setFormFiles } = useContext(FormContext);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      setFormFiles([
        ...formFiles.filter((x) => x.documentTypeId !== documentTypeId),
        { documentTypeId, file: event.target.files[0], name },
      ]);
    }
  };

  return (
    <div key={documentTypeId} className="flex flex-col gap-1">
      <label className="mb-2 block text-sm font-normal text-gray-900">{name}:</label>
      <InputFile onChange={handleFileChange} />
      <DownloadDocument document={document} />
    </div>
  );
}

export function Files({ documentTypes, documents }: Props) {
  return (
    <div className="grid gap-4">
      <Heading className="text-sms">Документы</Heading>
      <div className="flex flex-col gap-2">
        {documentTypes.map((documentType) => (
          <File
            key={documentType.documentTypeId}
            documentType={documentType}
            document={documents.find((x) => x.documentTypeId === documentType.documentTypeId)}
          />
        ))}
      </div>
    </div>
  );
}
