import { useMemo } from "react";
import { Trash2 } from "lucide-react";
import type { ColumnDef } from "@edr/ui-common";
import { ActionIcon, Badge, Group, Text, Tooltip } from "@mantine/core";

import { useMutation, useQuery } from "@tanstack/react-query";

import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
import { api } from "@/services/api";
import { useToast } from "@/hooks/use-toast";
import type { Wagon } from "@/services/wagon.service";
import { DataTable } from "@edr/ui-common";

export function WagonsTable({ trainId }: { trainId: string }) {
  const { data: wagons = [], isLoading, refetch } = useQuery(
    api.wagons.listByTrain.queryOptions({
      input: { trainId },
      enabled: !!trainId,
    }),
  );
  const unassign = useMutation(api.wagons.unassign.mutationOptions());
  const { toast } = useToast();

  const columns = useMemo((): ColumnDef<Wagon>[] => {
    const headerClassName = ruleEngineTable.headerCell;
    const cellClassName = ruleEngineTable.bodyCell;
    return [
      {
        id: "wagonNumber",
        header: "Number",
        meta: { headerClassName, cellClassName },
        cell: ({ row }) => row.original.wagonNumber,
      },
      {
        id: "wagonTypeId",
        header: "Type",
        meta: { headerClassName, cellClassName },
        cell: ({ row }) => row.original.wagonTypeId,
      },
      {
        id: "sequenceNumber",
        header: "Sequence",
        meta: { headerClassName, cellClassName },
        cell: ({ row }) => row.original.sequenceNumber ?? "—",
      },
      {
        id: "status",
        header: "Status",
        meta: { headerClassName, cellClassName },
        cell: ({ row }) => (
          <Badge variant="light" color="gray" size="sm">
            {row.original.status}
          </Badge>
        ),
      },
      {
        id: "actions",
        header: "Actions",
        meta: { headerClassName, cellClassName },
        cell: ({ row }) => (
          <Group justify="flex-end">
            <Tooltip label="Unassign">
              <ActionIcon
                variant="subtle"
                color="red"
                loading={unassign.isPending}
                onClick={async () => {
                  try {
                    await unassign.mutateAsync(row.original.id);
                    await refetch();
                    toast({ title: "Wagon unassigned" });
                  } catch {
                    toast({ title: "Failed to unassign wagon", variant: "destructive" });
                  }
                }}
              >
                <Trash2 size={16} />
              </ActionIcon>
            </Tooltip>
          </Group>
        ),
      },
    ];
  }, [unassign.isPending, refetch, toast]);

  if (!isLoading && !wagons.length) {
    return (
      <Text size="sm" c="dimmed" py="md">
        No wagons assigned to this train.
      </Text>
    );
  }

  return (
    <DataTable
      columns={columns}
      data={wagons}
      status={isLoading ? "loading" : "success"}
      emptyMessage="No wagons assigned"
      containerClassName="border-0 shadow-none bg-transparent"
    />
  );
}
