import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
  Box,
  Button,
  Card,
  Group,
  Paper,
  Select,
  Stack,
  Text,
  TextInput,
  ThemeIcon,
  Title,
} from "@mantine/core";
import {
  CheckCircle2,
  FileStack,
  Layers,
  Plus,
  Search,
  Timer,
  X,
} from "lucide-react";

import { api } from "@/services/api";
import type { BookingListFilter } from "@/services/bookings.service";
import type { Freight } from "@edr/types";
import {
  DataTable,
  DataTableFooter,
  type ColumnDef,
  usePagination,
} from "@edr/ui-common";
import { CargoModeCell, PaymentBadge } from "../bookings/booking-display";
import { BORDER, ContractStatusBadge, INK, StatCard } from "./contract-ui";

export default function ContractsList() {
  const navigate = useNavigate();
  const { pagination, setPagination } = usePagination({ pageSize: 10 });
  const [query, setQuery] = useState("");
  const [freightFilter, setFreightFilter] = useState<string | null>(null);
  const [createdFrom, setCreatedFrom] = useState<string>("");
  const [createdTo, setCreatedTo] = useState<string>("");

  const resetPage = () =>
    setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
  const hasExtraFilters = !!freightFilter || !!createdFrom || !!createdTo;
  const clearExtraFilters = () => {
    setFreightFilter(null);
    setCreatedFrom("");
    setCreatedTo("");
    resetPage();
  };

  const filter: BookingListFilter = useMemo(
    () => ({
      bookingType: "GENERAL_CONTRACT",
      freightType: freightFilter ?? undefined,
      createdFrom: createdFrom || undefined,
      createdTo: createdTo ? `${createdTo}T23:59:59.999Z` : undefined,
      page: pagination.pageIndex + 1,
      pageSize: pagination.pageSize,
      sortBy: "createdAt",
      sortOrder: "DESC",
    }),
    [
      freightFilter,
      createdFrom,
      createdTo,
      pagination.pageIndex,
      pagination.pageSize,
    ],
  );

  const { data, isLoading, isError } = useQuery(
    api.bookings.list.queryOptions({ input: filter }),
  );

  const rows = useMemo(() => {
    const items = data?.items ?? [];
    if (!query.trim()) return items;
    const q = query.toLowerCase();
    return items.filter(
      (b) =>
        b.reference?.toLowerCase().includes(q) ||
        b.originYard?.label?.toLowerCase().includes(q) ||
        b.destinationYard?.label?.toLowerCase().includes(q),
    );
  }, [data, query]);

  const stats = useMemo(() => {
    const items = data?.items ?? [];
    const active = items.filter((b) => b.status === "CONTRACT_ACTIVE").length;
    const pending = items.filter((b) =>
      [
        "SUBMITTED",
        "PENDING_APPROVAL",
        "APPROVED_PENDING_SIGNATURE",
        "CONTRACT_READY",
        "SIGNED_CUSTOMER",
        "FULLY_EXECUTED",
      ].includes(b.status),
    ).length;
    const total = data?.meta?.total ?? items.length;
    return { active, pending, total };
  }, [data]);

  const columns: ColumnDef<Freight.IBooking>[] = [
    {
      id: "reference",
      header: () => <ColHeader label="Contract" />,
      cell: ({ row }) => {
        const b = row.original;
        return (
          <Group gap={12} wrap="nowrap" align="center">
            <ThemeIcon
              size={38}
              radius="md"
              variant="light"
              color="violet"
              style={{ flexShrink: 0 }}
            >
              <Layers size={18} />
            </ThemeIcon>
            <div>
              <Text fz={14} fw={700} style={{ color: INK }}>
                {b.reference}
              </Text>
              <Text fz={12} c="dimmed">
                {b.freightType === "CONTAINER" ? "Containerised" : "Bulk"}
              </Text>
            </div>
          </Group>
        );
      },
    },
    {
      id: "cargo",
      header: () => <ColHeader label="Cargo" />,
      cell: ({ row }) => <CargoModeCell booking={row.original} />,
    },
    {
      id: "route",
      header: () => <ColHeader label="Route" />,
      cell: ({ row }) => {
        const b = row.original;
        return (
          <Text fz={13} style={{ color: INK }}>
            {b.originYard?.label ?? "—"}{" "}
            <Text span c="dimmed">
              →
            </Text>{" "}
            {b.destinationYard?.label ?? "—"}
          </Text>
        );
      },
    },
    {
      id: "payment",
      header: () => <ColHeader label="Payment" />,
      cell: ({ row }) => <PaymentBadge status={row.original.paymentStatus} />,
    },
    {
      id: "expires",
      header: () => <ColHeader label="Ordering Until" />,
      cell: ({ row }) => {
        const exp = row.original.expiresAt;
        return (
          <Text fz={13} c={exp ? undefined : "dimmed"} style={{ color: exp ? INK : undefined }}>
            {exp ? new Date(exp).toLocaleDateString() : "—"}
          </Text>
        );
      },
    },
    {
      id: "status",
      header: () => <ColHeader label="Status" />,
      cell: ({ row }) => <ContractStatusBadge status={row.original.status} />,
    },
  ];

  const dataTableStatus = isLoading ? "loading" : isError ? "error" : "success";
  const total = data?.meta?.total ?? (data?.items?.length ?? 0);
  const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));

  return (
    <Box style={{ padding: "28px 32px 32px" }}>
      <Stack gap="lg">
        {/* Header */}
        <Group justify="space-between" align="flex-end" wrap="wrap" gap="md">
          <Group gap={14} wrap="nowrap" align="center">
            <ThemeIcon size={48} radius="lg" variant="light" color="violet">
              <Layers size={24} />
            </ThemeIcon>
            <Box>
              <Title order={1} fw={800} fz={26} style={{ letterSpacing: "-0.01em" }}>
                General Contracts
              </Title>
              <Text size="sm" c="edr-muted" mt={4} maw={520}>
                Reserve a quantity once, then place orders against it until the
                contract runs out or its window closes.
              </Text>
            </Box>
          </Group>
          <Button
            color="edr-green"
            radius="md"
            size="md"
            leftSection={<Plus size={16} />}
            onClick={() => navigate("/bookings/new")}
          >
            New Contract
          </Button>
        </Group>

        {/* Summary strip */}
        <Group gap="md" wrap="wrap" align="stretch">
          <StatCard
            label="Active"
            hint="accepting orders"
            value={stats.active}
            icon={CheckCircle2}
            color="edr-green"
          />
          <StatCard
            label="In progress"
            hint="setup / signing"
            value={stats.pending}
            icon={Timer}
            color="edr-accent"
          />
          <StatCard
            label="Total contracts"
            value={stats.total}
            icon={FileStack}
            color="violet"
          />
        </Group>

        {/* Search + filters */}
        <Paper withBorder radius="lg" p="sm" style={{ borderColor: BORDER }}>
          <Group gap={10} wrap="wrap" align="center">
            <TextInput
              placeholder="Search by reference or route…"
              leftSection={<Search size={16} />}
              value={query}
              onChange={(e) => setQuery(e.currentTarget.value)}
              radius="md"
              styles={{ input: { height: 42 } }}
              style={{ flex: 1, minWidth: 220, maxWidth: 360 }}
            />
            <Select
              placeholder="Any cargo"
              data={[
                { value: "CONTAINER", label: "Container" },
                { value: "BULK", label: "Bulk" },
              ]}
              value={freightFilter}
              onChange={(v) => {
                setFreightFilter(v);
                resetPage();
              }}
              clearable
              radius="md"
              comboboxProps={{ withinPortal: true }}
              style={{ width: 150 }}
              styles={{ input: { height: 42 } }}
              aria-label="Filter by cargo type"
            />
            <TextInput
              type="date"
              value={createdFrom}
              onChange={(e) => {
                setCreatedFrom(e.currentTarget.value);
                resetPage();
              }}
              radius="md"
              style={{ width: 152 }}
              styles={{ input: { height: 42 } }}
              aria-label="Created from"
            />
            <TextInput
              type="date"
              value={createdTo}
              onChange={(e) => {
                setCreatedTo(e.currentTarget.value);
                resetPage();
              }}
              radius="md"
              style={{ width: 152 }}
              styles={{ input: { height: 42 } }}
              aria-label="Created to"
            />
            {hasExtraFilters && (
              <Button
                variant="subtle"
                color="gray"
                radius="md"
                leftSection={<X size={14} />}
                onClick={clearExtraFilters}
              >
                Clear
              </Button>
            )}
          </Group>
        </Paper>

        {/* Table */}
        <Card p={0} style={{ overflow: "hidden" }}>
          <DataTable
            columns={columns}
            data={rows}
            status={dataTableStatus}
            onRowClick={(row) =>
              navigate(`/contracts/${(row as Freight.IBooking).id}`)
            }
            pagination={{
              pageIndex: pagination.pageIndex,
              pageSize: pagination.pageSize,
              pageCount,
              totalCount: total,
            }}
            tableOptions={{
              state: { pagination },
              onPaginationChange: setPagination,
              manualPagination: true,
              pageCount,
            }}
            footer={DataTableFooter}
            emptyMessage="No general contracts yet. Create one from New Booking → General Contract."
          />
        </Card>
      </Stack>
    </Box>
  );
}

function ColHeader({ label }: { label: string }) {
  return (
    <Text fz={12} fw={700} c="dimmed" style={{ letterSpacing: 0.3 }}>
      {label}
    </Text>
  );
}
