import { FormContext } from './context/form-context';
import type { FormComponentProps } from './types';
import { ArrowDownTrayIcon } from '@heroicons/react/24/solid';
import { Heading, InputFile } from '@repo/ui';
import Link from 'next/link';
import { useContext } from 'react';

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

function DownloadDocument({ document }: DownloadDocumentProps) {
  return document?.href ? (
    <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: FormComponentProps['combinedDocuments'][number];
};

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

  const { canUpload, documentTypeId, name } = document;

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files !== null) {
      const file = event.target.files.item(0);
      if (file)
        setFormFiles([
          ...formFiles.filter((x) => x.documentTypeId !== documentTypeId),
          { documentTypeId, file, 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} disabled={!canUpload} />
      <DownloadDocument document={document} />
    </div>
  );
}

export function Files({ combinedDocuments }: FormComponentProps) {
  return (
    <div className="grid gap-4">
      <Heading className="text-sm">Документы</Heading>
      <div className="grid gap-2 md:grid-cols-2">
        {combinedDocuments.map((document) => (
          <File key={document.documentTypeId} document={document} />
        ))}
      </div>
    </div>
  );
}
