import { Fragment, useState } from 'react';
import {
  Alert,
  Badge,
  Button,
  Card,
  Group,
  Loader,
  Modal,
  Table,
  Tabs,
  Text,
} from '@mantine/core';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  ChevronDown,
  ChevronRight,
  Eye,
  FileText,
  History,
  PackageOpen,
  ShieldCheck,
  Truck,
} from 'lucide-react';

import { PageContainer, PageHeader } from '@/components/page';
import {
  ActivityTimeline,
  InventoryMovementHistoryTable,
  VisualEmptyState,
  WarehouseOpsKpiStrip,
  formatDate,
  formatNumber,
} from '@/components/warehouses';
import {
  useAutoUnloadExportAtDjibouti,
  useExportDjiboutiArrivalQueue,
  useExportDjiboutiTrainItems,
} from '@/hooks/useWarehouses';
import {
  useGenerateInterchangeDocument,
  useInterchangeDocuments,
} from '@/hooks/useInterchangeDocuments';
import { useToast } from '@/hooks/use-toast';
import { trainSchedulingService } from '@/services/trainScheduling.service';
import type {
  AutoUnloadExportDjiboutiResult,
  ExportTrain,
  ExportTrainItem,
} from '@/types/warehouse';

const getErrorMessage = (error: unknown) => {
  if (error && typeof error === 'object' && 'response' in error) {
    const response = (error as { response?: { data?: { message?: unknown } } }).response;
    const message = response?.data?.message;
    if (Array.isArray(message)) return message.join(', ');
    if (typeof message === 'string') return message;
  }
  return error instanceof Error ? error.message : undefined;
};

const statusColor = (status?: string | null) => {
  if (status === 'UNLOADED_AT_DJIBOUTI_PORT') return 'green';
  if (status === 'ARRIVED_AT_DJIBOUTI' || status === 'ARRIVED') return 'blue';
  if (status === 'FAILED') return 'red';
  if (status === 'SKIPPED') return 'orange';
  return 'gray';
};

const statusLabel = (status?: string | null) =>
  status === 'UNLOADED_AT_DJIBOUTI_PORT'
    ? 'Unloaded at Djibouti Port'
    : (status ?? 'PENDING').replace(/_/g, ' ');

function ExportTrainDetailRows({
  train,
  onOpenHistory,
}: {
  train: ExportTrain;
  onOpenHistory: (inventoryId: string) => void;
}) {
  const navigate = useNavigate();
  const { data: items = [], isLoading } = useExportDjiboutiTrainItems(train.scheduleId);

  if (isLoading) {
    return (
      <Group justify="center" py="md">
        <Loader size="sm" />
      </Group>
    );
  }

  if (items.length === 0) {
    return (
      <Text c="dimmed" ta="center" py="md" size="sm">
        No assigned export bookings found for this train.
      </Text>
    );
  }

  return (
    <Table.ScrollContainer minWidth={1420}>
      <Table highlightOnHover verticalSpacing="xs">
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Wagon</Table.Th>
            <Table.Th>Booking ID</Table.Th>
            <Table.Th>Booking Reference</Table.Th>
            <Table.Th>Customer ID</Table.Th>
            <Table.Th>Customer Name</Table.Th>
            <Table.Th>Item Type</Table.Th>
            <Table.Th>Container Number</Table.Th>
            <Table.Th>Cargo Type</Table.Th>
            <Table.Th>Weight</Table.Th>
            <Table.Th>Origin</Table.Th>
            <Table.Th>Destination</Table.Th>
            <Table.Th>Train Schedule</Table.Th>
            <Table.Th>Arrival Time at Djibouti</Table.Th>
            <Table.Th>Current Status</Table.Th>
            <Table.Th ta="right">Actions</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {items.map((item: ExportTrainItem) => (
            <Table.Tr key={`${item.bookingId}-${item.itemType}-${item.itemId ?? item.inventoryId ?? 'item'}`}>
              <Table.Td>
                <Text size="xs" fw={600}>
                  {item.sequenceNo ? `#${item.sequenceNo}` : '-'} {item.wagonNumber ?? ''}
                </Text>
              </Table.Td>
              <Table.Td>{item.bookingId.slice(0, 8)}</Table.Td>
              <Table.Td>
                <Text size="sm" fw={600}>
                  {item.bookingReference ?? '-'}
                </Text>
              </Table.Td>
              <Table.Td>{item.customerId?.slice(0, 8) ?? '-'}</Table.Td>
              <Table.Td>{item.customerName ?? '-'}</Table.Td>
              <Table.Td>{item.itemType}</Table.Td>
              <Table.Td>{item.containerNumber ?? '-'}</Table.Td>
              <Table.Td>{item.cargoType ?? '-'}</Table.Td>
              <Table.Td>{formatNumber(item.weight)}</Table.Td>
              <Table.Td>{item.origin ?? '-'}</Table.Td>
              <Table.Td>{item.destination ?? '-'}</Table.Td>
              <Table.Td>{item.trainSchedule ?? '-'}</Table.Td>
              <Table.Td>{formatDate(item.arrivalTime)}</Table.Td>
              <Table.Td>
                <Badge variant="light" color={statusColor(item.currentStatus)} size="sm">
                  {statusLabel(item.currentStatus)}
                </Badge>
              </Table.Td>
              <Table.Td>
                <Group gap="xs" justify="flex-end" wrap="nowrap">
                  <Button
                    size="compact-xs"
                    variant="light"
                    leftSection={<Eye size={14} />}
                    onClick={() => navigate(`/dashboard/booking-requests/${item.bookingId}`)}
                  >
                    View
                  </Button>
                  <Button
                    size="compact-xs"
                    variant="light"
                    color="gray"
                    leftSection={<History size={14} />}
                    disabled={!item.inventoryId}
                    onClick={() => item.inventoryId && onOpenHistory(item.inventoryId)}
                  >
                    Movement
                  </Button>
                </Group>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
    </Table.ScrollContainer>
  );
}

export default function ExportDjiboutiUnloadingQueuePage() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { data: trains = [], isLoading, isError, error } = useExportDjiboutiArrivalQueue();
  const { data: interchangeDocuments = [] } = useInterchangeDocuments({ direction: 'EXPORT' });
  const autoUnload = useAutoUnloadExportAtDjibouti();
  const generateInterchange = useGenerateInterchangeDocument();
  const qc = useQueryClient();
  const secureGatePass = useMutation({
    mutationFn: (scheduleId: string) => trainSchedulingService.grantImportDjiboutiGatepass(scheduleId),
    onSuccess: () =>
      qc.invalidateQueries({
        queryKey: ['warehouse-inventory', 'export-djibouti-arrival-queue'],
      }),
  });
  const [openScheduleId, setOpenScheduleId] = useState<string | null>(null);
  const [busyScheduleId, setBusyScheduleId] = useState<string | null>(null);
  const [historyInventoryId, setHistoryInventoryId] = useState<string | null>(null);

  const interchangeBySchedule = new Map(
    interchangeDocuments
      .filter((doc) => doc.scheduleId && doc.status !== 'CANCELLED')
      .map((doc) => [doc.scheduleId as string, doc]),
  );

  const secureGate = async (train: ExportTrain) => {
    setBusyScheduleId(train.scheduleId);
    try {
      await secureGatePass.mutateAsync(train.scheduleId);
      toast({
        title: 'Gate pass secured',
        description: `Djibouti Port entry allowed for ${train.trainNumber ?? 'the train'}. You can now auto unload.`,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: 'Could not secure gate pass',
        description: getErrorMessage(error),
      });
    } finally {
      setBusyScheduleId(null);
    }
  };

  const unloadTrain = async (train: ExportTrain) => {
    setBusyScheduleId(train.scheduleId);
    try {
      const res = (await autoUnload.mutateAsync(train.scheduleId)) as {
        data: AutoUnloadExportDjiboutiResult;
      };
      const result = res.data;
      const details = [
        result.skippedCount ? `${result.skippedCount} skipped` : '',
        result.failedCount ? `${result.failedCount} failed` : '',
        result.interchangeDocument
          ? `Signed interchange document ${result.interchangeDocument.documentNo} generated`
          : '',
      ]
        .filter(Boolean)
        .join(', ');

      toast({
        title: `${result.unloadedCount} export item(s) auto unloaded`,
        description: details || `${train.trainNumber ?? 'Train'} unloaded at Djibouti Port.`,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: 'Auto unload failed',
        description: getErrorMessage(error),
      });
    } finally {
      setBusyScheduleId(null);
    }
  };

  const generateInterchangeDocument = async (train: ExportTrain) => {
    setBusyScheduleId(train.scheduleId);
    try {
      const res = await generateInterchange.mutateAsync({
        scheduleId: train.scheduleId,
        direction: 'EXPORT',
        handoverLocation: train.destination ?? 'Djibouti Port',
        handoverFrom: 'EDR',
        handoverTo: 'Djibouti Port Operator',
        portOperatorName: 'Doraleh Multipurpose Port',
        generatedBy: 'EDR Operations',
        remarks: 'Generated after export unloading at Djibouti Port; signed by EDR and Djibouti Port Operator.',
      });
      toast({
        title: 'Interchange document generated',
        description: res.data.documentNo,
      });
      navigate('/dashboard/interchange-documents');
    } catch (error) {
      toast({
        variant: 'destructive',
        title: 'Interchange document generation failed',
        description: getErrorMessage(error),
      });
    } finally {
      setBusyScheduleId(null);
    }
  };

  return (
    <PageContainer>
      <PageHeader
        title="Djibouti Arrival / Unloading Queue"
        subtitle="Arrived export trains at Djibouti-side destinations, auto unloading, and signed interchange handover."
        breadcrumbs={[{ label: 'Djibouti Arrival / Unloading Queue' }]}
      />

      <WarehouseOpsKpiStrip />

      <Card withBorder radius="md" padding="lg">
          <Group justify="space-between" mb="md">
            <Text fw={600}>{trains.length} arrived export train(s)</Text>
            <Text size="sm" c="dimmed">
              Open a train, auto unload it, then view the signed interchange document.
            </Text>
          </Group>

          {isLoading ? (
            <Group justify="center" py="xl">
              <Loader />
            </Group>
          ) : isError ? (
            <Alert color="red" variant="light" title="Could not load arrived export trains">
              {getErrorMessage(error) ?? 'Check your API connection and sign in again.'}
            </Alert>
          ) : trains.length === 0 ? (
            <VisualEmptyState
              variant="train"
              title="No arrived export trains"
              description="Export trains appear here after arriving at Djibouti, Doraleh, DMP, DCT, or Nagad."
            />
          ) : (
            <Table.ScrollContainer minWidth={1180}>
              <Table verticalSpacing="sm" highlightOnHover striped>
                <Table.Thead>
                  <Table.Tr>
                    <Table.Th>Train Schedule ID</Table.Th>
                    <Table.Th>Train Number</Table.Th>
                    <Table.Th>Route</Table.Th>
                    <Table.Th>Origin</Table.Th>
                    <Table.Th>Destination</Table.Th>
                    <Table.Th>Departure Time</Table.Th>
                    <Table.Th>Arrival Time</Table.Th>
                    <Table.Th ta="center">Total Bookings</Table.Th>
                    <Table.Th ta="center">Total Containers</Table.Th>
                    <Table.Th ta="center">Total Cargoes</Table.Th>
                    <Table.Th>Current Status</Table.Th>
                    <Table.Th ta="right">Actions</Table.Th>
                  </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                  {trains.map((train: ExportTrain) => {
                    const isOpen = openScheduleId === train.scheduleId;
                    const interchangeDocument = interchangeBySchedule.get(train.scheduleId);
                    return (
                      <Fragment key={train.scheduleId}>
                        <Table.Tr>
                          <Table.Td>{train.scheduleId.slice(0, 8)}</Table.Td>
                          <Table.Td>
                            <Text size="sm" fw={700}>
                              {train.trainNumber ?? '-'}
                            </Text>
                          </Table.Td>
                          <Table.Td>{train.route ?? '-'}</Table.Td>
                          <Table.Td>{train.origin ?? '-'}</Table.Td>
                          <Table.Td>{train.destination ?? '-'}</Table.Td>
                          <Table.Td>{formatDate(train.departureTime)}</Table.Td>
                          <Table.Td>{formatDate(train.arrivalTime)}</Table.Td>
                          <Table.Td ta="center">{train.totalBookings}</Table.Td>
                          <Table.Td ta="center">{train.totalContainers}</Table.Td>
                          <Table.Td ta="center">{train.totalCargoes}</Table.Td>
                          <Table.Td>
                            <Badge variant="light" color={statusColor(train.status)} size="sm">
                              {statusLabel(train.status)}
                            </Badge>
                          </Table.Td>
                          <Table.Td>
                            <Group gap="xs" justify="flex-end" wrap="nowrap">
                              <Button
                                size="compact-xs"
                                variant="light"
                                leftSection={
                                  isOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />
                                }
                                onClick={() => setOpenScheduleId(isOpen ? null : train.scheduleId)}
                              >
                                Open
                              </Button>
                              <Button
                                size="compact-xs"
                                variant="light"
                                color="teal"
                                leftSection={<ShieldCheck size={14} />}
                                loading={busyScheduleId === train.scheduleId && secureGatePass.isPending}
                                onClick={() => secureGate(train)}
                              >
                                Secure Gate Pass
                              </Button>
                              <Button
                                size="compact-xs"
                                color="green"
                                leftSection={
                                  busyScheduleId === train.scheduleId ? (
                                    <PackageOpen size={14} />
                                  ) : (
                                    <Truck size={14} />
                                  )
                                }
                                loading={busyScheduleId === train.scheduleId && autoUnload.isPending}
                                onClick={() => unloadTrain(train)}
                              >
                                Auto Unload Export Items
                              </Button>
                              {interchangeDocument ? (
                                <Button
                                  size="compact-xs"
                                  variant="light"
                                  color="blue"
                                  leftSection={<Eye size={14} />}
                                  onClick={() => navigate('/dashboard/interchange-documents')}
                                >
                                  View Document
                                </Button>
                              ) : (
                                <Button
                                  size="compact-xs"
                                  variant="light"
                                  color="green"
                                  leftSection={<FileText size={14} />}
                                  loading={busyScheduleId === train.scheduleId && generateInterchange.isPending}
                                  onClick={() => generateInterchangeDocument(train)}
                                >
                                  Generate Signed Document
                                </Button>
                              )}
                            </Group>
                          </Table.Td>
                        </Table.Tr>
                        {isOpen && (
                          <Table.Tr>
                            <Table.Td colSpan={12} bg="var(--mantine-color-gray-0)">
                              <ExportTrainDetailRows
                                train={train}
                                onOpenHistory={setHistoryInventoryId}
                              />
                            </Table.Td>
                          </Table.Tr>
                        )}
                      </Fragment>
                    );
                  })}
                </Table.Tbody>
              </Table>
            </Table.ScrollContainer>
          )}
      </Card>

      <Modal
        opened={Boolean(historyInventoryId)}
        onClose={() => setHistoryInventoryId(null)}
        title="Movement history"
        size="xl"
      >
        {historyInventoryId ? (
          <Tabs defaultValue="activity">
            <Tabs.List>
              <Tabs.Tab value="activity">Activity</Tabs.Tab>
              <Tabs.Tab value="movements">Movements</Tabs.Tab>
            </Tabs.List>
            <Tabs.Panel value="activity" pt="md">
              <ActivityTimeline inventoryId={historyInventoryId} />
            </Tabs.Panel>
            <Tabs.Panel value="movements" pt="md">
              <InventoryMovementHistoryTable inventoryId={historyInventoryId} />
            </Tabs.Panel>
          </Tabs>
        ) : null}
      </Modal>
    </PageContainer>
  );
}
