import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Badge,
  Button,
  Card,
  Group,
  Text,
} from '@mantine/core';
import { ClipboardList, Eye, PackageOpen, Truck } from 'lucide-react';
import { DataTable, type ColumnDef } from '@edr/ui-common';

import { PageContainer, PageHeader } from '@/components/page';
import {
  InspectionReportModal,
  VisualEmptyState,
  formatDate,
} from '@/components/warehouses';
import { useMutation, useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { ArrivalQueueItem } from '@/types/warehouse';

function inspectionBadge(status: string | null) {
  if (!status) return <Badge variant="light" color="gray" size="sm">Not inspected</Badge>;
  const color = status === 'PASSED' ? 'edr-green' : status === 'FAILED' ? 'red' : 'orange';
  return <Badge variant="light" color={color} size="sm">{status.replace(/_/g, ' ')}</Badge>;
}

/** Batch 4.5 — arrived bookings awaiting unload / inspection. */
export default function ArrivalQueuePage() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { data, isLoading } = useQuery(api.warehouses.arrivalQueue.queryOptions());
  const autoUnload = useMutation(api.warehouses.autoUnloadArrived.mutationOptions());
  const unloadOne = useMutation(api.warehouses.unloadBooking.mutationOptions());
  const [inspectInventoryId, setInspectInventoryId] = useState<string | null>(null);

  const items = data ?? [];

  const handleAutoUnload = async () => {
    try {
      const r = await autoUnload.mutateAsync();
      toast({
        title: 'Auto-unload complete',
        description: `Processed ${r.processedCount}, skipped ${r.skippedCount}, failed ${r.failedCount}.`,
      });
    } catch {
      toast({ variant: 'destructive', title: 'Auto-unload failed' });
    }
  };

  const handleUnloadOne = async (item: ArrivalQueueItem) => {
    try {
      await unloadOne.mutateAsync({ bookingId: item.bookingId });
      toast({ title: 'Booking unloaded', description: `${item.bookingReference} stored as RECEIVED.` });
    } catch {
      toast({ variant: 'destructive', title: 'Unload failed' });
    }
  };

  const columns: ColumnDef<ArrivalQueueItem>[] = [
    {
      id: 'booking',
      header: 'Booking',
      cell: ({ row }) => (
        <Text fw={600} size="sm">
          {row.original.bookingReference}
        </Text>
      ),
    },
    { id: 'customer', header: 'Customer', cell: ({ row }) => row.original.customer ?? '—' },
    {
      id: 'cargo',
      header: 'Cargo / Container',
      cell: ({ row }) => row.original.container ?? row.original.cargo ?? '—',
    },
    {
      id: 'arrival',
      header: 'Arrival',
      cell: ({ row }) => <Text size="xs">{formatDate(row.original.arrivalDate)}</Text>,
    },
    { id: 'facility', header: 'Facility', cell: ({ row }) => row.original.facility ?? '—' },
    { id: 'warehouse', header: 'Warehouse', cell: ({ row }) => row.original.warehouse ?? '—' },
    { id: 'yard', header: 'Yard', cell: ({ row }) => row.original.yard ?? '—' },
    { id: 'zone', header: 'Zone', cell: ({ row }) => row.original.zone ?? '—' },
    {
      id: 'status',
      header: 'Status',
      cell: ({ row }) =>
        row.original.unloaded ? (
          <Badge variant="light" color="edr-green" size="sm">
            {row.original.currentStatus ?? 'RECEIVED'}
          </Badge>
        ) : (
          <Badge variant="light" color="orange" size="sm">
            Not unloaded
          </Badge>
        ),
    },
    {
      id: 'inspection',
      header: 'Inspection',
      cell: ({ row }) => inspectionBadge(row.original.inspectionStatus),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => {
        const item = row.original;
        return (
          <Group gap="xs" justify="flex-end" wrap="nowrap" onClick={(e) => e.stopPropagation()}>
            {!item.unloaded && (
              <Button
                size="compact-xs"
                variant="light"
                leftSection={<Truck size={14} />}
                loading={unloadOne.isPending}
                onClick={() => handleUnloadOne(item)}
              >
                Unload
              </Button>
            )}
            {item.inventoryId && (
              <Button
                size="compact-xs"
                variant="light"
                color="edr-green"
                leftSection={<ClipboardList size={14} />}
                onClick={() => setInspectInventoryId(item.inventoryId)}
              >
                Inspect
              </Button>
            )}
            {item.inventoryId && (
              <Button
                size="compact-xs"
                variant="subtle"
                color="gray"
                leftSection={<Eye size={14} />}
                onClick={() => navigate('/dashboard/warehouse-inventory')}
              >
                Inventory
              </Button>
            )}
          </Group>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <PageHeader
        title="Arrival / Unloading Queue"
        subtitle="Arrived bookings ready to unload, store and inspect."
        action={
          <Button
            leftSection={<PackageOpen size={16} />}
            loading={autoUnload.isPending}
            onClick={handleAutoUnload}
          >
            Auto Unload Arrived Bookings
          </Button>
        }
      />

      <Card>
        <Text fw={600} mb="md">
          {items.length} arrived booking(s)
        </Text>

        {!isLoading && items.length === 0 ? (
          <VisualEmptyState
            variant="container"
            title="No arrived bookings"
            description="Bookings in transit that arrive appear here for unloading and inspection."
          />
        ) : (
          <DataTable
            columns={columns}
            data={items}
            status={isLoading ? 'loading' : 'success'}
            containerClassName="border-0 shadow-none"
          />
        )}
      </Card>

      <InspectionReportModal
        opened={Boolean(inspectInventoryId)}
        onClose={() => setInspectInventoryId(null)}
        inventoryId={inspectInventoryId}
      />
    </PageContainer>
  );
}
