import { useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  Alert,
  Badge,
  Group,
  SegmentedControl,
  Table,
  Text,
  Tooltip,
} from "@mantine/core";

import { PageContainer, PageHeader } from "@/components/page";
import ListControls from "@/components/common/ListControls";
// Generic list footer — already shared by the fleet and train-scheduling lists
// despite the ruleEngine path; reused here rather than adding a second one.
import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
import { useListControls } from "@/hooks/useListControls";
import { useTrucksOnSite } from "@/hooks/useWarehouses";
import type { TruckOnSite } from "@/types/warehouse";

/**
 * Every truck inside the yard right now, across all bookings.
 *
 * The gate's question is "which trucks are here", not "which bookings have
 * trucks" — the ops dashboard could only count them, never open the list. Both
 * haulage paths appear because the same barrier handles both: a customer's own
 * truck and an EDR last-mile truck.
 */

/** How long the truck has been on site — the number the gate actually chases. */
function dwell(arrivedAt: string | null): string {
  if (!arrivedAt) return "—";
  const minutes = Math.floor((Date.now() - new Date(arrivedAt).getTime()) / 60_000);
  if (minutes < 1) return "just now";
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ${minutes % 60}m`;
  return `${Math.floor(hours / 24)}d ${hours % 24}h`;
}

/** Long dwell means a truck is sitting at the gate — worth flagging, not hiding. */
const LONG_DWELL_HOURS = 4;

function isLongDwell(arrivedAt: string | null): boolean {
  if (!arrivedAt) return false;
  return Date.now() - new Date(arrivedAt).getTime() > LONG_DWELL_HOURS * 3_600_000;
}

function Rows({ rows }: { rows: TruckOnSite[] }) {
  if (rows.length === 0) {
    return (
      <Alert variant="light" color="gray">
        No trucks assigned or on site.
      </Alert>
    );
  }
  return (
    <Table.ScrollContainer minWidth={1040}>
      <Table striped highlightOnHover verticalSpacing="xs">
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Status</Table.Th>
            <Table.Th>Plate</Table.Th>
            <Table.Th>Haulage</Table.Th>
            <Table.Th>Driver</Table.Th>
            <Table.Th>Truck type</Table.Th>
            <Table.Th>Booking</Table.Th>
            <Table.Th>Customer</Table.Th>
            <Table.Th>Containers</Table.Th>
            <Table.Th>On site</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {rows.map((row) => (
            <Table.Tr key={`${row.source}-${row.assignmentId}`}>
              <Table.Td>
                <Badge
                  size="sm"
                  radius="sm"
                  variant={row.status === "ON_SITE" ? "filled" : "light"}
                  color={row.status === "ON_SITE" ? "edr-green" : "gray"}
                >
                  {row.status === "ON_SITE" ? "On site" : "Inbound"}
                </Badge>
              </Table.Td>
              <Table.Td>
                <Text size="sm" fw={600}>
                  {row.plateNumber ?? "—"}
                </Text>
              </Table.Td>
              <Table.Td>
                <Badge
                  size="sm"
                  radius="sm"
                  variant="light"
                  color={row.source === "CUSTOMER" ? "blue" : "edr-green"}
                >
                  {row.source === "CUSTOMER" ? "Customer" : "EDR"}
                </Badge>
              </Table.Td>
              <Table.Td>
                <Text size="sm">{row.driverName ?? "—"}</Text>
              </Table.Td>
              <Table.Td>
                <Text size="sm">{row.truckType ?? "—"}</Text>
              </Table.Td>
              <Table.Td>
                <Text size="sm">{row.bookingReference ?? "—"}</Text>
              </Table.Td>
              <Table.Td>
                <Text size="sm">{row.customerName ?? "—"}</Text>
              </Table.Td>
              <Table.Td>
                {/* Bulk trucks carry no containers — they haul loose tonnage. */}
                <Text size="sm">{row.containers ?? "Bulk"}</Text>
              </Table.Td>
              <Table.Td>
                {row.arrivedAt == null ? (
                  <Text size="sm" c="dimmed">
                    —
                  </Text>
                ) : isLongDwell(row.arrivedAt) ? (
                  <Tooltip
                    label={`On site over ${LONG_DWELL_HOURS}h — arrived ${new Date(row.arrivedAt).toLocaleString()}`}
                    withArrow
                  >
                    <Text size="sm" c="red" fw={600}>
                      {dwell(row.arrivedAt)}
                    </Text>
                  </Tooltip>
                ) : (
                  <Text size="sm">{dwell(row.arrivedAt)}</Text>
                )}
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
    </Table.ScrollContainer>
  );
}

export default function TrucksOnSitePage() {
  const { data: trucks = [], isLoading } = useTrucksOnSite();
  // The dashboard's "Trucks on-site" card counts only arrived trucks, so it
  // deep-links here with ?scope=ON_SITE to land on the matching tab.
  const [searchParams] = useSearchParams();
  const scopeParam = searchParams.get("scope");
  const [scope, setScope] = useState<"ALL" | "ON_SITE" | "INBOUND">(
    scopeParam === "ON_SITE" || scopeParam === "INBOUND" ? scopeParam : "ALL",
  );
  const [source, setSource] = useState<"ALL" | "CUSTOMER" | "EDR">("ALL");

  // Scope/source are page filters and run first; the shared control then does
  // search + arrival-date range + pagination over what they leave.
  const scoped = useMemo(
    () =>
      trucks
        .filter((t) => scope === "ALL" || t.status === scope)
        .filter((t) => source === "ALL" || t.source === source),
    [trucks, scope, source],
  );

  const controls = useListControls(scoped, {
    searchKeys: ["plateNumber", "driverName", "bookingReference", "customerName", "containers"],
    dateKey: "arrivedAt",
  });

  const onSiteCount = trucks.filter((t) => t.status === "ON_SITE").length;
  const inboundCount = trucks.length - onSiteCount;
  const customerCount = trucks.filter((t) => t.source === "CUSTOMER").length;
  const edrCount = trucks.length - customerCount;

  return (
    <PageContainer>
      <PageHeader
        title="Trucks on site"
        subtitle="Customer self-haul and EDR last-mile trucks — assigned (inbound) or arrived, until they leave the yard."
      />

      <Group justify="space-between" mb="md" wrap="wrap" gap="sm">
        <Group gap="sm" wrap="wrap">
          <SegmentedControl
            size="xs"
            value={scope}
            onChange={(v) => setScope(v as typeof scope)}
            data={[
              { label: `All (${trucks.length})`, value: "ALL" },
              { label: `On site (${onSiteCount})`, value: "ON_SITE" },
              { label: `Inbound (${inboundCount})`, value: "INBOUND" },
            ]}
          />
          <SegmentedControl
            size="xs"
            value={source}
            onChange={(v) => setSource(v as typeof source)}
            data={[
              { label: "All", value: "ALL" },
              { label: `Customer (${customerCount})`, value: "CUSTOMER" },
              { label: `EDR (${edrCount})`, value: "EDR" },
            ]}
          />
        </Group>
      </Group>

      <ListControls
        search={controls.search}
        onSearchChange={controls.setSearch}
        searchPlaceholder="Plate, driver, booking, container…"
        dateFrom={controls.dateFrom}
        onDateFromChange={controls.setDateFrom}
        dateTo={controls.dateTo}
        onDateToChange={controls.setDateTo}
        dateLabel="Arrived"
        hasFilters={controls.hasFilters}
        onReset={controls.reset}
      />

      {isLoading ? (
        <Text size="sm">Loading…</Text>
      ) : (
        <>
          <Rows rows={controls.pagedRows} />
          <RuleEngineListFooter
            pagination={controls.pagination}
            pageCount={controls.pageCount}
            totalCount={controls.totalCount}
            itemLabel="trucks"
            onPaginationChange={controls.setPagination}
          />
        </>
      )}
    </PageContainer>
  );
}
