import { useEffect, useState } from 'react';

import Typography from '@material-hu/mui/Typography';

import CardContainer from '@material-hu/components/design-system/CardContainer';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { type UploadedDocumentInfo } from '../../../types';

import { DocumentSlot } from './components/DocumentSlot';

export type UploadedDocument = {
  slotIndex: number;
  fileAssetId: number;
};

type DocumentUploadSectionProps = {
  documentNames: string[];
  isCompleted: boolean;
  onFilesChange: (files: UploadedDocument[]) => void;
  onViewDocuments?: () => void;
  showValidationErrors?: boolean;
  uploadedDocuments?: UploadedDocumentInfo[];
};

export const DocumentUploadSection = ({
  documentNames,
  isCompleted,
  onFilesChange,
  showValidationErrors,
  uploadedDocuments,
}: DocumentUploadSectionProps) => {
  const { t } = useLokaliseTranslation('employee_lifecycle');
  const [uploadedBySlot, setUploadedBySlot] = useState<Record<number, number>>(
    {},
  );

  const handleFileChange = (slotIndex: number, fileAssetId: number | null) => {
    setUploadedBySlot(prev => {
      const next = { ...prev };
      if (fileAssetId === null) {
        delete next[slotIndex];
      } else {
        next[slotIndex] = fileAssetId;
      }
      return next;
    });
  };

  useEffect(() => {
    const uploaded = Object.entries(uploadedBySlot).map(([idx, id]) => ({
      slotIndex: Number(idx),
      fileAssetId: id,
    }));
    onFilesChange(uploaded);
  }, [uploadedBySlot]);

  return (
    <CardContainer
      fullWidth
      sx={{
        '& .MuiCardContent-root': {
          display: 'flex',
          flexDirection: 'column',
          gap: 3,
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
        },
      }}
    >
      <Typography fontWeight="fontWeightSemiBold">
        {isCompleted
          ? t('document_task_detail.attached_files')
          : t('document_task_detail.required_documents')}
      </Typography>
      {documentNames.map((name, index) => (
        <DocumentSlot
          key={index}
          documentName={name}
          slotIndex={index}
          isCompleted={isCompleted}
          onFileChange={handleFileChange}
          showError={!!showValidationErrors && !uploadedBySlot[index]}
          uploadedFile={uploadedDocuments?.[index]}
        />
      ))}
    </CardContainer>
  );
};
