import { useCallback, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
  ActionIcon,
  Badge,
  Box,
  Card,
  Group,
  ScrollArea,
  SegmentedControl,
  SimpleGrid,
  Stack,
  Tabs,
  Text,
  TextInput,
  ThemeIcon,
  Tooltip,
} from "@mantine/core";
import {
  ArrowRight,
  Calendar,
  CheckCircle,
  ChevronRight,
  History,
  Inbox,
  LayoutGrid,
  RefreshCw,
  Search,
  ShieldCheck,
  ShipWheel,
  Table as TableIcon,
  Truck,
  User,
  X,
} from "lucide-react";
import {
  DataTable,
  DataTableFooter,
  usePagination,
  type ColumnDef,
} from "@edr/ui-common";

import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { KpiStrip } from "@/components/page/KpiStrip";
import { bookingTable } from "@/components/bookings/booking-ui.styles";
import { bookingsService } from "@/services/bookings.service";
import type { BookingDetail } from "@/types/booking";
import {
  CLEARANCE_TABS,
  type ClearanceTabKey,
} from "@/features/clearance/clearance-tabs.config";

type ViewMode = "table" | "cards";
type PageTab = "queue" | "history";

const CLEARANCE_REVIEW_STATUS = "DOCUMENTS_UNDER_REVIEW";
const CLEARANCE_HISTORY_STATUS = "CLEARANCE_READY";

interface ClearanceRow {
  id: string;
  reference: string;
  customerLabel: string;
  tradeDirection: string;
  freightType: string;
  originLabel: string;
  destinationLabel: string;
  scheduledDate: string;
  updatedAt: string;
  hasCustoms: boolean;
}

function labelFromRef(
  ref?: { companyName?: string; label?: string; name?: string; code?: string },
  fallback = "—",
): string {
  if (!ref) return fallback;
  return ref.companyName ?? ref.label ?? ref.name ?? ref.code ?? fallback;
}

function toClearanceRow(booking: BookingDetail): ClearanceRow {
  return {
    id: booking.id,
    reference: booking.reference,
    customerLabel: booking.isGovernment
      ? (booking.governmentInstitution ?? "Government")
      : labelFromRef(booking.company, booking.companyId ?? undefined),
    tradeDirection: booking.tradeDirection ?? "—",
    freightType: booking.freightType ?? "—",
    originLabel: labelFromRef(booking.originYard),
    destinationLabel: labelFromRef(booking.destinationYard),
    scheduledDate: booking.scheduledDate,
    updatedAt: booking.updatedAt ?? "",
    hasCustoms: Boolean(
      booking.customsClearingEnabled ?? booking.serviceType?.includesCustoms,
    ),
  };
}

function formatDate(iso?: string): string {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString(undefined, {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function DirectionIcon({ direction }: { direction: string }) {
  const isImport = direction === "IMPORT";
  const Icon = isImport ? Truck : ShipWheel;
  const label = isImport ? "Import" : direction === "EXPORT" ? "Export" : "—";
  return (
    <Tooltip label={label} withArrow>
      <ThemeIcon
        variant="light"
        color={isImport ? "edr-green" : "gray"}
        radius="md"
        size={28}
        aria-label={label}
      >
        <Icon size={15} strokeWidth={1.9} />
      </ThemeIcon>
    </Tooltip>
  );
}

export default function DocumentClearanceListPage({
  opsMode = false,
}: {
  /**
   * true → Operations self-clearance queue: NON-customs bookings whose
   * per-booking clearance docs the operations team reviews (GENERAL Path A).
   * false → legacy GL queue: customs bookings only.
   */
  opsMode?: boolean;
}) {
  const navigate = useNavigate();
  const [pageTab, setPageTab] = useState<PageTab>("queue");
  const [activeTab, setActiveTab] = useState<ClearanceTabKey>("all");
  const [query, setQuery] = useState("");
  const [view, setView] = useState<ViewMode>("table");
  const { pagination, setPagination } = usePagination({ pageSize: 10 });

  const isHistory = pageTab === "history";

  const { data, isLoading, isError, isFetching, refetch } = useQuery({
    queryKey: ["clearance", "list", isHistory, opsMode],
    queryFn: () =>
      bookingsService.list({
        status: isHistory ? CLEARANCE_HISTORY_STATUS : CLEARANCE_REVIEW_STATUS,
        pageSize: 200,
      }),
  });

  const allRows = useMemo(() => {
    // opsMode: self-clearance (non-customs) bookings; else customs bookings only.
    const rows = (data?.items ?? [])
      .map(toClearanceRow)
      .filter((r) => (opsMode ? !r.hasCustoms : r.hasCustoms));

    if (isHistory) {
      return [...rows].sort((a, b) => {
        const ta = new Date(a.updatedAt || 0).getTime();
        const tb = new Date(b.updatedAt || 0).getTime();
        return tb - ta;
      });
    }
    return rows;
  }, [data?.items, isHistory, opsMode]);

  const tabCounts = useMemo(
    () => ({
      all: allRows.length,
      import: allRows.filter((r) => r.tradeDirection === "IMPORT").length,
      export: allRows.filter((r) => r.tradeDirection === "EXPORT").length,
    }),
    [allRows],
  );

  const rows = useMemo(() => {
    const q = query.trim().toLowerCase();
    return allRows.filter((r) => {
      if (activeTab === "import" && r.tradeDirection !== "IMPORT") return false;
      if (activeTab === "export" && r.tradeDirection !== "EXPORT") return false;
      if (!q) return true;
      return (
        r.reference.toLowerCase().includes(q) ||
        r.customerLabel.toLowerCase().includes(q) ||
        r.originLabel.toLowerCase().includes(q) ||
        r.destinationLabel.toLowerCase().includes(q)
      );
    });
  }, [allRows, activeTab, query]);

  const total = rows.length;
  const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));

  const pagedRows = useMemo(() => {
    const start = pagination.pageIndex * pagination.pageSize;
    return rows.slice(start, start + pagination.pageSize);
  }, [rows, pagination.pageIndex, pagination.pageSize]);

  const openDetail = useCallback(
    (id: string) => navigate(`/dashboard/clearance/${id}`),
    [navigate],
  );

  const statusBadge = isHistory ? (
    <Badge
      variant="light"
      color="edr-green"
      radius="sm"
      leftSection={<CheckCircle size={13} />}
    >
      {tabCounts.all} cleared
    </Badge>
  ) : (
    <Badge
      variant="light"
      color="edr-green"
      radius="sm"
      leftSection={<ShieldCheck size={13} />}
    >
      {tabCounts.all} awaiting review
    </Badge>
  );

  const columns: ColumnDef<ClearanceRow>[] = useMemo(
    () => [
      {
        id: "booking",
        header: () => <span className={bookingTable.headerCell}>Booking</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <div className="flex items-center gap-3 py-1.5">
              <div className={bookingTable.rowIcon}>
                <ShieldCheck className="size-4" strokeWidth={1.75} />
              </div>
              <div className="min-w-0">
                <p className="truncate font-medium text-foreground">
                  {r.reference}
                </p>
                <p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
                  <User className="size-3 shrink-0 opacity-70" />
                  {r.customerLabel}
                </p>
              </div>
            </div>
          );
        },
      },
      {
        id: "route",
        header: () => <span className={bookingTable.headerCell}>Route</span>,
        cell: ({ row }) => {
          const r = row.original;
          return (
            <Stack gap={4} py={2}>
              <Group gap={6} wrap="nowrap">
                <Text size="sm" fw={500} truncate maw={120}>
                  {r.originLabel}
                </Text>
                <ArrowRight size={14} className="shrink-0 text-muted-foreground" />
                <Text size="sm" fw={500} truncate maw={120}>
                  {r.destinationLabel}
                </Text>
              </Group>
              <Group gap={8} align="center">
                <DirectionIcon direction={r.tradeDirection} />
                <Badge size="xs" variant="default" radius="sm">
                  {r.freightType}
                </Badge>
              </Group>
            </Stack>
          );
        },
      },
      {
        id: "scheduled",
        header: () => <span className={bookingTable.headerCell}>Scheduled</span>,
        cell: ({ row }) => (
          <span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
            <Calendar className="size-3.5" />
            {formatDate(row.original.scheduledDate)}
          </span>
        ),
      },
      {
        id: "status",
        header: () => <span className={bookingTable.headerCell}>Status</span>,
        cell: () =>
          isHistory ? (
            <Badge size="sm" variant="light" color="edr-green" radius="sm">
              Cleared
            </Badge>
          ) : (
            <Badge size="sm" variant="light" color="yellow" radius="sm">
              Under review
            </Badge>
          ),
      },
      {
        id: "go",
        size: 56,
        cell: () => (
          <Group justify="flex-end" pr="xs">
            <ChevronRight size={16} className="text-muted-foreground" />
          </Group>
        ),
      },
    ],
    [isHistory],
  );

  return (
    <PageContainer>
      <Stack gap="lg">
        <PageHeader
          title={opsMode ? "Self-Clearance Review" : "Document Clearance"}
          subtitle={
            opsMode
              ? "Review the customer's own clearance documents per shipment booking, raise queries, and finalize."
              : "Review customer documents, raise queries, and finalize document approval for each booking."
          }
          meta={statusBadge}
          action={
            <ActionIcon
              variant="default"
              size="lg"
              radius="md"
              onClick={() => refetch()}
              loading={isFetching}
              aria-label="Refresh"
            >
              <RefreshCw size={16} />
            </ActionIcon>
          }
        />

        <Group>
          <SegmentedControl
            value={pageTab}
            onChange={(v) => {
              setPageTab(v as PageTab);
              setActiveTab("all");
              setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
            }}
            data={[
              {
                value: "queue",
                label: (
                  <Group gap={6} wrap="nowrap">
                    <Inbox size={14} />
                    <span>Queue</span>
                  </Group>
                ),
              },
              {
                value: "history",
                label: (
                  <Group gap={6} wrap="nowrap">
                    <History size={14} />
                    <span>History</span>
                  </Group>
                ),
              },
            ]}
            radius="md"
          />
        </Group>

        <KpiStrip
          loading={isLoading}
          items={[
            {
              label: isHistory ? "Cleared" : "Awaiting review",
              value: tabCounts.all,
              icon: isHistory ? CheckCircle : Inbox,
              color: "edr-green",
            },
            {
              label: "Import",
              value: tabCounts.import,
              icon: Truck,
              color: "edr-green",
            },
            {
              label: "Export",
              value: tabCounts.export,
              icon: ShipWheel,
              color: "gray",
            },
          ]}
        />

        <Tabs
          value={activeTab}
          onChange={(v) => {
            setActiveTab((v as ClearanceTabKey) ?? "all");
            setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
          }}
          variant="pills"
          color="edr-green"
        >
          <ScrollArea type="auto" scrollbarSize={6} offsetScrollbars="x">
            <Tabs.List style={{ flexWrap: "nowrap", width: "max-content" }}>
              {CLEARANCE_TABS.map((tab) => {
                const Icon = tab.icon;
                const isActive = activeTab === tab.key;
                return (
                  <Tabs.Tab
                    key={tab.key}
                    value={tab.key}
                    leftSection={<Icon size={15} />}
                    rightSection={
                      <Badge
                        size="sm"
                        radius="sm"
                        variant={isActive ? "white" : "light"}
                        color={isActive ? "edr-green" : "gray"}
                      >
                        {tabCounts[tab.key]}
                      </Badge>
                    }
                  >
                    {tab.label}
                  </Tabs.Tab>
                );
              })}
            </Tabs.List>
          </ScrollArea>
        </Tabs>

        <Card p={0} withBorder shadow="sm" radius="lg">
          <Stack gap={0}>
            <Box px="md" pt="md" pb="sm">
              <Group justify="space-between" gap="md" wrap="wrap">
                <TextInput
                  placeholder="Search reference, customer, or route…"
                  leftSection={<Search size={18} />}
                  value={query}
                  onChange={(e) => {
                    setQuery(e.currentTarget.value);
                    setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
                  }}
                  rightSection={
                    query ? (
                      <ActionIcon
                        size="sm"
                        color="gray"
                        radius="md"
                        variant="transparent"
                        onClick={() => setQuery("")}
                      >
                        <X size={16} />
                      </ActionIcon>
                    ) : null
                  }
                  radius="lg"
                  style={{ flex: 1, minWidth: 220 }}
                />
                <Group gap="sm" wrap="nowrap">
                  <Text size="sm" c="dimmed">
                    {total} record{total !== 1 ? "s" : ""}
                  </Text>
                  <SegmentedControl
                    size="sm"
                    radius="md"
                    value={view}
                    onChange={(v) => setView(v as ViewMode)}
                    data={[
                      {
                        value: "table",
                        label: (
                          <Group gap={6} wrap="nowrap">
                            <TableIcon size={15} />
                            <Box visibleFrom="sm">Table</Box>
                          </Group>
                        ),
                      },
                      {
                        value: "cards",
                        label: (
                          <Group gap={6} wrap="nowrap">
                            <LayoutGrid size={15} />
                            <Box visibleFrom="sm">Cards</Box>
                          </Group>
                        ),
                      },
                    ]}
                  />
                </Group>
              </Group>
            </Box>

            {view === "table" ? (
              <Box style={{ overflowX: "auto" }} px="xs" pb="xs">
                <DataTable<ClearanceRow, unknown>
                  columns={columns}
                  data={pagedRows}
                  status={isLoading ? "loading" : isError ? "error" : "success"}
                  onRowClick={(row) => openDetail(row.id)}
                  pagination={{
                    pageIndex: pagination.pageIndex,
                    pageSize: pagination.pageSize,
                    pageCount,
                    totalCount: total,
                  }}
                  tableOptions={{
                    state: { pagination },
                    onPaginationChange: setPagination,
                    manualPagination: true,
                    pageCount,
                  }}
                  containerClassName="border-0 shadow-none bg-transparent"
                  footer={DataTableFooter}
                />
              </Box>
            ) : (
              <ClearanceCardGrid
                rows={pagedRows}
                loading={isLoading}
                isHistory={isHistory}
                onOpen={openDetail}
              />
            )}
          </Stack>
        </Card>
      </Stack>
    </PageContainer>
  );
}

function ClearanceCardGrid({
  rows,
  loading,
  isHistory,
  onOpen,
}: {
  rows: ClearanceRow[];
  loading: boolean;
  isHistory: boolean;
  onOpen: (id: string) => void;
}) {
  if (loading) {
    return (
      <Box px="md" py="xl">
        <Text c="dimmed" ta="center">
          Loading…
        </Text>
      </Box>
    );
  }
  if (rows.length === 0) {
    return (
      <Stack align="center" gap={8} py={48}>
        <ThemeIcon variant="light" color="gray" radius="xl" size={48}>
          <Inbox size={22} />
        </ThemeIcon>
        <Text c="dimmed">No bookings match this view.</Text>
      </Stack>
    );
  }
  return (
    <SimpleGrid cols={{ base: 1, sm: 2, xl: 3 }} spacing="md" p="md">
      {rows.map((r) => (
        <ClearanceCard
          key={r.id}
          row={r}
          isHistory={isHistory}
          onOpen={() => onOpen(r.id)}
        />
      ))}
    </SimpleGrid>
  );
}

function ClearanceCard({
  row,
  isHistory,
  onOpen,
}: {
  row: ClearanceRow;
  isHistory: boolean;
  onOpen: () => void;
}) {
  return (
    <Card
      withBorder
      shadow="sm"
      radius="lg"
      p="md"
      onClick={onOpen}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onOpen();
        }
      }}
      style={{ cursor: "pointer", transition: "all 120ms ease" }}
      className="hover:border-edr-green-4 hover:shadow-md"
    >
      <Group justify="space-between" align="flex-start" wrap="nowrap">
        <Group gap={10} wrap="nowrap" style={{ minWidth: 0 }}>
          <ThemeIcon variant="light" color="edr-green" radius="md" size={40}>
            <ShieldCheck size={19} />
          </ThemeIcon>
          <Box style={{ minWidth: 0 }}>
            <Text fw={700} size="sm" c="edr-text" truncate>
              {row.reference}
            </Text>
            <Group gap={4} wrap="nowrap">
              <User size={11} className="shrink-0 opacity-70" />
              <Text size="xs" c="dimmed" truncate>
                {row.customerLabel}
              </Text>
            </Group>
          </Box>
        </Group>
        {isHistory ? (
          <Badge size="sm" variant="light" color="edr-green" radius="sm">
            Cleared
          </Badge>
        ) : (
          <Badge size="sm" variant="light" color="yellow" radius="sm">
            Under review
          </Badge>
        )}
      </Group>

      <Box
        mt="md"
        p="sm"
        style={{
          borderRadius: 12,
          background: "var(--mantine-color-edr-card-6)",
          border: "1px solid var(--mantine-color-edr-border-6)",
        }}
      >
        <Group gap={8} wrap="nowrap" justify="center">
          <Text size="sm" fw={600} truncate maw={130}>
            {row.originLabel}
          </Text>
          <ArrowRight size={15} className="shrink-0 text-muted-foreground" />
          <Text size="sm" fw={600} truncate maw={130}>
            {row.destinationLabel}
          </Text>
        </Group>
      </Box>

      <Group justify="space-between" mt="md" wrap="nowrap">
        <Group gap={8} wrap="nowrap">
          <DirectionIcon direction={row.tradeDirection} />
          <Badge size="xs" variant="default" radius="sm">
            {row.freightType}
          </Badge>
          {row.hasCustoms ? (
            <Tooltip label="Customs clearance" withArrow>
              <ThemeIcon
                variant="light"
                color="edr-green"
                radius="md"
                size={28}
                aria-label="Customs clearance"
              >
                <ShieldCheck size={15} strokeWidth={1.9} />
              </ThemeIcon>
            </Tooltip>
          ) : null}
        </Group>
        <Group gap={4} wrap="nowrap">
          <Calendar size={13} className="text-muted-foreground" />
          <Text size="xs" c="dimmed">
            {formatDate(row.scheduledDate)}
          </Text>
        </Group>
      </Group>
    </Card>
  );
}
