import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Alert,
  Badge,
  Button,
  Card,
  Group,
  Loader,
  Modal,
  Paper,
  Progress,
  Stack,
  Table,
  Text,
  TextInput,
  Textarea,
  Title,
  Tooltip,
} from '@mantine/core';
import {
  IconAlertTriangle,
  IconAnchor,
  IconArrowRight,
  IconCertificate,
  IconInfoCircle,
  IconPlus,
  IconRefresh,
  IconShip,
} from '@tabler/icons-react';
import { notify } from '@ema-platform/ui';
import {
  STATUS_COLORS,
  STATUS_LABELS,
  STATUS_PROGRESS,
  TERMINAL_STATUSES,
  extractErrorMessage,
  useCreateApplicationMutation,
  useCreateVesselIncidentMutation,
  useGetCertificateUrlMutation,
  useGetMyApplicationsQuery,
  useGetMyLicensesQuery,
  useGetMyVesselsQuery,
} from '@ema-platform/api';
import type { Vessel } from '@ema-platform/api';

const REGISTRATION_TYPE_KEY = 'VESSEL_REGISTRATION';

const CATEGORY_LABELS: Record<string, string> = {
  INLAND_WATERWAY: 'Inland Waterway',
  SEA_GOING: 'Sea-going',
};

const VESSEL_STATUS_COLORS: Record<string, string> = {
  REGISTERED: 'green',
  SUSPENDED: 'orange',
  DEREGISTERED: 'gray',
};

/** US-VES-016: the owner reports an accident or incident on their vessel. */
function IncidentModal({
  vessel,
  onClose,
}: {
  vessel: Vessel | null;
  onClose: () => void;
}) {
  const [occurredAt, setOccurredAt] = useState('');
  const [location, setLocation] = useState('');
  const [description, setDescription] = useState('');
  const [createIncident, { isLoading }] = useCreateVesselIncidentMutation();

  const submit = async () => {
    if (!vessel) return;
    try {
      await createIncident({
        vesselId: vessel.id,
        body: {
          occurredAt,
          description,
          ...(location ? { location } : {}),
        },
      }).unwrap();
      notify.success('Incident recorded');
      onClose();
      setOccurredAt('');
      setLocation('');
      setDescription('');
    } catch (error) {
      notify.error(extractErrorMessage(error, 'Could not record the incident'));
    }
  };

  return (
    <Modal
      opened={Boolean(vessel)}
      onClose={onClose}
      title={`Report incident — ${vessel?.name ?? ''}`}
      centered
    >
      <Stack>
        <TextInput
          type="date"
          label="Date of occurrence"
          required
          value={occurredAt}
          onChange={(e) => setOccurredAt(e.target.value)}
        />
        <TextInput
          label="Location"
          value={location}
          onChange={(e) => setLocation(e.target.value)}
        />
        <Textarea
          label="What happened"
          required
          minRows={3}
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
        <Group justify="flex-end">
          <Button variant="default" onClick={onClose}>
            Cancel
          </Button>
          <Button
            loading={isLoading}
            disabled={!occurredAt || description.trim().length < 10}
            onClick={submit}
          >
            Record incident
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}

/**
 * The vessel owner's home (US-VES-001…009, 016): registered vessels with
 * their certificates and renewals, registrations still in flight, and the
 * entry point into the config-driven registration wizard.
 */
export function VesselRegistrationPage() {
  const navigate = useNavigate();
  const { data: vessels, isLoading: loadingVessels } = useGetMyVesselsQuery();
  const { data: applications, isLoading: loadingApplications } =
    useGetMyApplicationsQuery();
  const { data: licenses } = useGetMyLicensesQuery();
  const [createApplication] = useCreateApplicationMutation();
  const [getCertificateUrl] = useGetCertificateUrlMutation();
  const [incidentFor, setIncidentFor] = useState<Vessel | null>(null);

  const inFlight = (applications?.items ?? []).filter(
    (app) =>
      app.licenseType?.key === REGISTRATION_TYPE_KEY &&
      !TERMINAL_STATUSES.includes(app.status),
  );

  const licenseById = new Map(
    (licenses?.items ?? []).map((license) => [license.id, license]),
  );

  async function downloadCertificate(vessel: Vessel) {
    try {
      const result = await getCertificateUrl(vessel.licenseId).unwrap();
      window.open(result.url, '_blank', 'noopener');
    } catch (error) {
      notify.error(
        extractErrorMessage(error, 'Could not fetch the certificate'),
      );
    }
  }

  /** A renewal is an ordinary application of kind RENEWAL (US-VES-009). */
  async function renew(vessel: Vessel) {
    try {
      const application = await createApplication({
        licenseType: REGISTRATION_TYPE_KEY,
        kind: 'RENEWAL',
        previousLicenseId: vessel.licenseId,
      }).unwrap();
      navigate(
        `/licensing/${REGISTRATION_TYPE_KEY}/applications/${application.id}`,
      );
    } catch (error) {
      notify.error(extractErrorMessage(error, 'Could not start the renewal'));
    }
  }

  if (loadingVessels || loadingApplications) {
    return (
      <Group justify="center" py="xl">
        <Loader />
      </Group>
    );
  }

  return (
    <Stack>
      <Group justify="space-between">
        <Title order={2}>Vessel Registration</Title>
        <Button
          leftSection={<IconPlus size={16} />}
          onClick={() => navigate(`/licensing/${REGISTRATION_TYPE_KEY}/apply`)}
        >
          Register a vessel
        </Button>
      </Group>

      {/* ----------------------------------------------------- in-flight */}
      {inFlight.length > 0 && (
        <Stack gap="sm">
          <Title order={4}>Registrations in progress</Title>
          {inFlight.map((app) => {
            const isDraft = app.status === 'DRAFT';
            const needsAction = app.status === 'RESUBMIT_REQUIRED';
            const vesselName =
              (app.formData?.vesselDetails?.vesselName as string) ?? null;
            return (
              <Card key={app.id} withBorder radius="md" p="md">
                <Group justify="space-between" wrap="nowrap">
                  <div>
                    <Group gap="xs">
                      <Text fw={600}>{app.applicationNumber}</Text>
                      {vesselName && (
                        <Text c="dimmed" size="sm">
                          — {vesselName}
                        </Text>
                      )}
                      {app.kind === 'RENEWAL' && (
                        <Badge variant="light">Renewal</Badge>
                      )}
                    </Group>
                    <Progress
                      value={STATUS_PROGRESS[app.status]}
                      mt="xs"
                      w={260}
                    />
                  </div>
                  <Group wrap="nowrap">
                    <Badge color={STATUS_COLORS[app.status]}>
                      {STATUS_LABELS[app.status]}
                    </Badge>
                    <Button
                      size="compact-sm"
                      variant={needsAction ? 'filled' : 'light'}
                      color={needsAction ? 'orange' : undefined}
                      rightSection={<IconArrowRight size={14} />}
                      onClick={() =>
                        navigate(
                          `/licensing/${REGISTRATION_TYPE_KEY}/applications/${app.id}`,
                        )
                      }
                    >
                      {isDraft ? 'Continue' : needsAction ? 'Fix' : 'View'}
                    </Button>
                  </Group>
                </Group>
              </Card>
            );
          })}
        </Stack>
      )}

      {/* ------------------------------------------------------- register */}
      <Stack gap="sm">
        <Title order={4}>My vessels</Title>
        {(vessels ?? []).length === 0 ? (
          <Paper withBorder radius="md" p="xl">
            <Stack align="center" gap="sm">
              <IconShip size={40} color="var(--mantine-color-blue-5)" />
              <Text fw={600}>No registered vessels yet</Text>
              <Text size="sm" c="dimmed" ta="center" maw={420}>
                Register an inland-waterway or sea-going vessel. Approval
                issues the registration certificate and enters the vessel in
                the national register.
              </Text>
              <Button
                mt="xs"
                onClick={() =>
                  navigate(`/licensing/${REGISTRATION_TYPE_KEY}/apply`)
                }
              >
                Start registration
              </Button>
            </Stack>
          </Paper>
        ) : (
          <Table.ScrollContainer minWidth={760}>
            <Table striped highlightOnHover>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th>Registration №</Table.Th>
                  <Table.Th>Vessel</Table.Th>
                  <Table.Th>Category</Table.Th>
                  <Table.Th>Certificate</Table.Th>
                  <Table.Th>Status</Table.Th>
                  <Table.Th />
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {(vessels ?? []).map((vessel) => {
                  const license = licenseById.get(vessel.licenseId);
                  const renewable = license?.renewable ?? false;
                  const expiring =
                    license?.daysUntilExpiry !== undefined &&
                    license.daysUntilExpiry <= 60;
                  return (
                    <Table.Tr key={vessel.id}>
                      <Table.Td>
                        <Text ff="monospace" size="sm" fw={600}>
                          {vessel.registrationNumber}
                        </Text>
                      </Table.Td>
                      <Table.Td>
                        <Text size="sm" fw={500}>
                          {vessel.name}
                        </Text>
                        <Text size="xs" c="dimmed">
                          {vessel.vesselType ?? '—'}
                          {vessel.imoNumber ? ` · IMO ${vessel.imoNumber}` : ''}
                        </Text>
                      </Table.Td>
                      <Table.Td>
                        {CATEGORY_LABELS[vessel.category] ?? vessel.category}
                      </Table.Td>
                      <Table.Td>
                        {license ? (
                          <Group gap={6} wrap="nowrap">
                            <Badge
                              size="sm"
                              variant="light"
                              color={
                                license.status === 'ACTIVE'
                                  ? expiring
                                    ? 'yellow'
                                    : 'green'
                                  : 'red'
                              }
                            >
                              {license.status === 'ACTIVE' && expiring
                                ? `Expires in ${license.daysUntilExpiry}d`
                                : license.status}
                            </Badge>
                          </Group>
                        ) : (
                          <Text size="sm" c="dimmed">
                            —
                          </Text>
                        )}
                      </Table.Td>
                      <Table.Td>
                        <Badge
                          size="sm"
                          color={VESSEL_STATUS_COLORS[vessel.status]}
                        >
                          {vessel.status}
                        </Badge>
                      </Table.Td>
                      <Table.Td>
                        <Group gap="xs" justify="flex-end" wrap="nowrap">
                          <Tooltip label="Download certificate">
                            <Button
                              size="compact-xs"
                              variant="subtle"
                              leftSection={<IconCertificate size={14} />}
                              onClick={() => downloadCertificate(vessel)}
                            >
                              Certificate
                            </Button>
                          </Tooltip>
                          {renewable && vessel.status === 'REGISTERED' && (
                            <Tooltip label="Renew the registration">
                              <Button
                                size="compact-xs"
                                variant="light"
                                leftSection={<IconRefresh size={14} />}
                                onClick={() => renew(vessel)}
                              >
                                Renew
                              </Button>
                            </Tooltip>
                          )}
                          <Tooltip label="Report accident / incident">
                            <Button
                              size="compact-xs"
                              variant="subtle"
                              color="orange"
                              leftSection={<IconAlertTriangle size={14} />}
                              onClick={() => setIncidentFor(vessel)}
                            >
                              Incident
                            </Button>
                          </Tooltip>
                        </Group>
                      </Table.Td>
                    </Table.Tr>
                  );
                })}
              </Table.Tbody>
            </Table>
          </Table.ScrollContainer>
        )}
      </Stack>

      {(vessels ?? []).some((v) => v.status === 'SUSPENDED') && (
        <Alert color="orange" icon={<IconInfoCircle size={16} />}>
          A suspended vessel may not operate. Contact the Ethiopian Maritime
          Authority about reinstatement.
        </Alert>
      )}

      <Paper withBorder radius="md" p="md">
        <Group gap="xs">
          <IconAnchor size={18} color="var(--mantine-color-blue-5)" />
          <Text size="sm" c="dimmed">
            Amendment and duplicate-certificate services are coming in a
            later release.
          </Text>
        </Group>
      </Paper>

      <IncidentModal vessel={incidentFor} onClose={() => setIncidentFor(null)} />
    </Stack>
  );
}

export default VesselRegistrationPage;
