import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useApiMutation } from '@ema-platform/api';
import {
  Alert,
  Badge,
  Box,
  Button,
  Card,
  Divider,
  FileButton,
  Group,
  NumberInput,
  Paper,
  Select,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
  ThemeIcon,
  Title,
  rem,
} from '@mantine/core';
import {
  IconAnchor,
  IconArrowLeft,
  IconArrowRight,
  IconCamera,
  IconCheck,
  IconCircleCheck,
  IconFileDescription,
  IconId,
  IconInfoCircle,
  IconShieldCheck,
  IconShip,
  IconWaveSine,
} from '@tabler/icons-react';
import { notify, PhoneInput } from '@ema-platform/ui';
import { isValidPhoneNumber } from 'libphonenumber-js';

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const STEPS = [
  { label: 'Vessel Category' },
  { label: 'Vessel Details' },
  { label: 'Technical & Ownership' },
  { label: 'Documents Upload' },
  { label: 'Review & Submit' },
];

const VESSEL_TYPES_INLAND = [
  'Passenger Ferry', 'Cargo Barge', 'Fishing Vessel', 'Tug Boat',
  'Dredger', 'Patrol/Inspection Boat', 'Pleasure Craft', 'Water Taxi',
];

const VESSEL_TYPES_SEAGOING = [
  'Container Ship', 'Bulk Carrier', 'Tanker', 'General Cargo',
  'Ro-Ro Vessel', 'Passenger/Cruise Ship', 'Fishing Vessel', 'Trawler',
  'Yacht/Pleasure Craft', 'Chemical Tanker', 'LPG Carrier', 'Multi-Purpose Vessel',
];

const ENGINE_TYPES = [
  'Diesel Engine', 'Dual-Fuel Engine', 'Electric Motor', 'Hybrid Diesel-Electric',
  'Steam Turbine', 'Gas Turbine', 'Outboard Motor', 'Inboard Petrol Engine',
];

const HULL_MATERIALS = [
  'Steel', 'Aluminum', 'Fiberglass/GRP', 'Wood', 'Ferro-Cement',
];

const PASSENGER_VESSEL_TYPES = new Set([
  'Passenger Ferry', 'Passenger/Cruise Ship', 'Water Taxi', 'Yacht/Pleasure Craft', 'Pleasure Craft',
]);

interface DocSlot {
  key: string;
  label: string;
  description: string;
  required: boolean;
  icon: typeof IconId;
}

// ---------------------------------------------------------------------------
// Step indicator (matches SeafarerRegistrationPage pattern)
// ---------------------------------------------------------------------------
function StepIndicator({ active, completed }: { active: number; completed: number[] }) {
  return (
    <Box mb={32}>
      <Group gap={0} align="center" wrap="nowrap">
        {STEPS.map((step, i) => {
          const isDone = completed.includes(i);
          const isCurrent = active === i;
          return (
            <Group key={i} gap={0} align="center" style={{ flex: i < STEPS.length - 1 ? 1 : 'none' }}>
              <Stack gap={4} align="center" style={{ minWidth: rem(40) }}>
                <Box
                  style={{
                    width: rem(40),
                    height: rem(40),
                    borderRadius: '50%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: isDone
                      ? 'var(--mantine-color-blue-8)'
                      : isCurrent
                      ? 'var(--mantine-color-blue-7)'
                      : 'var(--mantine-color-gray-1)',
                    border: isCurrent ? '2.5px solid var(--mantine-color-blue-5)' : '2px solid transparent',
                    boxShadow: isCurrent || isDone ? '0 2px 8px rgba(34, 139, 230, 0.2)' : 'none',
                    flexShrink: 0,
                    transition: 'all 0.2s ease',
                  }}
                >
                  {isDone ? (
                    <IconCheck size={18} color="white" stroke={2.5} />
                  ) : (
                    <Text fw={700} fz="sm" c={isCurrent ? 'white' : 'gray.5'}>
                      {i + 1}
                    </Text>
                  )}
                </Box>
                <Text
                  fz="xs"
                  fw={isCurrent ? 700 : 400}
                  c={isCurrent ? 'blue.7' : 'dimmed'}
                  style={{ whiteSpace: 'nowrap' }}
                >
                  {isDone ? `${step.label} ✓` : step.label}
                </Text>
              </Stack>

              {i < STEPS.length - 1 && (
                <Box
                  style={{
                    flex: 1,
                    height: rem(2),
                    backgroundColor: isDone
                      ? 'var(--mantine-color-blue-8)'
                      : 'var(--mantine-color-gray-2)',
                    marginBottom: rem(22),
                  }}
                />
              )}
            </Group>
          );
        })}
      </Group>
    </Box>
  );
}

function SectionHead({ title }: { title: string }) {
  return (
    <>
      <Divider mt="md" mb="xs" />
      <Text fw={600} fz="sm" tt="uppercase" c="gray.6">{title}</Text>
    </>
  );
}

function ReviewRow({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <Text fz="xs" c="dimmed" tt="uppercase" fw={600} lh={1.2}>{label}</Text>
      <Text fz="sm" mt={2}>{value || '—'}</Text>
    </div>
  );
}

function DocCard({
  slot,
  file,
  onFile,
}: {
  slot: DocSlot;
  file: File | null;
  onFile: (f: File | null) => void;
}) {
  const resetRef = useRef<() => void>(null);
  const SlotIcon = slot.icon;
  return (
    <Card
      withBorder
      radius="md"
      p="md"
      style={{
        borderStyle: 'dashed',
        borderColor: file
          ? 'var(--mantine-color-teal-5)'
          : 'var(--mantine-color-default-border)',
      }}
    >
      <Group gap="sm" mb="sm" wrap="nowrap">
        <Box
          style={{
            width: rem(44),
            height: rem(44),
            borderRadius: rem(8),
            background: 'var(--mantine-color-blue-light)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
          }}
        >
          <SlotIcon size={22} color="var(--mantine-color-blue-6)" stroke={1.5} />
        </Box>
        <div>
          <Text fw={600} fz="sm">
            {slot.label}
            {slot.required && <Text span c="red" ml={3}>*</Text>}
          </Text>
          <Text fz="xs" c="dimmed">{slot.description}</Text>
        </div>
      </Group>

      {file ? (
        <Group gap="xs" align="center">
          <IconCircleCheck size={16} color="var(--mantine-color-teal-6)" />
          <Text fz="xs" c="teal.7" style={{ flex: 1 }} truncate>{file.name}</Text>
          <Button
            size="xs"
            variant="subtle"
            color="red"
            onClick={() => { onFile(null); resetRef.current?.(); }}
          >
            Remove
          </Button>
        </Group>
      ) : (
        <FileButton resetRef={resetRef} onChange={onFile} accept="application/pdf,image/jpeg,image/png">
          {(props) => (
            <Button size="xs" variant="default" {...props}>
              Choose File
            </Button>
          )}
        </FileButton>
      )}
    </Card>
  );
}

// ---------------------------------------------------------------------------
// Main page
// ---------------------------------------------------------------------------
export function VesselRegistrationApplicationPage() {
  const navigate = useNavigate();
  const [submitTrigger] = useApiMutation<{ id: string }>();
  const [active, setActive] = useState(0);
  const [completed, setCompleted] = useState<number[]>([]);
  const [submitting, setSubmitting] = useState(false);

  // Step 0 — Category
  const [category, setCategory] = useState<string | null>(null);

  // Step 1 — Vessel Details
  const [vesselName, setVesselName] = useState('');
  const [vesselType, setVesselType] = useState<string | null>(null);
  const [capacityValue, setCapacityValue] = useState<string | number>('');
  const [vesselLengthM, setVesselLengthM] = useState<string | number>('');
  const [flagState, setFlagState] = useState('Ethiopia');
  const [portOfRegistry, setPortOfRegistry] = useState('');

  // Step 2 — Technical & Ownership
  const [imoOrHullNumber, setImoOrHullNumber] = useState('');
  const [manufacturerShipyard, setManufacturerShipyard] = useState('');
  const [yearBuilt, setYearBuilt] = useState<string | number>('');
  const [engineType, setEngineType] = useState<string | null>(null);
  const [enginePowerKw, setEnginePowerKw] = useState<string | number>('');
  const [numberOfEngines, setNumberOfEngines] = useState<string | number>('');
  const [hullMaterial, setHullMaterial] = useState<string | null>(null);
  const [ownerName, setOwnerName] = useState('');
  const [ownerNationalIdOrTin, setOwnerNationalIdOrTin] = useState('');
  const [ownerPhone, setOwnerPhone] = useState('');
  const [ownerAddress, setOwnerAddress] = useState('');

  // Step 3 — Documents
  const [files, setFiles] = useState<Record<string, File | null>>({
    vesselPhotos: null, proofOfOwnership: null, shipParticulars: null, insuranceCertificate: null,
  });
  const setFile = (key: string) => (f: File | null) => setFiles((prev) => ({ ...prev, [key]: f }));

  // Reset vessel type when category changes
  useEffect(() => { setVesselType(null); }, [category]);

  // Derived
  const vesselTypeOptions = category === 'Inland Waterway Vessel' ? VESSEL_TYPES_INLAND : VESSEL_TYPES_SEAGOING;
  const capacityLabel = PASSENGER_VESSEL_TYPES.has(vesselType ?? '') ? 'Passenger Capacity' : 'Gross Tonnage (GT)';
  const idLabel = category === 'Sea-going Vessel (International)' ? 'IMO Number' : 'Hull/Registration Number';

  // Inland: only vessel photos required
  // Sea-going: vessel photos + proof of ownership + ship particulars + insurance
  const docSlots: DocSlot[] = category === 'Inland Waterway Vessel'
    ? [
        { key: 'vesselPhotos', label: 'Vessel Photos (min. 2)', description: 'Clear exterior and interior photos of the vessel', required: true, icon: IconCamera },
      ]
    : [
        { key: 'vesselPhotos', label: 'Vessel Photos (min. 2)', description: 'Clear exterior and interior photos of the vessel', required: true, icon: IconCamera },
        { key: 'proofOfOwnership', label: 'Proof of Ownership / Bill of Sale', description: 'Legal document proving ownership of the vessel', required: true, icon: IconFileDescription },
        { key: 'shipParticulars', label: 'Ship Particulars', description: 'Detailed technical specifications issued by the shipyard', required: true, icon: IconId },
        { key: 'insuranceCertificate', label: 'Insurance Certificate', description: 'Valid hull and machinery insurance policy', required: true, icon: IconShieldCheck },
      ];

  const canNext = () => {
    if (active === 0) return !!category;
    if (active === 1) return (
      !!vesselName.trim() && !!vesselType && !!capacityValue && !!vesselLengthM &&
      !!flagState.trim() && !!portOfRegistry.trim()
    );
    if (active === 2) return (
      !!imoOrHullNumber.trim() && !!manufacturerShipyard.trim() && !!yearBuilt &&
      !!engineType && !!enginePowerKw && !!numberOfEngines && !!hullMaterial &&
      !!ownerName.trim() && !!ownerNationalIdOrTin.trim() && isValidPhoneNumber(ownerPhone)
    );
    if (active === 3) return category === 'Inland Waterway Vessel'
      ? !!files.vesselPhotos
      : !!files.vesselPhotos && !!files.proofOfOwnership && !!files.shipParticulars && !!files.insuranceCertificate;
    return true;
  };

  const next = () => {
    setCompleted((prev) => prev.includes(active) ? prev : [...prev, active]);
    setActive((c) => c + 1);
  };
  const prev = () => setActive((c) => c - 1);

  const handleSubmit = async () => {
    setSubmitting(true);
    try {
      await submitTrigger({
        url: '/vessel-registrations',
        method: 'POST',
        body: {
          category, vesselName, vesselType, capacityLabel, capacityValue, vesselLengthM,
          flagState, portOfRegistry, imoOrHullNumber, manufacturerShipyard, yearBuilt,
          engineType, enginePowerKw, numberOfEngines, hullMaterial,
          ownerName, ownerNationalIdOrTin, ownerPhone, ownerAddress,
        },
      }).unwrap();
      notify.success('Vessel registration submitted successfully!');
      navigate('/vessel-registration');
    } catch {
      notify.error('Submission failed. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Stack gap="md">
      <Group gap="xs">
        <Button variant="subtle" size="xs" leftSection={<IconArrowLeft size={14} />} onClick={() => navigate('/vessel-registration')}>
          Back
        </Button>
      </Group>

      <div>
        <Title order={3}>Vessel Registration Application</Title>
        <Text fz="sm" c="dimmed">Step {active + 1} of {STEPS.length} — {STEPS[active].label}</Text>
      </div>

      <StepIndicator active={active} completed={completed} />

      <Paper withBorder radius="lg" p="xl">
        <Group justify="space-between" mb="lg">
          <Text fw={700} fz="lg">{STEPS[active].label}</Text>
          <Badge variant="light" color="blue" radius="md">Step {active + 1} of {STEPS.length}</Badge>
        </Group>

        {/* ── Step 0: Vessel Category ──────────────────────────────── */}
        {active === 0 && (
          <Stack gap="md">
            <Text fz="sm" c="dimmed">Select the primary use category of the vessel to be registered.</Text>
            <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
              {[
                {
                  value: 'Inland Waterway Vessel',
                  icon: IconWaveSine,
                  title: 'Inland Waterway Vessel',
                  desc: 'Vessels operating on lakes, rivers, and inland waterways within Ethiopia (e.g. Lake Tana, Hawassa, Blue Nile)',
                },
                {
                  value: 'Sea-going Vessel (International)',
                  icon: IconShip,
                  title: 'Sea-going Vessel (International)',
                  desc: 'Vessels operating in international waters, Red Sea, Gulf of Aden, and ocean routes',
                },
              ].map((opt) => {
                const Icon = opt.icon;
                const selected = category === opt.value;
                return (
                  <Card
                    key={opt.value}
                    withBorder
                    radius="md"
                    p="lg"
                    style={{
                      cursor: 'pointer',
                      borderColor: selected ? 'var(--mantine-color-blue-5)' : 'var(--mantine-color-default-border)',
                      borderWidth: selected ? 2 : 1,
                      background: selected ? 'var(--mantine-color-blue-light)' : undefined,
                      transition: 'all 0.15s ease',
                    }}
                    onClick={() => { setCategory(opt.value); next(); }}
                  >
                    <ThemeIcon size={48} radius="md" color="blue" variant={selected ? 'filled' : 'light'} mb="sm">
                      <Icon size={26} />
                    </ThemeIcon>
                    <Text fw={700} fz="md" mb={4}>{opt.title}</Text>
                    <Text fz="sm" c="dimmed">{opt.desc}</Text>
                  </Card>
                );
              })}
            </SimpleGrid>
          </Stack>
        )}

        {/* ── Step 1: Vessel Details ───────────────────────────────── */}
        {active === 1 && (
          <Stack gap="md">
            <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
              Category: <strong>{category}</strong>
            </Alert>
            <SectionHead title="Vessel Identification" />
            <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
              <TextInput
                label="Vessel Name"
                placeholder="e.g. Lake Tana Star"
                required
                value={vesselName}
                onChange={(e) => setVesselName(e.currentTarget.value)}
              />
              <Select
                label="Vessel Type"
                placeholder="Select vessel type"
                required
                data={vesselTypeOptions}
                value={vesselType}
                onChange={setVesselType}
              />
              <NumberInput
                label={capacityLabel}
                placeholder="Enter value"
                required
                min={1}
                value={capacityValue}
                onChange={setCapacityValue}
              />
              <NumberInput
                label="Vessel Length (meters)"
                placeholder="e.g. 32"
                required
                min={1}
                value={vesselLengthM}
                onChange={setVesselLengthM}
              />
              <TextInput
                label="Flag State"
                required
                value={flagState}
                onChange={(e) => setFlagState(e.currentTarget.value)}
              />
              <TextInput
                label="Registration Area"
                placeholder="e.g. Bahir Dar"
                required
                value={portOfRegistry}
                onChange={(e) => setPortOfRegistry(e.currentTarget.value)}
              />
            </SimpleGrid>
          </Stack>
        )}

        {/* ── Step 2: Technical & Ownership ───────────────────────── */}
        {active === 2 && (
          <Stack gap="md">
            <SectionHead title="Technical Specifications" />
            <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
              <TextInput
                label={idLabel}
                placeholder={category === 'Sea-going Vessel (International)' ? 'IMO0000000' : 'ETH-INL-0000'}
                required
                value={imoOrHullNumber}
                onChange={(e) => setImoOrHullNumber(e.currentTarget.value)}
              />
              <TextInput
                label="Manufacturer / Shipyard Name"
                placeholder="e.g. Hyundai Heavy Industries"
                required
                value={manufacturerShipyard}
                onChange={(e) => setManufacturerShipyard(e.currentTarget.value)}
              />
              <NumberInput
                label="Year Built"
                placeholder="e.g. 2019"
                required
                min={1900}
                max={new Date().getFullYear()}
                value={yearBuilt}
                onChange={setYearBuilt}
              />
              <Select
                label="Engine Type"
                placeholder="Select engine type"
                required
                data={ENGINE_TYPES}
                value={engineType}
                onChange={setEngineType}
              />
              <NumberInput
                label="Engine Power (kW)"
                placeholder="e.g. 450"
                required
                min={1}
                value={enginePowerKw}
                onChange={setEnginePowerKw}
              />
              <NumberInput
                label="Number of Engines"
                placeholder="e.g. 2"
                required
                min={1}
                max={12}
                value={numberOfEngines}
                onChange={setNumberOfEngines}
              />
              <Select
                label="Hull Material"
                placeholder="Select material"
                required
                data={HULL_MATERIALS}
                value={hullMaterial}
                onChange={setHullMaterial}
              />
            </SimpleGrid>

            <SectionHead title="Owner Information" />
            <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
              <TextInput
                label="Owner Name / Company"
                placeholder="e.g. Abebe Girma"
                required
                value={ownerName}
                onChange={(e) => setOwnerName(e.currentTarget.value)}
              />
              <TextInput
                label="National ID / TIN"
                placeholder="e.g. ET-9812345"
                required
                value={ownerNationalIdOrTin}
                onChange={(e) => setOwnerNationalIdOrTin(e.currentTarget.value)}
              />
              <PhoneInput
                label="Owner Phone"
                required
                value={ownerPhone}
                onChange={setOwnerPhone}
              />
              <TextInput
                label="Owner Address"
                placeholder="City, Region"
                value={ownerAddress}
                onChange={(e) => setOwnerAddress(e.currentTarget.value)}
                style={{ gridColumn: 'span 2' }}
              />
            </SimpleGrid>
          </Stack>
        )}

        {/* ── Step 3: Documents Upload ─────────────────────────────── */}
        {active === 3 && (
          <Stack gap="md">
            <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
              Upload clear scans or photos. Accepted formats: PDF, JPG, PNG. Max 5MB per file.
            </Alert>
            <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
              {docSlots.map((slot) => (
                <DocCard key={slot.key} slot={slot} file={files[slot.key]} onFile={setFile(slot.key)} />
              ))}
            </SimpleGrid>
          </Stack>
        )}

        {/* ── Step 4: Review & Submit ──────────────────────────────── */}
        {active === 4 && (
          <Stack gap="md">
            <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
              Please review all information before submitting. You will be notified by the authority on application status.
            </Alert>

            <Paper withBorder radius="md" p="md">
              <Text fw={700} fz="sm" mb="sm">Vessel Information</Text>
              <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
                <ReviewRow label="Category" value={category ?? ''} />
                <ReviewRow label="Vessel Name" value={vesselName} />
                <ReviewRow label="Vessel Type" value={vesselType ?? ''} />
                <ReviewRow label={capacityLabel} value={String(capacityValue)} />
                <ReviewRow label="Vessel Length (m)" value={String(vesselLengthM)} />
                <ReviewRow label="Flag State" value={flagState} />
                <ReviewRow label="Registration Area" value={portOfRegistry} />
              </SimpleGrid>
            </Paper>

            <Paper withBorder radius="md" p="md">
              <Text fw={700} fz="sm" mb="sm">Technical Details</Text>
              <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
                <ReviewRow label={idLabel} value={imoOrHullNumber} />
                <ReviewRow label="Manufacturer / Shipyard" value={manufacturerShipyard} />
                <ReviewRow label="Year Built" value={String(yearBuilt)} />
                <ReviewRow label="Engine Type" value={engineType ?? ''} />
                <ReviewRow label="Engine Power (kW)" value={String(enginePowerKw)} />
                <ReviewRow label="Number of Engines" value={String(numberOfEngines)} />
                <ReviewRow label="Hull Material" value={hullMaterial ?? ''} />
              </SimpleGrid>
            </Paper>

            <Paper withBorder radius="md" p="md">
              <Text fw={700} fz="sm" mb="sm">Owner Information</Text>
              <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
                <ReviewRow label="Owner Name" value={ownerName} />
                <ReviewRow label="National ID / TIN" value={ownerNationalIdOrTin} />
                <ReviewRow label="Phone" value={ownerPhone} />
                <ReviewRow label="Address" value={ownerAddress} />
              </SimpleGrid>
            </Paper>

            <Paper withBorder radius="md" p="md">
              <Text fw={700} fz="sm" mb="sm">Documents</Text>
              <Stack gap={6}>
                {docSlots.map((slot) => (
                  <Group key={slot.key} gap="xs">
                    <ThemeIcon size={20} radius="xl" color={files[slot.key] ? 'teal' : 'gray'} variant={files[slot.key] ? 'filled' : 'light'}>
                      <IconCheck size={12} />
                    </ThemeIcon>
                    <Text fz="sm" c={files[slot.key] ? undefined : 'dimmed'}>
                      {slot.label} {!files[slot.key] && slot.required ? '(missing)' : files[slot.key] ? `— ${files[slot.key]!.name}` : '(not uploaded)'}
                    </Text>
                  </Group>
                ))}
              </Stack>
            </Paper>
          </Stack>
        )}

        {/* Navigation */}
        <Group justify="space-between" mt="xl">
          <Button
            variant="default"
            leftSection={<IconArrowLeft size={16} />}
            onClick={active === 0 ? () => navigate('/vessel-registration') : prev}
          >
            {active === 0 ? 'Cancel' : 'Back'}
          </Button>
          {active < STEPS.length - 1 ? (
            <Button
              rightSection={<IconArrowRight size={16} />}
              disabled={!canNext()}
              onClick={next}
            >
              Next
            </Button>
          ) : (
            <Button
              color="teal"
              leftSection={<IconAnchor size={16} />}
              loading={submitting}
              onClick={handleSubmit}
            >
              Submit Registration
            </Button>
          )}
        </Group>
      </Paper>
    </Stack>
  );
}
