import { useState, useEffect } 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 { useCreateTrain, useUpdateTrain } from '@/hooks/useTrains';
import { useToast } from '@/hooks/use-toast';

interface TrainFormDialogProps {
  trigger?: React.ReactNode;
  train?: any;
  onSuccess?: () => void;
}

export function TrainFormDialog({ trigger, train, onSuccess }: TrainFormDialogProps) {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ code: '', capacityTons: 0, trainNumber: '', trainName: '' });
  const createTrain = useCreateTrain();
  const updateTrain = useUpdateTrain();
  const { toast } = useToast();

  useEffect(() => {
    if (train) setForm({
      code: train.code,
      capacityTons: train.capacityTons,
      trainNumber: train.trainNumber || '',
      trainName: train.trainName || '',
    });
  }, [train]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (train) await updateTrain.mutateAsync({ id: train.id, data: form });
      else await createTrain.mutateAsync(form);
      toast({ title: train ? 'Train updated' : 'Train created', description: `${form.code} saved.` });
      setOpen(false);
      onSuccess?.();
    } catch {
      toast({ title: 'Error', description: `Failed to ${train ? 'update' : 'create'} train.`, variant: 'destructive' });
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger || <Button>New Train</Button>}</DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>{train ? 'Edit Train' : 'Create Train'}</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div><Label>Code*</Label><Input required value={form.code} onChange={e => setForm({...form, code: e.target.value})} /></div>
          <div><Label>Capacity (tons)*</Label><Input type="number" required value={form.capacityTons} onChange={e => setForm({...form, capacityTons: parseFloat(e.target.value)})} /></div>
          <div><Label>Train Number</Label><Input value={form.trainNumber} onChange={e => setForm({...form, trainNumber: e.target.value})} /></div>
          <div><Label>Train Name</Label><Input value={form.trainName} onChange={e => setForm({...form, trainName: e.target.value})} /></div>
          <Button type="submit" disabled={createTrain.isPending || updateTrain.isPending}>Save</Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}