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

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 [preview, setPreview] = useState<{ url: string; title: string } | null>(
    null,
  );
  const localized = useLocalized();
  const { t } = useTranslation();

  if (!evidence?.length) return null;

  return (
    <Group gap="xs">
      {evidence.map((item) => {
        const attachment = attachments.find(
          (a) => a.documentKey === item.docKey && a.files?.length,
        );
        const uploaded = Boolean(attachment);
        const fileUrl = attachment?.files?.[0]?.url;
        return (
          <Group key={item.docKey} gap={4} wrap="nowrap">
          <FileButton
            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>
          {uploaded && fileUrl && (
            <ActionIcon
              size="sm"
              variant="subtle"
              aria-label={t('licensing.documents.view', 'View')}
              onClick={() =>
                setPreview({ url: fileUrl, title: localized(item.label) })
              }
            >
              <IconEye size={14} />
            </ActionIcon>
          )}
          </Group>
        );
      })}
      <PdfPreviewModal
        opened={Boolean(preview)}
        onClose={() => setPreview(null)}
        url={preview?.url ?? ''}
        title={preview?.title}
      />
    </Group>
  );
}
