import { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import axios from 'axios';
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 { Loader2 } from 'lucide-react';
import { useWagonTypes } from '@/hooks/use-wagon-types';

interface Wagon {
  id: string;
  wagonNumber: string;
  wagonTypeId: string;
  trainId?: string;
  status: 'AVAILABLE' | 'IN_USE' | 'MAINTENANCE' | 'RETIRED';
  capacity: number;
  emptyWeight: number;
  remarks?: string;
}

interface Train {
  id: string;
  trainNumber: string;
}

interface WagonFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  wagon?: Wagon | null;
  trains: Train[];
  onSuccess?: () => void;
}

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';

export default function WagonFormDialog({
  open,
  onOpenChange,
  wagon,
  trains = [],
  onSuccess,
}: WagonFormDialogProps) {
  const queryClient = useQueryClient();
  const { data: wagonTypes = [], isLoading: wagonTypesLoading } = useWagonTypes();
  const [formData, setFormData] = useState<Partial<Wagon>>({
    wagonNumber: '',
    wagonTypeId: '',
    status: 'AVAILABLE',
    capacity: 0,
    emptyWeight: 0,
    remarks: '',
  });

  useEffect(() => {
    if (wagon) {
      setFormData(wagon);
    } else {
      setFormData({
        wagonNumber: '',
        wagonTypeId: '',
        status: 'AVAILABLE',
        capacity: 0,
        emptyWeight: 0,
        remarks: '',
      });
    }
  }, [wagon, open]);

  const createMutation = useMutation({
    mutationFn: (data: Partial<Wagon>) =>
      axios.post(`${API_BASE_URL}/api/wagons`, data),
    onSuccess: () => {
      toast.success('Wagon created successfully');
      onOpenChange(false);
      queryClient.invalidateQueries({ queryKey: ['wagons'] });
      onSuccess?.();
    },
    onError: (error) => {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message || 'Failed to create wagon'
        : 'Failed to create wagon';
      toast.error(message);
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: Partial<Wagon>) =>
      axios.patch(`${API_BASE_URL}/api/wagons/${wagon?.id}`, data),
    onSuccess: () => {
      toast.success('Wagon updated successfully');
      onOpenChange(false);
      queryClient.invalidateQueries({ queryKey: ['wagons'] });
      onSuccess?.();
    },
    onError: (error) => {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message || 'Failed to update wagon'
        : 'Failed to update wagon';
      toast.error(message);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.wagonNumber || !formData.wagonTypeId) {
      toast.error('Please fill in all required fields');
      return;
    }
    if (wagon?.id) {
      updateMutation.mutate(formData);
    } else {
      createMutation.mutate(formData);
    }
  };

  const isLoading = createMutation.isPending || updateMutation.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>
            {wagon ? 'Edit Wagon' : 'Create New Wagon'}
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="wagonNumber">Wagon Number *</Label>
              <Input
                id="wagonNumber"
                value={formData.wagonNumber || ''}
                onChange={(e) =>
                  setFormData({ ...formData, wagonNumber: e.target.value })
                }
                placeholder="e.g., W001"
                required
              />
            </div>
            <div>
              <Label htmlFor="wagonTypeId">Type *</Label>
              <Select
                value={formData.wagonTypeId || ''}
                disabled={wagonTypesLoading}
                onValueChange={(value) => {
                  const selectedType = wagonTypes.find((type: any) => type.id === value);
                  setFormData({
                    ...formData,
                    wagonTypeId: value,
                    capacity: formData.capacity && formData.capacity > 0
                      ? formData.capacity
                      : Number(selectedType?.capacityTons ?? 0),
                  });
                }}
              >
                <SelectTrigger id="wagonTypeId">
                  <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>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="trainId">Train (Optional)</Label>
              <select
                id="trainId"
                value={formData.trainId || ''}
                onChange={(e) =>
                  setFormData({ ...formData, trainId: e.target.value || undefined })
                }
                className="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Select a train...</option>
                {trains.map(train => (
                  <option key={train.id} value={train.id}>
                    {train.trainNumber}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <Label htmlFor="status">Status</Label>
              <select
                id="status"
                value={formData.status || 'AVAILABLE'}
                onChange={(e) =>
                  setFormData({ ...formData, status: e.target.value as any })
                }
                className="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="AVAILABLE">Available</option>
                <option value="IN_USE">In Use</option>
                <option value="MAINTENANCE">Maintenance</option>
                <option value="RETIRED">Retired</option>
              </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="emptyWeight">Empty Weight (kg)</Label>
              <Input
                id="emptyWeight"
                type="number"
                value={formData.emptyWeight || ''}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    emptyWeight: 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" />}
              {wagon ? 'Update' : 'Create'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
