import React, { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, 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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2 } from 'lucide-react';
import { Listing } from '@/hooks/useChannelManager';

interface ListingFormModalProps {
  open: boolean;
  onClose: () => void;
  onCreate: (data: any) => Promise<boolean>;
  onUpdate?: (id: string, data: any) => Promise<boolean>;
  listing?: Listing;
  channels: Array<{ id: string; name: string; }>;
}

const LISTING_TYPES = [
  { value: 'hotel', label: 'Hotel' },
  { value: 'restaurant', label: 'Restaurante' },
  { value: 'vehicle', label: 'Vehículo' },
  { value: 'flight', label: 'Vuelo' },
  { value: 'activity', label: 'Actividad' },
];

export const ListingFormModal: React.FC<ListingFormModalProps> = ({ 
  open, 
  onClose, 
  onCreate, 
  onUpdate, 
  listing,
  channels 
}) => {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: listing?.name || '',
    type: listing?.type || '',
    description: listing?.description || '',
    basePrice: listing?.basePrice || 0,
    address: listing?.location.address || '',
    latitude: listing?.location.coordinates.lat || 0,
    longitude: listing?.location.coordinates.lng || 0,
    selectedChannels: listing?.channels || [],
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    
    const listingData = {
      name: formData.name,
      type: formData.type,
      description: formData.description,
      basePrice: Number(formData.basePrice),
      location: {
        address: formData.address,
        coordinates: {
          lat: Number(formData.latitude),
          lng: Number(formData.longitude),
        },
      },
      channels: formData.selectedChannels,
      status: 'active',
      availability: true,
      images: [],
    };

    const success = listing && onUpdate
      ? await onUpdate(listing.id, listingData)
      : await onCreate(listingData);
    
    if (success) {
      onClose();
    }
    
    setLoading(false);
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{listing ? 'Editar' : 'Nueva'} Propiedad</DialogTitle>
          <DialogDescription>
            {listing ? 'Actualiza la información' : 'Crea una nueva propiedad'} para distribuir en tus canales
          </DialogDescription>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="listing-type">Tipo de Propiedad</Label>
            <Select 
              value={formData.type} 
              onValueChange={(value) => setFormData({ ...formData, type: value })}
            >
              <SelectTrigger id="listing-type">
                <SelectValue placeholder="Selecciona un tipo" />
              </SelectTrigger>
              <SelectContent>
                {LISTING_TYPES.map((type) => (
                  <SelectItem key={type.value} value={type.value}>
                    {type.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="listing-name">Nombre</Label>
            <Input
              id="listing-name"
              placeholder="Ej: Hotel Paradise"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="listing-description">Descripción</Label>
            <Textarea
              id="listing-description"
              placeholder="Describe tu propiedad..."
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={4}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="listing-price">Precio Base</Label>
            <Input
              id="listing-price"
              type="number"
              placeholder="0.00"
              value={formData.basePrice}
              onChange={(e) => setFormData({ ...formData, basePrice: Number(e.target.value) })}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="listing-address">Dirección</Label>
            <Input
              id="listing-address"
              placeholder="Calle, Ciudad, País"
              value={formData.address}
              onChange={(e) => setFormData({ ...formData, address: e.target.value })}
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="listing-lat">Latitud</Label>
              <Input
                id="listing-lat"
                type="number"
                step="any"
                placeholder="0.000000"
                value={formData.latitude}
                onChange={(e) => setFormData({ ...formData, latitude: Number(e.target.value) })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="listing-lng">Longitud</Label>
              <Input
                id="listing-lng"
                type="number"
                step="any"
                placeholder="0.000000"
                value={formData.longitude}
                onChange={(e) => setFormData({ ...formData, longitude: Number(e.target.value) })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
              Cancelar
            </Button>
            <Button type="submit" disabled={loading}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {listing ? 'Actualizar' : 'Crear'} Propiedad
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};
