import { useState, useEffect } from 'react';
import { toast } from 'sonner';
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 { useContainerTypes } from './use-container-types';
import { useContainerMutations } from './use-containers';
import { Loader2 } from 'lucide-react';

interface Container {
  id: string;
  containerNumber: string;
  containerTypeId: string;
  wagonId?: string;
  status: 'AVAILABLE' | 'IN_USE' | 'MAINTENANCE' | 'RETIRED';
  capacity: number;
  weight: number;
  remarks?: string;
}

interface Wagon {
  id: string;
  wagonNumber: string;
}

interface ContainerFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  container?: Container | null;
  wagons: Wagon[];
  onSuccess?: () => void;
}

export default function ContainerFormDialog({
  open,
  onOpenChange,
  container,
  wagons = [],
  onSuccess,
}: ContainerFormDialogProps) {
  const { data: containerTypes } = useContainerTypes();
  const { createContainer, updateContainer } = useContainerMutations();
  const [formData, setFormData] = useState<Partial<Container>>({
    containerNumber: '',
    containerTypeId: '',
    status: 'AVAILABLE',
    capacity: 0,
    weight: 0,
    remarks: '',
  });

  useEffect(() => {
    if (container) {
      setFormData(container);
    } else {
      setFormData({
        containerNumber: '',
        containerTypeId: '',
        status: 'AVAILABLE',
        capacity: 0,
        weight: 0,
        remarks: '',
      });
    }
  }, [container, open]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.containerNumber || !formData.containerTypeId) {
      toast.error('Please fill in all required fields');
      return;
    }
    if (container?.id) {
      updateContainer.mutate(
        { id: container.id, data: formData },
        { onSuccess: () => { onOpenChange(false); onSuccess?.(); } }
      );
    } else {
      createContainer.mutate(formData, {
        onSuccess: () => { onOpenChange(false); onSuccess?.(); }
      });
    }
  };

  const isLoading = createContainer.isPending || updateContainer.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>
            {container ? 'Edit Container' : 'Create New Container'}
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="containerNumber">Container Number *</Label>
              <Input
                id="containerNumber"
                value={formData.containerNumber || ''}
                onChange={(e) =>
                  setFormData({ ...formData, containerNumber: e.target.value })
                }
                placeholder="e.g., CNT001"
                required
              />
            </div>
            <div>
              <Label htmlFor="containerTypeId">Container Type *</Label>
              <Select 
                value={formData.containerTypeId || ''} 
                onValueChange={(val:any) => setFormData({ ...formData, containerTypeId: val })}
              >
                <SelectTrigger id="containerTypeId">
                  <SelectValue placeholder="Select container type..." />
                </SelectTrigger>
                <SelectContent>
                  {containerTypes?.map((type: any) => (
                    <SelectItem key={type.id} value={type.id}>{type.name || type.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="wagonId">Wagon (Optional)</Label>
              <Select
                value={formData.wagonId || 'none'}
                onValueChange={(val:any) => setFormData({ ...formData, wagonId: val === 'none' ? undefined : val })}
              >
                <SelectTrigger id="wagonId">
                  <SelectValue placeholder="Select a wagon..." />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">None</SelectItem>
                  {wagons.map((wagon) => (
                    <SelectItem key={wagon.id} value={wagon.id}>
                      {wagon.wagonNumber}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="status">Status</Label>
              <Select
                value={formData.status || 'AVAILABLE'}
                onValueChange={(val:any) => setFormData({ ...formData, status: val })}
              >
                <SelectTrigger id="status">
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="AVAILABLE">Available</SelectItem>
                  <SelectItem value="IN_USE">In Use</SelectItem>
                  <SelectItem value="MAINTENANCE">Maintenance</SelectItem>
                  <SelectItem value="RETIRED">Retired</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="capacity">Capacity *</Label>
              <Input
                id="capacity"
                type="number"
                value={formData.capacity || ''}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    capacity: parseFloat(e.target.value) || 0,
                  })
                }
                placeholder="0"
                required
              />
            </div>
            <div>
              <Label htmlFor="weight">Weight (kg)</Label>
              <Input
                id="weight"
                type="number"
                value={formData.weight || ''}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    weight: parseFloat(e.target.value) || 0,
                  })
                }
                placeholder="0"
              />
            </div>
          </div>

          <div>
            <Label htmlFor="remarks">Remarks</Label>
            <Textarea
              id="remarks"
              value={formData.remarks || ''}
              onChange={(e) =>
                setFormData({ ...formData, remarks: e.target.value })
              }
              placeholder="Add any additional notes..."
              rows={3}
            />
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isLoading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {container ? 'Update' : 'Create'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
