import { useMemo, useState } from "react";
import { Badge, Box, Group, Paper, ScrollArea, Tabs, Text, Tooltip } from "@mantine/core";
import { CreditCard, History, Layers, PackageCheck, PackagePlus, XCircle } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import type { BatchBoardBookingDetail, TrainScheduleDetail } from "@/types/trainScheduling";
import { AssignedBookingsPanel } from "./AssignedBookingsPanel";
import { UnassignedBookingsPanel } from "./UnassignedBookingsPanel";
import { RemovalLogPanel } from "./RemovalLogPanel";
import { BatchBookingList } from "./BatchBookingList";
import { BookingDetailModal, type BookingDetailData } from "./BookingDetailModal";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { freightBrand } from "@/theme/freight-brand";

interface CompositionBookingTabsProps {
  scheduleDetail: TrainScheduleDetail;
  scheduleId: string;
  /** Bookings selected for batch with a payment notification sent (awaiting payment). */
  awaitingPayment?: BatchBoardBookingDetail[];
  /** Bookings whose payment window expired. */
  expired?: BatchBoardBookingDetail[];
  /** Booking id highlighted in the train consist (lifted to the page). */
  selectedBookingId?: string | null;
  onSelectBooking?: (bookingId: string | null) => void;
}

type TabKey = "assigned" | "unassigned" | "payment" | "expired" | "removed";

const TAB_META: Record<TabKey, { label: string; icon: LucideIcon; color: string }> = {
  assigned: { label: "Assigned to train", icon: PackageCheck, color: "edr-green" },
  unassigned: { label: "Unassigned (ready to load)", icon: PackagePlus, color: "orange" },
  payment: { label: "Awaiting payment", icon: CreditCard, color: "orange" },
  expired: { label: "Expired bookings", icon: XCircle, color: "red" },
  removed: { label: "Removed from train", icon: History, color: "gray" },
};

export const CompositionBookingTabs = ({
  scheduleDetail,
  scheduleId,
  awaitingPayment = [],
  expired = [],
  selectedBookingId,
  onSelectBooking,
}: CompositionBookingTabsProps) => {
  const [detailBooking, setDetailBooking] = useState<BookingDetailData | null>(null);
  const [tab, setTab] = useState<TabKey>("assigned");

  const unassignedQuery = useQuery(
    api.trainScheduling.unassignedBookings.queryOptions({
      input: { scheduleId },
      enabled: Boolean(scheduleId),
    }),
  );
  const removalsQuery = useQuery(
    api.trainScheduling.compositionRemovals.queryOptions({
      input: { scheduleId },
      enabled: Boolean(scheduleId),
    }),
  );

  const { assignedCount } = useMemo(() => {
    const wagons = scheduleDetail.trainSet?.wagons ?? [];
    const ids = new Set<string>();
    for (const w of wagons) {
      for (const a of w.allocations ?? []) {
        ids.add(a.bookingId);
      }
    }
    return { assignedCount: ids.size };
  }, [scheduleDetail.trainSet?.wagons]);

  const counts: Record<TabKey, number> = {
    assigned: assignedCount,
    unassigned: unassignedQuery.data?.bookings?.length ?? 0,
    payment: awaitingPayment.length,
    expired: expired.length,
    removed: removalsQuery.data?.length ?? 0,
  };

  const handleSelect = (booking: BookingDetailData) => {
    setDetailBooking(booking);
    onSelectBooking?.(booking.bookingId);
  };

  const TabButton = ({ value }: { value: TabKey }) => {
    const meta = TAB_META[value];
    const Icon = meta.icon;
    const active = tab === value;
    const count = counts[value];
    return (
      <Tooltip label={meta.label} withArrow position="top">
        <Tabs.Tab value={value} px={6}>
          <Group gap={5} wrap="nowrap" justify="center">
            <Icon size={15} />
            <Badge
              size="xs"
              circle
              variant={active ? "filled" : "light"}
              color={active ? meta.color : "gray"}
            >
              {count}
            </Badge>
          </Group>
        </Tabs.Tab>
      </Tooltip>
    );
  };

  return (
    <>
      <Paper
        radius="lg"
        withBorder
        style={{
          height: "100%",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column",
          borderColor: "var(--mantine-color-gray-2)",
        }}
      >
        {/* Header — reflects the active tab */}
        <Group
          justify="space-between"
          wrap="nowrap"
          px="md"
          py="sm"
          style={{
            background: `linear-gradient(135deg, ${freightBrand.mutedBg}, white)`,
            borderBottom: "1px solid var(--mantine-color-gray-2)",
          }}
        >
          <Group gap={10} wrap="nowrap">
            <Box
              style={{
                width: 34,
                height: 34,
                borderRadius: 9,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                background: freightBrand.gradient,
                color: "white",
              }}
            >
              <Layers size={18} />
            </Box>
            <div>
              <Text fw={800} size="sm">
                {TAB_META[tab].label}
              </Text>
              <Text size="11px" c="dimmed">
                {counts[tab]} booking{counts[tab] === 1 ? "" : "s"}
              </Text>
            </div>
          </Group>
        </Group>

        <Tabs
          value={tab}
          onChange={(v) => v && setTab(v as TabKey)}
          variant="default"
          color="edr-green"
          style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}
        >
          <Tabs.List grow>
            <TabButton value="assigned" />
            <TabButton value="unassigned" />
            <TabButton value="payment" />
            <TabButton value="expired" />
            <TabButton value="removed" />
          </Tabs.List>

          <ScrollArea style={{ flex: 1 }} type="auto" offsetScrollbars>
            <Tabs.Panel value="assigned" p="md">
              <AssignedBookingsPanel
                scheduleDetail={scheduleDetail}
                scheduleId={scheduleId}
                selectedBookingId={selectedBookingId}
                onSelect={handleSelect}
              />
            </Tabs.Panel>

            <Tabs.Panel value="unassigned" p="md">
              <UnassignedBookingsPanel
                scheduleId={scheduleId}
                selectedBookingId={selectedBookingId}
                onSelect={handleSelect}
              />
            </Tabs.Panel>

            <Tabs.Panel value="payment" p="md">
              <BatchBookingList
                bookings={awaitingPayment}
                variant="payment"
                selectedBookingId={selectedBookingId}
                onSelect={handleSelect}
                emptyTitle="No bookings awaiting payment"
                emptyHint="Bookings selected for this batch with a payment notification sent will appear here."
              />
            </Tabs.Panel>

            <Tabs.Panel value="expired" p="md">
              <BatchBookingList
                bookings={expired}
                variant="expired"
                selectedBookingId={selectedBookingId}
                onSelect={handleSelect}
                emptyTitle="No expired bookings"
                emptyHint="Bookings whose payment window lapsed will appear here."
              />
            </Tabs.Panel>

            <Tabs.Panel value="removed" p="md">
              <RemovalLogPanel scheduleId={scheduleId} />
            </Tabs.Panel>
          </ScrollArea>
        </Tabs>

        {/* Footer summary */}
        <Group
          justify="space-between"
          px="md"
          py="xs"
          style={{
            borderTop: "1px solid var(--mantine-color-gray-2)",
            background: "var(--mantine-color-gray-0)",
          }}
        >
          <Group gap={5} wrap="nowrap">
            <PackageCheck size={13} color="var(--mantine-color-edr-green-7)" />
            <Text size="xs" c="dimmed">
              {assignedCount} on train
            </Text>
          </Group>
          <Group gap={5} wrap="nowrap">
            <CreditCard size={13} color="var(--mantine-color-orange-6)" />
            <Text size="xs" c="dimmed">
              {counts.payment} to pay
            </Text>
          </Group>
          <Group gap={5} wrap="nowrap">
            <XCircle size={13} color="var(--mantine-color-red-6)" />
            <Text size="xs" c="dimmed">
              {counts.expired} expired
            </Text>
          </Group>
        </Group>
      </Paper>

      <BookingDetailModal
        opened={Boolean(detailBooking)}
        onClose={() => setDetailBooking(null)}
        booking={detailBooking}
        wagons={scheduleDetail.trainSet?.wagons ?? []}
      />
    </>
  );
};
