import { useState } from "react";
import { ActionIcon, Badge, Box, Card, Group, Stack, Text, ThemeIcon, Tooltip } from "@mantine/core";
import { Building2, Package, TrainFront, Weight, X } from "lucide-react";
import type { TrainScheduleDetail } from "@/types/trainScheduling";
import type { BookingDetailData } from "./BookingDetailModal";
import { RemoveBookingConfirmModal, type RemovalTarget } from "./RemoveBookingConfirmModal";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useToast } from "@/hooks/use-toast";
import { freightBrand } from "@/theme/freight-brand";

interface AssignedBookingsPanelProps {
  scheduleDetail: TrainScheduleDetail;
  scheduleId: string;
  selectedBookingId?: string | null;
  onSelect: (booking: BookingDetailData) => void;
}

export const AssignedBookingsPanel = ({
  scheduleDetail,
  scheduleId,
  selectedBookingId,
  onSelect,
}: AssignedBookingsPanelProps) => {
  const { toast } = useToast();
  const unassign = useMutation(api.trainScheduling.unassignBooking.mutationOptions());
  const isDispatched = scheduleDetail.status === "DISPATCHED";
  const [removalTarget, setRemovalTarget] = useState<RemovalTarget | null>(null);

  const wagons = scheduleDetail.trainSet?.wagons ?? [];
  const wagonCountByBooking = new Map<string, number>();
  for (const w of wagons) {
    for (const a of w.allocations ?? []) {
      wagonCountByBooking.set(a.bookingId, (wagonCountByBooking.get(a.bookingId) ?? 0) + 1);
    }
  }

  const assignedBookings = (scheduleDetail.bookings ?? []).filter((b) =>
    wagonCountByBooking.has(b.id),
  );

  const handleConfirmRemove = async () => {
    if (!removalTarget) return;
    try {
      await unassign.mutateAsync({ id: scheduleId, bookingId: removalTarget.bookingId });
      toast({ title: "Booking removed from train" });
      setRemovalTarget(null);
    } catch {
      toast({ title: "Could not remove booking", variant: "destructive" });
    }
  };

  if (assignedBookings.length === 0) {
    return (
      <Stack align="center" gap="xs" py="xl">
        <ThemeIcon size={44} radius="xl" variant="light" color="gray">
          <Package size={20} />
        </ThemeIcon>
        <Text size="sm" fw={600} c="gray.7">
          No assigned bookings
        </Text>
        <Text size="xs" c="dimmed" ta="center" maw={220}>
          Assign a paid booking from the Unassigned tab to load it onto a wagon.
        </Text>
      </Stack>
    );
  }

  return (
    <>
    <Stack gap="xs">
      {assignedBookings.map((booking) => {
        const isActive = selectedBookingId === booking.id;
        return (
          <Card
            key={booking.id}
            padding="xs"
            radius="md"
            withBorder
            onClick={() =>
              onSelect({
                bookingId: booking.id,
                reference: booking.reference,
                company: booking.customer,
                freightType: scheduleDetail.freightType ?? null,
                weightTons: booking.weightTons ?? null,
                status: booking.status,
              })
            }
            style={{
              cursor: "pointer",
              borderColor: isActive ? freightBrand.primary : undefined,
              boxShadow: isActive ? `0 0 0 2px ${freightBrand.ring}` : undefined,
              background: isActive ? freightBrand.mutedBg : undefined,
              transition: "box-shadow 120ms ease",
            }}
          >
            <Group gap={8} wrap="nowrap" align="flex-start">
              <ThemeIcon size={30} radius="md" variant="light" color="edr-green">
                <Package size={16} />
              </ThemeIcon>
              <Box style={{ flex: 1, minWidth: 0 }}>
                <Group justify="space-between" wrap="nowrap" gap={4}>
                  <Text size="sm" fw={700} truncate>
                    {booking.reference}
                  </Text>
                  <Group gap={4} wrap="nowrap">
                    <Badge
                      size="xs"
                      variant="light"
                      color="edr-green"
                      leftSection={<TrainFront size={9} />}
                    >
                      {wagonCountByBooking.get(booking.id)}
                    </Badge>
                    {!isDispatched ? (
                      <Tooltip label="Remove from train" withArrow>
                        <ActionIcon
                          size="sm"
                          variant="subtle"
                          color="red"
                          loading={unassign.isPending && unassign.variables?.bookingId === booking.id}
                          onClick={(e) => {
                            e.stopPropagation();
                            setRemovalTarget({
                              bookingId: booking.id,
                              reference: booking.reference,
                              company: booking.customer,
                              weightTons: booking.weightTons ?? null,
                              wagonCount: wagonCountByBooking.get(booking.id) ?? 0,
                            });
                          }}
                        >
                          <X size={14} />
                        </ActionIcon>
                      </Tooltip>
                    ) : null}
                  </Group>
                </Group>
                {booking.customer ? (
                  <Group gap={4} wrap="nowrap">
                    <Building2 size={11} color="var(--mantine-color-gray-6)" />
                    <Text size="11px" c="dimmed" truncate>
                      {booking.customer}
                    </Text>
                  </Group>
                ) : null}
                <Group gap={4} wrap="nowrap" mt={2}>
                  <Weight size={11} color="var(--mantine-color-gray-6)" />
                  <Text size="11px" c="dimmed">
                    {(booking.weightTons ?? 0).toFixed(1)} T
                  </Text>
                </Group>
              </Box>
            </Group>
          </Card>
        );
      })}
    </Stack>

    <RemoveBookingConfirmModal
      opened={Boolean(removalTarget)}
      onClose={() => setRemovalTarget(null)}
      onConfirm={handleConfirmRemove}
      isLoading={unassign.isPending}
      target={removalTarget}
    />
    </>
  );
};
