import { useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {Alert, Avatar, Badge, Button, Center, Container, Divider, Group, Loader, Modal, Paper, SimpleGrid, Stack, Text, Textarea, ThemeIcon, rem} from '@mantine/core';
import { IconAlertTriangle, IconArrowLeft, IconCash, IconCheck, IconDownload, IconFileCertificate } from '@tabler/icons-react';
import {
  SEAFARER_DOCUMENT_KIND_LABELS,
  SEAFARER_DOCUMENT_REQUEST_KIND_COLORS,
  SEAFARER_DOCUMENT_REQUEST_KIND_LABELS,
  SEAFARER_DOCUMENT_STATUS_COLORS,
  SEAFARER_DOCUMENT_STATUS_LABELS,
  extractErrorMessage,
  useConfirmSeafarerDocumentPaymentMutation,
  useGetSeafarerDocumentReviewQuery,
  useIssueSeafarerDocumentMutation,
  useLazyGetSeafarerDocumentReviewDownloadQuery,
  useRejectSeafarerDocumentMutation,
  useScheduleSeafarerDocumentMutation,
} from '@ema-platform/api';
import { AmharicDatePicker, notify, PageHeader } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';
import { LICENSE_PERMISSIONS, RequirePermission } from '@ema-platform/auth';

const QUEUE_PATH = { SEAMAN_BOOK: '/seaman-book-queue', BTC_BASIC_TRAINING: '/btc-queue' } as const;

function Stat({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div>
      <Text fz={10} fw={700} tt="uppercase" c="dimmed" lh={1.2} mb={3}>{label}</Text>
      <Text fz="sm" fw={600} component="div">{value ?? '—'}</Text>
    </div>
  );
}

function SectionCard({
  title,
  icon,
  color,
  children,
}: {
  title: string;
  icon: React.ReactNode;
  color: string;
  children: React.ReactNode;
}) {
  return (
    <Paper withBorder radius="md" p="md">
      <Group gap="xs" mb="sm">
        <ThemeIcon variant="light" color={color} size={26} radius="md">{icon}</ThemeIcon>
        <Text fw={700} fz="sm">{title}</Text>
      </Group>
      <Divider mb="md" />
      {children}
    </Paper>
  );
}

/** One Seaman Book / BTC request: payment → collection date → issue, or reject. */
export function SeafarerDocumentReviewPage() {
  const { id = '' } = useParams();
  const navigate = useNavigate();
  const showDate = useDateDisplayer();
  const { data, isLoading, error } = useGetSeafarerDocumentReviewQuery(id, { skip: !id });

  const [confirmPayment, { isLoading: confirming }] = useConfirmSeafarerDocumentPaymentMutation();
  const [schedule, { isLoading: scheduling }] = useScheduleSeafarerDocumentMutation();
  const [issue, { isLoading: issuing }] = useIssueSeafarerDocumentMutation();
  const [reject, { isLoading: rejecting }] = useRejectSeafarerDocumentMutation();
  const [getDownload, { isFetching: downloading }] = useLazyGetSeafarerDocumentReviewDownloadQuery();

  const [scheduleOpen, setScheduleOpen] = useState(false);
  const [pickupDate, setPickupDate] = useState('');
  const [rejectOpen, setRejectOpen] = useState(false);
  const [reason, setReason] = useState('');

  if (isLoading) {
    return (
      <Center h={300}>
        <Loader />
      </Center>
    );
  }
  if (error || !data) {
    return (
      <Container size="md" py="xl">
        <Alert color="red" icon={<IconAlertTriangle size={16} />}>
          {extractErrorMessage(error, 'Could not load this request.')}
        </Alert>
      </Container>
    );
  }

  const { document, applicant, payment } = data;
  const kindLabel = SEAFARER_DOCUMENT_KIND_LABELS[document.kind];
  const terminal = ['ISSUED', 'REJECTED', 'CANCELLED'].includes(document.status);

  async function run(action: () => Promise<unknown>, done: string) {
    try {
      await action();
      notify.success(done);
      setScheduleOpen(false);
      setRejectOpen(false);
      setReason('');
    } catch (err) {
      notify.error(extractErrorMessage(err, 'Could not record the action'));
    }
  }

  async function download() {
    try {
      const { url } = await getDownload(id).unwrap();
      window.open(url, '_blank', 'noopener');
    } catch (err) {
      notify.error(extractErrorMessage(err, 'Could not fetch the PDF'));
    }
  }

  return (
    <Container size="lg" py="md">
      <Button
        variant="subtle"
        size="xs"
        leftSection={<IconArrowLeft size={14} />}
        onClick={() => navigate(QUEUE_PATH[document.kind])}
        mb="xs"
      >
        Back to queue
      </Button>
      <PageHeader
        title={`${kindLabel} — ${applicant?.name ?? '—'}`}
        meta={
          <>
            <Text size="sm" c="dimmed" ff="monospace">
              {document.requestNumber}
            </Text>
            <Badge size="sm" variant="light" color={SEAFARER_DOCUMENT_STATUS_COLORS[document.status]}>
              {SEAFARER_DOCUMENT_STATUS_LABELS[document.status]}
            </Badge>
            {document.requestKind !== 'NEW' && (
              <Badge size="sm" variant="outline" color={SEAFARER_DOCUMENT_REQUEST_KIND_COLORS[document.requestKind]}>
                {SEAFARER_DOCUMENT_REQUEST_KIND_LABELS[document.requestKind]}
              </Badge>
            )}
            {document.documentNumber && (
              <Badge size="sm" color="teal" leftSection={<IconCheck size={10} />}>
                {document.documentNumber}
              </Badge>
            )}
          </>
        }
        action={
          <Group gap="xs">
          {(document.status === 'PAYMENT_PENDING' || document.status === 'PAID') && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_APPLICATION]} hideOnly>
              <Button loading={confirming} onClick={() => run(() => confirmPayment(id).unwrap(), 'Payment confirmed')}>
                Confirm payment
              </Button>
            </RequirePermission>
          )}
          {document.status === 'PAYMENT_CONFIRMED' && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_APPLICATION]} hideOnly>
              <Button onClick={() => setScheduleOpen(true)}>Schedule pickup</Button>
            </RequirePermission>
          )}
          {(document.status === 'SCHEDULED' || document.status === 'PAYMENT_CONFIRMED') && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_APPLICATION]} hideOnly>
              <Button color="teal" loading={issuing} onClick={() => run(() => issue(id).unwrap(), `${kindLabel} issued`)}>
                Issue
              </Button>
            </RequirePermission>
          )}
          {document.status === 'ISSUED' && (
            <Button variant="light" leftSection={<IconDownload size={14} />} loading={downloading} onClick={download}>
              Download PDF
            </Button>
          )}
          {!terminal && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.REJECT_APPLICATION]} hideOnly>
              <Button color="red" variant="light" onClick={() => setRejectOpen(true)}>
                Reject
              </Button>
            </RequirePermission>
          )}
          </Group>
        }
      />

      {document.status === 'REJECTED' && (
        <Alert color="red" icon={<IconAlertTriangle size={16} />} title="Rejected" mb="md">
          {document.rejectionReason}
        </Alert>
      )}

      <Paper withBorder radius="md" p="lg" mb="md">
        <Group gap="md" wrap="nowrap">
          <Avatar size={52} radius="xl" color="blue" style={{ fontSize: rem(18) }}>
            {(applicant?.name ?? '??').split(' ').filter(Boolean).slice(0, 2).map((p) => p[0]).join('').toUpperCase()}
          </Avatar>
          <div>
            <Text fw={700} fz="lg" lh={1.2}>{applicant?.name ?? '—'}</Text>
            <Group gap={6} mt={4}>
              <Text fz="xs" c="dimmed" ff="monospace">{applicant?.seafarerNumber ?? '—'}</Text>
              {applicant?.registrationId && (
                <>
                  <Text fz="xs" c="dimmed">·</Text>
                  <Link to={`/seafarer-registrations/${applicant.registrationId}`}>
                    <Text fz="xs" c="blue.6">{applicant.registrationNumber}</Text>
                  </Link>
                </>
              )}
            </Group>
          </div>
        </Group>
      </Paper>

      <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
        <SectionCard title="Payment" icon={<IconCash size={14} />} color="teal">
          <SimpleGrid cols={2} spacing="md">
            <Stat label="Fee" value={document.feeAmount !== null ? `${document.feeAmount} ${document.feeCurrency}` : null} />
            <Stat label="Released to payment" value={document.submittedAt ? showDate(document.submittedAt) : null} />
            <Stat label="Paid" value={document.paidAt ? showDate(document.paidAt) : null} />
            <Stat label="Provider" value={payment?.provider} />
            <Stat label="Reference" value={document.paymentReference ?? payment?.providerRef} />
          </SimpleGrid>
        </SectionCard>

        <SectionCard title="Issuance" icon={<IconFileCertificate size={14} />} color="violet">
          <SimpleGrid cols={2} spacing="md">
            <Stat label="Pickup date" value={document.scheduledIssuanceDate ? showDate(document.scheduledIssuanceDate) : null} />
            <Stat label="Document №" value={document.documentNumber} />
            <Stat label="Issued" value={document.issueDate ? showDate(document.issueDate) : null} />
            <Stat label="Valid until" value={document.expiryDate ? showDate(document.expiryDate) : null} />
          </SimpleGrid>
        </SectionCard>
      </SimpleGrid>

      <Modal opened={scheduleOpen} onClose={() => setScheduleOpen(false)} title="Schedule pickup" centered>
        <Stack>
          <AmharicDatePicker label="Pickup date" dateFormat="date" value={pickupDate} onChange={setPickupDate} required />
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setScheduleOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={!pickupDate}
              loading={scheduling}
              onClick={() => run(() => schedule({ id, scheduledDate: pickupDate }).unwrap(), 'Pickup scheduled')}
            >
              Schedule
            </Button>
          </Group>
        </Stack>
      </Modal>

      <Modal opened={rejectOpen} onClose={() => setRejectOpen(false)} title={`Reject ${kindLabel}`} centered>
        <Stack>
          <Textarea label="Reason (shown to the seafarer)" required minRows={3} value={reason} onChange={(e) => setReason(e.currentTarget.value)} data-autofocus />
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setRejectOpen(false)}>
              Cancel
            </Button>
            <Button color="red" disabled={reason.trim().length < 3} loading={rejecting} onClick={() => run(() => reject({ id, reason: reason.trim() }).unwrap(), 'Request rejected')}>
              Confirm
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Container>
  );
}

export default SeafarerDocumentReviewPage;
