import { Badge, Divider, Group, Modal, SimpleGrid, Stack, Text } from '@mantine/core';

import type { WarehouseInventoryItem } from '@/types/warehouse';
import { InventoryStatusBadge } from './badges';
import { formatDate, formatNumber } from './options';

interface InventoryDetailModalProps {
  opened: boolean;
  onClose: () => void;
  item: WarehouseInventoryItem | null;
}

function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <Stack gap={2}>
      <Text size="xs" c="dimmed" tt="uppercase" fw={700}>
        {label}
      </Text>
      <Text size="sm" fw={500}>
        {value || '-'}
      </Text>
    </Stack>
  );
}

const noteLineValue = (notes: string | null | undefined, label: string) => {
  const match = notes?.match(new RegExp(`^${label}:\\s*(.+)$`, 'im'));
  return match?.[1]?.trim() ?? '';
};

export function InventoryDetailModal({ opened, onClose, item }: InventoryDetailModalProps) {
  const bookingReference = item?.booking?.reference ?? '-';
  const handoverReference = item?.handoverDocumentReference ?? noteLineValue(item?.notes, 'Handover Reference');
  const handoverDate = item?.handoverDocumentDate ?? noteLineValue(item?.notes, 'Generated At');
  const inventorySummary = [
    item?.status?.replace(/_/g, ' '),
    item?.grnNumber ? `GRN ${item.grnNumber}` : null,
    item?.releaseOrderReference ? `Release ${item.releaseOrderReference}` : null,
    handoverReference ? `Handover ${handoverReference}` : null,
    item?.warehouse ? `${item.warehouse.name} (${item.warehouse.code})` : null,
  ]
    .filter(Boolean)
    .join(' / ');

  return (
    <Modal opened={opened} onClose={onClose} title="Inventory detail" centered size="xl">
      {!item ? (
        <Text c="dimmed">No inventory item selected.</Text>
      ) : (
        <Stack gap="md">
          <Group justify="space-between" align="flex-start">
            <Stack gap={2}>
              <Text size="lg" fw={800}>
                {bookingReference}
              </Text>
              <Text size="sm" c="dimmed">
                {inventorySummary || 'Inventory information'}
              </Text>
            </Stack>
            <InventoryStatusBadge status={item.status} />
          </Group>

          <Divider label="Location" labelPosition="left" />
          <SimpleGrid cols={{ base: 1, sm: 3 }}>
            <DetailRow label="Warehouse" value={item.warehouse ? `${item.warehouse.name} (${item.warehouse.code})` : '-'} />
            <DetailRow label="Yard" value={item.yard ? `${item.yard.name} (${item.yard.code})` : '-'} />
            <DetailRow label="Zone" value={item.zone ? `${item.zone.name} (${item.zone.code})` : '-'} />
          </SimpleGrid>

          <Divider label="Booking & item" labelPosition="left" />
          <SimpleGrid cols={{ base: 1, sm: 3 }}>
            <DetailRow label="Booking reference" value={bookingReference} />
            <DetailRow label="GRN" value={item.grnNumber ?? '-'} />
            <DetailRow label="Booking status" value={item.booking?.status ?? '-'} />
            <DetailRow label="Payment status" value={item.booking?.paymentStatus ?? '-'} />
            <DetailRow label="Trade direction" value={item.booking?.tradeDirection ?? '-'} />
            <DetailRow label="Inventory status" value={item.status.replace(/_/g, ' ')} />
            <DetailRow label="Release reference" value={item.releaseOrderReference ?? '-'} />
            <DetailRow label="Handover reference" value={handoverReference || '-'} />
            <DetailRow label="Quantity" value={formatNumber(item.quantity)} />
            <DetailRow label="Weight" value={`${formatNumber(item.weight)} kg`} />
            <DetailRow label="Volume" value={item.volume == null ? '-' : formatNumber(item.volume)} />
          </SimpleGrid>

          <Divider label="Lifecycle" labelPosition="left" />
          <SimpleGrid cols={{ base: 1, sm: 3 }}>
            <DetailRow label="Inspection" value={<Badge variant="light">{item.inspectionStatus ?? 'Not inspected'}</Badge>} />
            <DetailRow label="Arrived" value={formatDate(item.arrivedAt)} />
            <DetailRow label="Stored" value={formatDate(item.storedAt)} />
            <DetailRow label="Reserved" value={formatDate(item.reservedAt)} />
            <DetailRow label="Inspected" value={formatDate(item.inspectedAt)} />
            <DetailRow label="Ready for loading" value={formatDate(item.readyForLoadingAt)} />
            <DetailRow label="Loaded" value={formatDate(item.loadedAt)} />
            <DetailRow label="Dispatched" value={formatDate(item.dispatchedAt)} />
            <DetailRow label="Ready for pickup" value={formatDate(item.readyForPickupAt)} />
            <DetailRow label="Released" value={formatDate(item.releaseDate)} />
            <DetailRow label="Handover generated" value={formatDate(handoverDate)} />
            <DetailRow label="Delivered" value={formatDate(item.deliveredAt)} />
            <DetailRow label="Release reference" value={item.releaseOrderReference ?? '-'} />
          </SimpleGrid>

          {item.notes && (
            <>
              <Divider label="Notes" labelPosition="left" />
              <Text size="sm">{item.notes}</Text>
            </>
          )}
        </Stack>
      )}
    </Modal>
  );
}
