import { useMutation, useQuery } from '@tanstack/react-query';
import { api } from '@/services/api';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoadCargoDialog } from './LoadCargoDialog';
import type { Cargo } from '@/services/cargoService';

export function CargoesTable({ containerId }: { containerId: string }) {
  const { data: cargoes, refetch } = useQuery(
    api.cargoes.listByContainer.queryOptions({
      input: { containerId },
      enabled: !!containerId,
    }),
  );
  const deliver = useMutation(api.cargoes.deliver.mutationOptions());
  const unload = useMutation(api.cargoes.unload.mutationOptions());

  if (!cargoes?.length) return <div className="text-muted-foreground">No cargoes for this container.</div>;

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Reference</TableHead>
          <TableHead>Description</TableHead>
          <TableHead>Quantity</TableHead>
          <TableHead>Weight (kg)</TableHead>
          <TableHead>Status</TableHead>
          <TableHead>Actions</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {cargoes.map((cargo: Cargo) => (
          <TableRow key={cargo.id}>
            <TableCell>{cargo.cargoReference}</TableCell>
            <TableCell>{cargo.description || '-'}</TableCell>
            <TableCell>{cargo.quantity}</TableCell>
            <TableCell>{cargo.weight}</TableCell>
            <TableCell><Badge variant="outline">{cargo.status}</Badge></TableCell>
            <TableCell className="space-x-2">
              {cargo.status === 'PENDING' && <LoadCargoDialog cargoId={cargo.id} onSuccess={() => refetch()} />}
              {cargo.status === 'LOADED' && <Button size="sm" onClick={() => deliver.mutateAsync({ id: cargo.id }).then(() => refetch())}>Deliver</Button>}
              {cargo.status === 'LOADED' && <Button size="sm" variant="outline" onClick={() => unload.mutateAsync({ id: cargo.id }).then(() => refetch())}>Unload</Button>}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

