import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} 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 { Textarea } from '@/components/ui/textarea';
import { useCargoTypes } from './use-cargo-types';
import { useCargoMutations } from './use-cargoes';
import { Loader2 } from 'lucide-react';

interface Cargo {
  id: string;
  cargoNumber: string;
  cargoTypeId: string;
  weight: number;
  remarks?: string;
}

interface CargoFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  cargo?: Cargo | null;
  onSuccess?: () => void;
}

export default function CargoFormDialog({
  open,
  onOpenChange,
  cargo,
  onSuccess,
}: CargoFormDialogProps) {
  const { data: cargoTypes } = useCargoTypes();
  const { createCargo, updateCargo } = useCargoMutations();
  const [formData, setFormData] = useState<Partial<Cargo>>({
    cargoNumber: '',
    cargoTypeId: '',
    weight: 0,
    remarks: '',
  });

  useEffect(() => {
    if (cargo) {
      setFormData(cargo);
    } else {
      setFormData({
        cargoNumber: '',
        cargoTypeId: '',
        weight: 0,
        remarks: '',
      });
    }
  }, [cargo, open]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (cargo?.id) {
      updateCargo.mutate(
        { id: cargo.id, data: formData },
        { onSuccess: () => { onOpenChange(false); onSuccess?.(); } }
      );
    } else {
      createCargo.mutate(formData, {
        onSuccess: () => { onOpenChange(false); onSuccess?.(); }
      });
    }
  };

  const isLoading = createCargo.isPending || updateCargo.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader><DialogTitle>{cargo ? 'Edit Cargo' : 'Create New Cargo'}</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Cargo Number *</Label>
              <Input value={formData.cargoNumber} onChange={e => setFormData({...formData, cargoNumber: e.target.value})} required />
            </div>
            <div>
              <Label>Cargo Type *</Label>
              <Select 
                value={formData.cargoTypeId || ''} 
                onValueChange={(val) => setFormData({ ...formData, cargoTypeId: val })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select cargo type..." />
                </SelectTrigger>
                <SelectContent>
                  {cargoTypes?.map((type: any) => (
                    <SelectItem key={type.id} value={type.id}>{type.cargo_type_name || type.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div>
            <Label>Weight (kg) *</Label>
            <Input type="number" value={formData.weight} onChange={e => setFormData({...formData, weight: parseFloat(e.target.value)})} required />
          </div>
          <div>
            <Label>Remarks</Label>
            <Textarea value={formData.remarks} onChange={e => setFormData({...formData, remarks: e.target.value})} rows={3} />
          </div>
          <DialogFooter>
            <Button type="submit" disabled={isLoading}>{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}{cargo ? 'Update' : 'Create'}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}