import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
// import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useWagons, useAssignWagonToTrain } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@edr/ui-common';

export function AssignWagonDialog({ trainId }: { trainId: string }) {
  const [open, setOpen] = useState(false);
  const [wagonId, setWagonId] = useState('');
  const [sequence, setSequence] = useState<number>();
  const { data: wagons } = useWagons();
  const assign = useAssignWagonToTrain();
  const { toast } = useToast();

  const available = wagons?.filter((w:any) => w.status === 'AVAILABLE' || !w.trainId);

  const handleAssign = async () => {
    if (!wagonId) return;
    await assign.mutateAsync({ wagonId, trainId, sequenceNumber: sequence });
    toast({ title: 'Assigned', description: 'Wagon attached to train.' });
    setOpen(false);
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Wagon</Button></DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>Assign Wagon to Train</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div>
            <Label>Wagon</Label>
            <Select value={wagonId} onValueChange={setWagonId}>
              <SelectTrigger><SelectValue placeholder="Select wagon" /></SelectTrigger>
              <SelectContent>
                {available?.map((w:any) => <SelectItem key={w.id} value={w.id}>{w.wagonNumber}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
          <div>
            <Label>Sequence (optional)</Label>
            <Input type="number" value={sequence ?? ''} onChange={e => setSequence(parseInt(e.target.value) || undefined)} />
          </div>
          <Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}