import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useMutation } from '@tanstack/react-query';
import { api } from '@/services/api';
import { useToast } from '@/hooks/use-toast';

export function LoadCargoDialog({ cargoId, onSuccess }: { cargoId: string; onSuccess?: () => void }) {
  const [open, setOpen] = useState(false);
  const [quantity, setQuantity] = useState(0);
  const [weight, setWeight] = useState(0);
  const [volume, setVolume] = useState<number>();
  const load = useMutation(api.cargoes.load.mutationOptions());
  const { toast } = useToast();

  const handleLoad = async () => {
    await load.mutateAsync({ id: cargoId, quantity, weight, volume });
    toast({ title: 'Loaded', description: 'Cargo loaded into container.' });
    setOpen(false);
    onSuccess?.();
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild><Button size="sm">Load Cargo</Button></DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>Load Cargo</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Quantity*</Label><Input type="number" required value={quantity} onChange={e => setQuantity(parseFloat(e.target.value))} /></div>
          <div><Label>Weight (kg)*</Label><Input type="number" required value={weight} onChange={e => setWeight(parseFloat(e.target.value))} /></div>
          <div><Label>Volume (m³)</Label><Input type="number" value={volume ?? ''} onChange={e => setVolume(parseFloat(e.target.value) || undefined)} /></div>
          <Button onClick={handleLoad} disabled={load.isPending}>Confirm Load</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}