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 '@edr/ui-common';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useContainers, useAssignContainerToWagon } from './use-containers';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';

export function AssignContainerDialog({ wagonId }: { wagonId: string }) {
  const [open, setOpen] = useState(false);
  const [containerId, setContainerId] = useState('');
  const [position, setPosition] = useState<number>();
  const { data: containers } = useContainers();
  const assign = useAssignContainerToWagon();
  const { toast } = useToast();

  const available = containers?.filter(c => c.status === 'AVAILABLE' && !c.wagonId);

  const handleAssign = async () => {
    if (!containerId) return;
    await assign.mutateAsync({ containerId, wagonId, position });
    toast({ title: 'Assigned', description: 'Container placed on wagon.' });
    setOpen(false);
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Container</Button></DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>Assign Container to Wagon</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Container</Label><Select value={containerId} onValueChange={setContainerId}><SelectTrigger><SelectValue placeholder="Select container" /></SelectTrigger><SelectContent>{available?.map(c => <SelectItem key={c.id} value={c.id}>{c.containerNumber}</SelectItem>)}</SelectContent></Select></div>
          <div><Label>Position (optional)</Label><Input type="number" value={position ?? ''} onChange={e => setPosition(parseInt(e.target.value) || undefined)} /></div>
          <Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}