import { useState } from 'react';
import { Button, FileButton, Group, Loader } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { IconCheck } from '@tabler/icons-react';
import {
  useLocalized,
  uploadDocument,
  useGetAttachmentsQuery,
  type StaffEvidenceRequirement,
} from '@ema-platform/api';
import { useTranslation } from 'react-i18next';

const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;

interface Props {
  staffId: string;
  evidence: StaffEvidenceRequirement[];
  readOnly?: boolean;
  onUploaded: () => void;
}

/**
 * Per-person evidence uploads (CV, work agreement, ERB certificate).
 *
 * These attach to the staff member rather than the application, which is why
 * staff are stored as real rows: each needs a stable owner for their files.
 */
export function StaffEvidence({ staffId, evidence, readOnly, onUploaded }: Props) {
  const { data: attachments = [], refetch } = useGetAttachmentsQuery({
    ownerType: 'APPLICATION_STAFF',
    ownerId: staffId,
  });
  const [busy, setBusy] = useState<string | null>(null);
  const localized = useLocalized();
  const { t } = useTranslation();

  if (!evidence?.length) return null;

  return (
    <Group gap="xs">
      {evidence.map((item) => {
        const uploaded = attachments.some(
          (a) => a.documentKey === item.docKey && a.files?.length,
        );
        return (
          <FileButton
            key={item.docKey}
            accept="application/pdf,image/jpeg,image/png"
            onChange={async (file) => {
              if (!file) return;
              if (file.size > MAX_FILE_SIZE_BYTES) {
                notifications.show({
                  color: 'red',
                  message: t('licensing.msg.fileTooLarge', {
                    size: `${(file.size / 1024 / 1024).toFixed(1)}MB`,
                  }),
                });
                return;
              }
              setBusy(item.docKey);
              await uploadDocument({
                ownerType: 'APPLICATION_STAFF',
                ownerId: staffId,
                documentKey: item.docKey,
                file,
              });
              setBusy(null);
              refetch();
              onUploaded();
            }}
          >
            {(props) => (
              <Button
                {...props}
                size="compact-xs"
                variant={uploaded ? 'light' : 'outline'}
                color={uploaded ? 'teal' : item.mandatory ? 'blue' : 'gray'}
                disabled={readOnly || busy === item.docKey}
                leftSection={
                  busy === item.docKey ? (
                    <Loader size={10} type="oval" />
                  ) : uploaded ? (
                    <IconCheck size={12} />
                  ) : undefined
                }
              >
                {localized(item.label)}
                {item.mandatory && !uploaded ? ' *' : ''}
              </Button>
            )}
          </FileButton>
        );
      })}
    </Group>
  );
}
