import { FormContext } from './context/form-context';
import type { Props } from './types';
import type { Document } from '@/api/ius/types';
import { useContext } from 'react';
import { Heading, InputFile } from 'ui';

function File({ documentTypeId, name }: Document) {
  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">
      <label className="mb-2 block text-sm font-normal text-gray-900">{name}:</label>
      <InputFile onChange={handleFileChange} />
    </div>
  );
}

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