// src/components/wagons/WagonFormDialog.tsx
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@edr/ui-common';
import { useWagonTypes } from '@/hooks/use-wagon-types';
import { useCreateWagon, useUpdateWagon } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';

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

export function WagonFormDialog({ trigger, wagon, onSuccess }: WagonFormDialogProps) {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({
    wagonNumber: '',
    wagonTypeId: '',
    tareWeight: 0,
    maxPayloadWeight: 0,
    status: 'AVAILABLE',
    notes: ''
  });
  const createWagon = useCreateWagon();
  const updateWagon = useUpdateWagon();
  const { data: wagonTypes = [], isLoading: wagonTypesLoading } = useWagonTypes();
  const { toast } = useToast();

  useEffect(() => {
    if (wagon) setForm({
      wagonNumber: wagon.wagonNumber,
      wagonTypeId: wagon.wagonTypeId,
      tareWeight: wagon.tareWeight,
      maxPayloadWeight: wagon.maxPayloadWeight,
      status: wagon.status,
      notes: wagon.notes || ''
    });
  }, [wagon]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.wagonNumber || !form.wagonTypeId) {
      toast({ title: 'Missing required field', description: 'Please select a wagon type.', variant: 'destructive' });
      return;
    }
    try {
      if (wagon) await updateWagon.mutateAsync({ id: wagon.id, data: form });
      else await createWagon.mutateAsync(form);
      toast({ title: wagon ? 'Wagon updated' : 'Wagon created', description: `${form.wagonNumber} saved.` });
      setOpen(false);
      onSuccess?.();
    } catch {
      toast({ title: 'Error', description: `Failed to ${wagon ? 'update' : 'create'} wagon.`, variant: 'destructive' });
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger || <Button>New Wagon</Button>}</DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>{wagon ? 'Edit Wagon' : 'Create Wagon'}</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div><Label>Wagon Number*</Label><Input value={form.wagonNumber} onChange={e => setForm({...form, wagonNumber: e.target.value})} /></div>
          <div>
            <Label>Wagon Type*</Label>
            <Select
              value={form.wagonTypeId}
              disabled={wagonTypesLoading}
              onValueChange={(value) => {
                const selectedType = wagonTypes.find((type: any) => type.id === value);
                setForm((current) => ({
                  ...current,
                  wagonTypeId: value,
                  maxPayloadWeight: current.maxPayloadWeight > 0
                    ? current.maxPayloadWeight
                    : Number(selectedType?.capacityTons ?? current.maxPayloadWeight),
                }));
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select wagon type" />
              </SelectTrigger>
              <SelectContent>
                {wagonTypes.map((type: any) => (
                  <SelectItem key={type.id} value={type.id}>
                    {type.code} - {type.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div><Label>Tare Weight (kg)*</Label><Input type="number" value={form.tareWeight} onChange={e => setForm({...form, tareWeight: Number(e.target.value)})} /></div>
          <div><Label>Max Payload (kg)*</Label><Input type="number" value={form.maxPayloadWeight} onChange={e => setForm({...form, maxPayloadWeight: Number(e.target.value)})} /></div>
          <div><Label>Status</Label><Input value={form.status} onChange={e => setForm({...form, status: e.target.value})} /></div>
          <div><Label>Notes</Label><Input value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} /></div>
          <Button type="submit" disabled={createWagon.isPending || updateWagon.isPending}>Save</Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
