import { useState } from 'react';
import { useApiQuery } from '@ema-platform/api';
import { useNavigate } from 'react-router-dom';
import {
  Alert,
  Badge,
  Button,
  Card,
  Divider,
  FileInput,
  Group,
  List,
  Modal,
  Paper,
  SimpleGrid,
  Stack,
  Stepper,
  Text,
  TextInput,
  ThemeIcon,
  Title,
  rem,
} from '@mantine/core';
import {
  IconAlertCircle,
  IconArrowLeft,
  IconArrowRight,
  IconCheck,
  IconCircleCheck,
  IconClock,
  IconDownload,
  IconEye,
  IconFileDescription,
  IconInfoCircle,
  IconRubberStamp,
  IconShieldCheck,
  IconUpload,
} from '@tabler/icons-react';

// ---------------------------------------------------------------------------
// Mock data — existing endorsement applications
// ---------------------------------------------------------------------------
/** What `/endorsements/my` returns. */
interface EndorsementsOverview {
  issued: {
    id: string;
    endorsementNo: string;
    cocType: string;
    foreignCocNo: string;
    issuingCountry: string;
    issued: string;
    expiry: string;
    status: string;
  }[];
  applications: {
    id: string;
    applicationId: string;
    cocType: string;
    foreignCocNo: string;
    issuingCountry: string;
    submitted: string;
    status: string;
  }[];
}

// Keyed by the workflow's own status values so an unmapped one falls back to
// grey rather than rendering colourless.
const STATUS_COLOR: Record<string, string> = {
  DRAFT: 'gray',
  SUBMITTED: 'blue',
  UNDER_REVIEW: 'yellow',
  UNDER_EVALUATION: 'yellow',
  RESUBMIT_REQUIRED: 'orange',
  APPROVED: 'teal',
  REJECTED: 'red',
  PAYMENT_PENDING: 'orange',
  PAYMENT_CONFIRMED: 'blue',
  CERTIFICATE_ISSUED: 'teal',
  COMPLETED: 'teal',
  ACTIVE: 'teal',
  EXPIRED: 'red',
  SUSPENDED: 'orange',
};

function humanStatus(status: string): string {
  return status
    .toLowerCase()
    .split('_')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

function formatDate(value: string | null | undefined): string {
  if (!value) return '—';
  return new Date(value).toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });
}

// blank PDF
const BLANK_PDF = 'data:application/pdf;base64,JVBERi0xLjQKJcfsj6IKMSAwIG9iago8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFI+PgplbmRvYmoKMiAwIG9iago8PC9UeXBlL1BhZ2VzL0tpZHNbMyAwIFJdL0NvdW50IDE+PgplbmRvYmoKMyAwIG9iago8PC9UeXBlL1BhZ2UvUGFyZW50IDIgMCBSL01lZGlhQm94WzAgMCA2MTIgNzkyXT4+CmVuZG9iagp4cmVmCjAgNAowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMDkgMDAwMDAgbiAKMDAwMDAwMDA1OCAwMDAwMCBuIAowMDAwMDAwMTE1IDAwMDAwIG4gCnRyYWlsZXIKPDwvU2l6ZSA0L1Jvb3QgMSAwIFI+PgpzdGFydHhyZWYKMjE3CiUlRU9G';

// ---------------------------------------------------------------------------
// Application wizard
// ---------------------------------------------------------------------------
interface Docs {
  foreignCoc: File | null;
  translation: File | null;
  medical: File | null;
  seamanBook: File | null;
  photo: File | null;
}

function ApplicationWizard({ onDone }: { onDone: () => void }) {
  const [step, setStep] = useState(0);
  const [cocNo, setCocNo] = useState('');
  const [issuer, setIssuer] = useState('');
  const [country, setCountry] = useState('');
  const [cocType, setCocType] = useState('');
  const [issueDate, setIssueDate] = useState('');
  const [expiryDate, setExpiryDate] = useState('');
  const [docs, setDocs] = useState<Docs>({ foreignCoc: null, translation: null, medical: null, seamanBook: null, photo: null });
  const [submitted, setSubmitted] = useState(false);

  const step0Ok = !!cocNo && !!issuer && !!country && !!cocType && !!issueDate && !!expiryDate;
  const step1Ok = !!docs.foreignCoc && !!docs.medical && !!docs.seamanBook && !!docs.photo;

  if (submitted) {
    return (
      <Stack gap="lg" align="center" py="xl">
        <ThemeIcon size={72} radius="xl" color="teal" variant="light"><IconCircleCheck size={40} /></ThemeIcon>
        <Title order={3} ta="center">Application Submitted</Title>
        <Text c="dimmed" ta="center" maw={400}>
          Your endorsement application has been submitted. EMA officers will verify your documents
          and notify you of the outcome. Reference: <strong>END-APP-2025-NEW</strong>
        </Text>
        <Button onClick={onDone}>Back to Endorsements</Button>
      </Stack>
    );
  }

  return (
    <Stack gap="lg">
      <Stepper active={step} size="sm">
        <Stepper.Step label="Foreign CoC Details"   description="Certificate information" />
        <Stepper.Step label="Upload Documents"       description="Required documents" />
        <Stepper.Step label="Payment"                description="Pay endorsement fee" />
        <Stepper.Step label="Review & Submit"        description="Final check" />
      </Stepper>

      {/* Step 0 — Foreign CoC details */}
      {step === 0 && (
        <Paper withBorder radius="lg" p="xl">
          <Alert variant="light" color="blue" icon={<IconInfoCircle size={15} />} mb="lg">
            <Text fz="sm">
              <strong>STCW Regulation I/10</strong> — EMA will endorse your foreign CoC so it is
              recognised for service on Ethiopian-flagged vessels. The endorsement is valid
              for the same period as your foreign CoC.
            </Text>
          </Alert>
          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
            <TextInput label="Foreign CoC Number" placeholder="e.g. PHL-COC-2022-0045" value={cocNo} onChange={(e) => setCocNo(e.currentTarget.value)} required />
            <TextInput label="Issuing Country" placeholder="e.g. Philippines" value={country} onChange={(e) => setCountry(e.currentTarget.value)} required />
            <TextInput label="Issuing Authority / Administration" placeholder="e.g. Maritime Industry Authority (MARINA)" value={issuer} onChange={(e) => setIssuer(e.currentTarget.value)} required />
            <TextInput label="Certificate Type" placeholder="e.g. Officer in Charge of a Navigational Watch" value={cocType} onChange={(e) => setCocType(e.currentTarget.value)} required />
            <TextInput label="Issue Date" type="date" value={issueDate} onChange={(e) => setIssueDate(e.currentTarget.value)} required />
            <TextInput label="Expiry Date" type="date" value={expiryDate} onChange={(e) => setExpiryDate(e.currentTarget.value)} required />
          </SimpleGrid>
        </Paper>
      )}

      {/* Step 1 — Documents */}
      {step === 1 && (
        <Stack gap="md">
          <Alert variant="light" color="yellow" icon={<IconAlertCircle size={15} />}>
            <Text fz="sm">
              A <strong>certified translation</strong> is required if your foreign CoC is not in English.
              All documents must be clear, legible, and complete.
            </Text>
          </Alert>

          <Paper withBorder radius="lg" p="xl">
            <Text fw={700} mb="md">Required Documents</Text>
            <Stack gap="md">
              {[
                { key: 'foreignCoc' as keyof Docs, label: 'Foreign CoC (Original or Certified Copy)',           required: true  },
                { key: 'translation' as keyof Docs, label: 'Certified Translation (only if CoC is not in English)', required: false },
                { key: 'medical' as keyof Docs,    label: 'Valid Medical Fitness Certificate (STCW Reg I/2)',   required: true  },
                { key: 'seamanBook' as keyof Docs, label: 'Ethiopian Seaman Book',                              required: true  },
                { key: 'photo' as keyof Docs,      label: 'Passport-Size Photo',                                required: true  },
              ].map((slot) => (
                <FileInput
                  key={slot.key}
                  label={<Group gap={4}><Text fz="sm" fw={500}>{slot.label}</Text>{slot.required && <Badge size="xs" color="red" variant="light">Required</Badge>}</Group>}
                  placeholder="Click to upload"
                  leftSection={<IconUpload size={14} />}
                  value={docs[slot.key]}
                  onChange={(f) => setDocs((prev) => ({ ...prev, [slot.key]: f }))}
                  accept=".pdf,.jpg,.jpeg,.png"
                  clearable
                />
              ))}
            </Stack>
          </Paper>

          {/* Upload checklist */}
          <Paper withBorder radius="md" p="md" bg="gray.0">
            <Text fz="xs" fw={700} mb="sm" tt="uppercase" c="dimmed">Upload Checklist</Text>
            <Stack gap={4}>
              {[
                { label: 'Foreign CoC',    done: !!docs.foreignCoc },
                { label: 'Medical Cert',   done: !!docs.medical },
                { label: 'Seaman Book',    done: !!docs.seamanBook },
                { label: 'Photo',          done: !!docs.photo },
              ].map((item) => (
                <Group key={item.label} gap="xs">
                  <ThemeIcon size={18} radius="xl" color={item.done ? 'teal' : 'gray'} variant={item.done ? 'filled' : 'light'}>
                    {item.done ? <IconCheck size={11} /> : <IconFileDescription size={11} />}
                  </ThemeIcon>
                  <Text fz="xs" c={item.done ? undefined : 'dimmed'}>{item.label}</Text>
                </Group>
              ))}
            </Stack>
          </Paper>
        </Stack>
      )}

      {/* Step 2 — Payment */}
      {step === 2 && (
        <Paper withBorder radius="lg" p="xl">
          <Text fw={700} mb="md">Endorsement Fee</Text>
          <Paper withBorder radius="md" p="md" bg="gray.0" mb="lg">
            {[
              { label: 'Application Processing Fee', amount: 300 },
              { label: 'Document Verification Fee',  amount: 200 },
              { label: 'Endorsement Issuance Fee',   amount: 500 },
            ].map(({ label, amount }) => (
              <Group key={label} justify="space-between" mb="xs">
                <Text fz="sm">{label}</Text>
                <Text fz="sm" fw={600}>ETB {amount}</Text>
              </Group>
            ))}
            <Divider my="xs" />
            <Group justify="space-between">
              <Text fw={800}>Total</Text>
              <Text fw={800} fz="lg" c="blue">ETB 1,000</Text>
            </Group>
          </Paper>
          <Alert variant="light" color="blue" icon={<IconInfoCircle size={15} />}>
            <Text fz="sm">
              Transfer the fee to <strong>CBE Account: 1000-XXXXX-EMA</strong> and upload the receipt below.
            </Text>
          </Alert>
          <FileInput label="Payment Receipt" placeholder="Upload bank transfer receipt" leftSection={<IconUpload size={14} />} mt="md" accept=".pdf,.jpg,.jpeg,.png" />
        </Paper>
      )}

      {/* Step 3 — Review */}
      {step === 3 && (
        <Paper withBorder radius="lg" p="xl">
          <Text fw={700} mb="lg">Review Your Application</Text>
          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md" mb="lg">
            {[
              ['CoC Number',  cocNo],
              ['Country',     country],
              ['Issuer',      issuer],
              ['CoC Type',    cocType],
              ['Issue Date',  issueDate],
              ['Expiry Date', expiryDate],
            ].map(([label, value]) => (
              <div key={label}>
                <Text fz="xs" c="dimmed" tt="uppercase" fw={600}>{label}</Text>
                <Text fz="sm" fw={500}>{value || '—'}</Text>
              </div>
            ))}
          </SimpleGrid>
          <Divider mb="md" />
          <Text fz="xs" fw={700} tt="uppercase" c="dimmed" mb="xs">Uploaded Documents</Text>
          <List spacing="xs" size="sm">
            {[
              { label: 'Foreign CoC',         file: docs.foreignCoc },
              { label: 'Medical Certificate', file: docs.medical },
              { label: 'Seaman Book',         file: docs.seamanBook },
              { label: 'Photo',               file: docs.photo },
              { label: 'Translation',         file: docs.translation },
            ].map(({ label, file }) => file && (
              <List.Item key={label} icon={<ThemeIcon size={18} radius="xl" color="teal" variant="filled"><IconCheck size={11} /></ThemeIcon>}>
                <Text fz="sm">{label}: <Text span c="blue.7">{file.name}</Text></Text>
              </List.Item>
            ))}
          </List>
          <Alert variant="light" color="blue" icon={<IconInfoCircle size={14} />} mt="lg">
            <Text fz="xs">
              By submitting you confirm that all information is accurate and the documents are genuine.
              Providing false information is an offence under the Maritime Code.
            </Text>
          </Alert>
        </Paper>
      )}

      {/* Navigation */}
      <Group justify="space-between" mt="md">
        <Button variant="default" leftSection={<IconArrowLeft size={14} />} onClick={() => setStep(s => s - 1)} disabled={step === 0}>
          Back
        </Button>
        {step < 3 ? (
          <Button
            rightSection={<IconArrowRight size={14} />}
            disabled={(step === 0 && !step0Ok) || (step === 1 && !step1Ok)}
            onClick={() => setStep(s => s + 1)}
          >
            Next
          </Button>
        ) : (
          <Button color="teal" leftSection={<IconCircleCheck size={14} />} onClick={() => setSubmitted(true)}>
            Submit Application
          </Button>
        )}
      </Group>
    </Stack>
  );
}

// ---------------------------------------------------------------------------
// Main page
// ---------------------------------------------------------------------------
export function EndorsementPage() {
  const navigate = useNavigate();
  const [applying, setApplying] = useState(false);
  const [previewId, setPreviewId] = useState<string | null>(null);

  const { data } = useApiQuery<EndorsementsOverview>({
    url: '/endorsements/my',
    method: 'GET',
  });
  const endorsementApps = data?.applications ?? [];
  const issuedEndorsements = data?.issued ?? [];

  if (applying) {
    return (
      <Stack gap="md">
        <Group gap="sm">
          <Button variant="subtle" leftSection={<IconArrowLeft size={14} />} onClick={() => setApplying(false)}>Back</Button>
          <div>
            <Title order={3}>Apply for Endorsement</Title>
            <Text fz="sm" c="dimmed">STCW Reg I/10 — Flag State Endorsement of Foreign CoC</Text>
          </div>
        </Group>
        <ApplicationWizard onDone={() => setApplying(false)} />
      </Stack>
    );
  }

  return (
    <Stack gap="md">
      <Group justify="space-between" align="flex-start" wrap="wrap" gap="sm">
        <div>
          <Title order={3}>Endorsements</Title>
          <Text fz="sm" c="dimmed">STCW Reg I/10 — Flag-state endorsement of foreign-issued Certificates of Competency</Text>
        </div>
        <Button leftSection={<IconRubberStamp size={15} />} rightSection={<IconArrowRight size={15} />} onClick={() => setApplying(true)}>
          Apply for Endorsement
        </Button>
      </Group>

      {/* Info panel */}
      <Paper withBorder radius="lg" p="md" bg="var(--mantine-color-blue-light)">
        <Group gap="md" wrap="nowrap">
          <ThemeIcon size={48} radius="md" color="blue" variant="light"><IconRubberStamp size={24} /></ThemeIcon>
          <Stack gap={2} style={{ flex: 1 }}>
            <Text fw={700} fz="sm">What is an Endorsement?</Text>
            <SimpleGrid cols={{ base: 1, sm: 3 }} spacing="xs">
              {[
                { icon: IconShieldCheck, color: 'blue',   title: 'Flag-State Recognition',   desc: 'Under STCW Reg I/10, Ethiopia (flag state) must endorse foreign CoC certificates before a seafarer can serve on Ethiopian-flagged vessels.' },
                { icon: IconCircleCheck, color: 'teal',   title: 'Co-Terminous Validity',    desc: 'The endorsement is valid for the same period as your foreign CoC. It must be revalidated whenever the foreign CoC is revalidated.' },
                { icon: IconClock,       color: 'orange', title: 'Processing Time',           desc: 'Typical processing time is 10–15 working days after all documents are verified.' },
              ].map(({ icon: Icon, color, title, desc }) => (
                <Card key={title} withBorder radius="md" p="sm">
                  <Group gap="xs" mb={4}>
                    <ThemeIcon size={20} radius="sm" color={color} variant="light"><Icon size={12} /></ThemeIcon>
                    <Text fz="xs" fw={700}>{title}</Text>
                  </Group>
                  <Text fz="xs" c="dimmed" lh={1.4}>{desc}</Text>
                </Card>
              ))}
            </SimpleGrid>
          </Stack>
        </Group>
      </Paper>

      {/* Active applications */}
      <Paper withBorder radius="lg" p="xl">
        <Text fw={700} mb="md">My Endorsement Applications</Text>
        {endorsementApps.length === 0 ? (
          <Alert variant="light" color="gray" icon={<IconInfoCircle size={15} />}>
            No active endorsement applications.
          </Alert>
        ) : (
          <Stack gap="sm">
            {endorsementApps.map((app) => (
              <Paper key={app.id} withBorder radius="md" p="md">
                <Group justify="space-between" wrap="wrap" gap="sm">
                  <Group gap="sm" wrap="nowrap">
                    <ThemeIcon size={36} radius="md" color="blue" variant="light"><IconRubberStamp size={18} /></ThemeIcon>
                    <div>
                      <Text fz="sm" fw={700}>{app.cocType}</Text>
                      <Text fz="xs" c="dimmed">CoC No: {app.foreignCocNo} · {app.issuingCountry} · Submitted {formatDate(app.submitted)}</Text>
                    </div>
                  </Group>
                  <Group gap="xs">
                    <Badge color={STATUS_COLOR[app.status] ?? "gray"} variant="light">{humanStatus(app.status)}</Badge>
                    <Text fz="xs" c="blue.7" fw={600}>{app.id}</Text>
                  </Group>
                </Group>
                <Alert variant="light" color={STATUS_COLOR[app.status] ?? "gray"} icon={<IconInfoCircle size={13} />} p="xs" mt="sm">
                  <Text fz="xs">{humanStatus(app.status)}</Text>
                </Alert>
              </Paper>
            ))}
          </Stack>
        )}
      </Paper>

      {/* Issued endorsements */}
      <Paper withBorder radius="lg" p="xl">
        <Text fw={700} mb="md">My Endorsements</Text>
        {issuedEndorsements.length === 0 ? (
          <Alert variant="light" color="gray" icon={<IconInfoCircle size={15} />}>
            No endorsements issued yet.
          </Alert>
        ) : (
          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
            {issuedEndorsements.map((end) => (
              <Card key={end.id} withBorder radius="md" p="md">
                <Group justify="space-between" mb="sm">
                  <Group gap="sm">
                    <ThemeIcon size={36} radius="md" color="teal" variant="light"><IconRubberStamp size={18} /></ThemeIcon>
                    <div>
                      <Text fw={700} fz="sm">{end.cocType}</Text>
                      <Text fz="xs" c="dimmed">{end.endorsementNo}</Text>
                    </div>
                  </Group>
                  <Badge color={STATUS_COLOR[end.status] ?? "gray"} variant="light">{humanStatus(end.status)}</Badge>
                </Group>
                <Divider mb="sm" />
                <SimpleGrid cols={2} spacing="xs" mb="sm">
                  <div><Text fz="xs" c="dimmed">Foreign CoC No.</Text><Text fz="sm" fw={500}>{end.foreignCocNo}</Text></div>
                  <div><Text fz="xs" c="dimmed">Issuing Country</Text><Text fz="sm" fw={500}>{end.issuingCountry}</Text></div>
                  <div><Text fz="xs" c="dimmed">Issued</Text><Text fz="sm" fw={500}>{end.issued}</Text></div>
                  <div><Text fz="xs" c="dimmed">Expires</Text><Text fz="sm" fw={500}>{end.expiry}</Text></div>
                </SimpleGrid>
                <Group gap="xs">
                  <Button size="xs" variant="light" leftSection={<IconEye size={12} />} onClick={() => setPreviewId(end.id)}>View</Button>
                  <Button size="xs" variant="default" leftSection={<IconDownload size={12} />}>Download</Button>
                </Group>
              </Card>
            ))}
          </SimpleGrid>
        )}
      </Paper>

      {/* Preview modal */}
      <Modal
        opened={!!previewId}
        onClose={() => setPreviewId(null)}
        title={<Text fw={700} fz="sm">Endorsement Certificate</Text>}
        size="xl"
        radius="lg"
      >
        <iframe src={BLANK_PDF} style={{ width: '100%', height: '70vh', border: 'none', borderRadius: rem(8) }} title="Endorsement" />
      </Modal>
    </Stack>
  );
}
