import {
  Badge,
  Group,
  Loader,
  SimpleGrid,
  Stack,
  Table,
  Text,
} from '@mantine/core';
import type { ReactNode } from 'react';

import { useInterchangeDocument } from '@/hooks/useInterchangeDocuments';
import type { InterchangeDocumentStatus } from '@/types/interchangeDocument';
import { formatDate, formatNumber } from './options';

const statusColor: Record<InterchangeDocumentStatus, string> = {
  DRAFT: 'gray',
  GENERATED: 'blue',
  ACKNOWLEDGED: 'green',
  DISPUTED: 'red',
  CANCELLED: 'gray',
};

function DetailField({ label, value }: { label: string; value: ReactNode }) {
  return (
    <Stack gap={2}>
      <Text size="xs" c="dimmed">
        {label}
      </Text>
      <Text size="sm" fw={600}>
        {value || '-'}
      </Text>
    </Stack>
  );
}

export function InterchangeDocumentDetailPanel({ id }: { id: string }) {
  const { data: document, isLoading } = useInterchangeDocument(id);

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

  if (!document) return null;

  const items = document.items ?? [];

  return (
    <Stack gap="lg">
      <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }}>
        <DetailField label="Document No" value={document.documentNo} />
        <DetailField label="Direction" value={document.direction} />
        <DetailField label="Schedule" value={document.scheduleId?.slice(0, 8)} />
        <DetailField label="Train No" value={document.trainNo} />
        <DetailField label="Handover Location" value={document.handoverLocation} />
        <DetailField label="Handover From" value={document.handoverFrom} />
        <DetailField label="Handover To" value={document.handoverTo} />
        <DetailField
          label="Status"
          value={
            <Badge variant="light" color={statusColor[document.status]}>
              {document.status}
            </Badge>
          }
        />
        <DetailField label="Generated At" value={formatDate(document.generatedAt)} />
        <DetailField label="Acknowledged At" value={formatDate(document.acknowledgedAt)} />
        <DetailField label="Signed by EDR" value={document.generatedBy} />
        <DetailField label="Signed by Djibouti Port" value={document.acknowledgedBy} />
        <DetailField label="Customs Ref" value={document.customsReference} />
        <DetailField label="Manifest Ref" value={document.manifestReference} />
      </SimpleGrid>

      <Table.ScrollContainer minWidth={980}>
        <Table striped highlightOnHover verticalSpacing="sm">
          <Table.Thead>
            <Table.Tr>
              <Table.Th>Booking Reference</Table.Th>
              <Table.Th>Item Type</Table.Th>
              <Table.Th>Container Number</Table.Th>
              <Table.Th>Seal Number</Table.Th>
              <Table.Th>Cargo Type</Table.Th>
              <Table.Th>Weight</Table.Th>
              <Table.Th>Quantity</Table.Th>
              <Table.Th>Wagon Number</Table.Th>
              <Table.Th>Condition</Table.Th>
              <Table.Th>Damage Description</Table.Th>
              <Table.Th>Remarks</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>
            {items.map((item) => (
              <Table.Tr key={item.id}>
                <Table.Td>{item.bookingReference ?? item.bookingId?.slice(0, 8) ?? '-'}</Table.Td>
                <Table.Td>{item.itemType}</Table.Td>
                <Table.Td>{item.containerNumber ?? '-'}</Table.Td>
                <Table.Td>{item.sealNumber ?? '-'}</Table.Td>
                <Table.Td>{item.cargoType ?? item.cargoDescription ?? '-'}</Table.Td>
                <Table.Td>{formatNumber(item.weight)}</Table.Td>
                <Table.Td>{formatNumber(item.quantity)}</Table.Td>
                <Table.Td>{item.wagonNumber ?? '-'}</Table.Td>
                <Table.Td>
                  <Badge
                    variant="light"
                    color={
                      item.conditionStatus === 'GOOD'
                        ? 'green'
                        : item.conditionStatus === 'UNKNOWN'
                          ? 'gray'
                          : 'orange'
                    }
                    size="sm"
                  >
                    {item.conditionStatus}
                  </Badge>
                </Table.Td>
                <Table.Td>{item.damageDescription ?? '-'}</Table.Td>
                <Table.Td>{item.remarks ?? '-'}</Table.Td>
              </Table.Tr>
            ))}
          </Table.Tbody>
        </Table>
      </Table.ScrollContainer>
    </Stack>
  );
}
