import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Store, Plus, Edit, Trash2, MapPin, Phone, Globe, Clock, Star, Search } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';

const BusinessList = () => {
  const [businesses, setBusinesses] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const { toast } = useToast();

  const [newBusiness, setNewBusiness] = useState({
    name: '',
    description: '',
    category: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    coordinates: { x: 0, y: 0 },
    openingHours: {
      monday: '9:00-18:00',
      tuesday: '9:00-18:00',
      wednesday: '9:00-18:00',
      thursday: '9:00-18:00',
      friday: '9:00-18:00',
      saturday: '10:00-14:00',
      sunday: 'Cerrado'
    },
    images: ['']
  });

  const loadBusinesses = async () => {
    setLoading(true);
    try {
      const data = await apiClient.get('/establishments?page=1&limit=50');
      setBusinesses(Array.isArray(data) ? data : (data as any)?.establishments || []);
    } catch (error) {
      console.error('Error loading businesses:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadBusinesses();
  }, []);

  const handleCreate = async () => {
    try {
      await apiClient.post('/establishments', {
        ...newBusiness,
        coordinates: `(${newBusiness.coordinates.x},${newBusiness.coordinates.y})`,
        images: newBusiness.images.filter(img => img.trim() !== '')
      });
      setNewBusiness({
        name: '', description: '', category: '', address: '', phone: '', email: '', website: '',
        coordinates: { x: 0, y: 0 }, images: [''],
        openingHours: {
          monday: '9:00-18:00', tuesday: '9:00-18:00', wednesday: '9:00-18:00',
          thursday: '9:00-18:00', friday: '9:00-18:00', saturday: '10:00-14:00', sunday: 'Cerrado'
        }
      });
      loadBusinesses();
      toast({ title: 'Comercio creado', description: 'El establecimiento se creó correctamente.' });
    } catch (error: any) {
      toast({ title: 'Error', description: error?.message || 'No se pudo crear el comercio.' });
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await apiClient.delete(`/establishments/${id}`);
      loadBusinesses();
      toast({ title: 'Comercio eliminado', description: 'Se eliminó correctamente.' });
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo eliminar el comercio.' });
    }
  };

  const filteredBusinesses = businesses.filter(b =>
    b.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    b.category?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
          <Input
            placeholder="Buscar comercios..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Nuevo Comercio
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Registrar Nuevo Comercio</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Nombre del Comercio</Label>
                  <Input
                    value={newBusiness.name}
                    onChange={(e) => setNewBusiness({ ...newBusiness, name: e.target.value })}
                    placeholder="Restaurante El Caribe"
                  />
                </div>
                <div>
                  <Label>Categoría</Label>
                  <Select value={newBusiness.category} onValueChange={(v) => setNewBusiness({ ...newBusiness, category: v })}>
                    <SelectTrigger>
                      <SelectValue placeholder="Selecciona categoría" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="restaurant">Restaurante</SelectItem>
                      <SelectItem value="hotel">Hotel</SelectItem>
                      <SelectItem value="store">Tienda</SelectItem>
                      <SelectItem value="entertainment">Entretenimiento</SelectItem>
                      <SelectItem value="services">Servicios</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              
              <div>
                <Label>Descripción</Label>
                <Textarea
                  value={newBusiness.description}
                  onChange={(e) => setNewBusiness({ ...newBusiness, description: e.target.value })}
                  placeholder="Describe el comercio..."
                  rows={3}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Dirección</Label>
                  <Input
                    value={newBusiness.address}
                    onChange={(e) => setNewBusiness({ ...newBusiness, address: e.target.value })}
                    placeholder="Calle Principal #123"
                  />
                </div>
                <div>
                  <Label>Teléfono</Label>
                  <Input
                    value={newBusiness.phone}
                    onChange={(e) => setNewBusiness({ ...newBusiness, phone: e.target.value })}
                    placeholder="+1 809-555-0123"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Email</Label>
                  <Input
                    type="email"
                    value={newBusiness.email}
                    onChange={(e) => setNewBusiness({ ...newBusiness, email: e.target.value })}
                    placeholder="contacto@negocio.com"
                  />
                </div>
                <div>
                  <Label>Sitio Web</Label>
                  <Input
                    value={newBusiness.website}
                    onChange={(e) => setNewBusiness({ ...newBusiness, website: e.target.value })}
                    placeholder="https://www.negocio.com"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Latitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={newBusiness.coordinates.y}
                    onChange={(e) => setNewBusiness({ 
                      ...newBusiness, 
                      coordinates: { ...newBusiness.coordinates, y: parseFloat(e.target.value) || 0 }
                    })}
                  />
                </div>
                <div>
                  <Label>Longitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={newBusiness.coordinates.x}
                    onChange={(e) => setNewBusiness({ 
                      ...newBusiness, 
                      coordinates: { ...newBusiness.coordinates, x: parseFloat(e.target.value) || 0 }
                    })}
                  />
                </div>
              </div>

              <div>
                <Label>URLs de Imágenes (separadas por coma)</Label>
                <Textarea
                  value={newBusiness.images.join(', ')}
                  onChange={(e) => setNewBusiness({ 
                    ...newBusiness, 
                    images: e.target.value.split(',').map(url => url.trim())
                  })}
                  placeholder="https://ejemplo.com/imagen1.jpg, https://ejemplo.com/imagen2.jpg"
                  rows={2}
                />
              </div>

              <Button onClick={handleCreate} className="w-full">
                Crear Comercio
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-4">
        {filteredBusinesses.map((business) => (
          <Card key={business.id} className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 rounded-lg bg-orange-100 flex items-center justify-center">
                    <Store className="h-8 w-8 text-orange-600" />
                  </div>
                  <div>
                    <CardTitle>{business.name}</CardTitle>
                    <CardDescription className="flex items-center gap-2 mt-1">
                      <Badge variant="outline">{business.category}</Badge>
                      {business.isVerified && (
                        <Badge className="bg-green-100 text-green-800">Verificado</Badge>
                      )}
                    </CardDescription>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="flex items-center gap-1">
                    <Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
                    {business.rating || '4.5'}
                  </Badge>
                  <Button variant="outline" size="sm" onClick={() => console.log('Edit:', business.id)}>
                    <Edit className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => handleDelete(business.id)}>
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-gray-600 mb-4">{business.description}</p>
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div className="flex items-center gap-2 text-gray-600">
                  <MapPin className="h-4 w-4" />
                  {business.address || 'Sin dirección'}
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <Phone className="h-4 w-4" />
                  {business.phone || 'Sin teléfono'}
                </div>
                {business.website && (
                  <div className="flex items-center gap-2 text-gray-600">
                    <Globe className="h-4 w-4" />
                    <a href={business.website} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                      Sitio web
                    </a>
                  </div>
                )}
                <div className="flex items-center gap-2 text-gray-600">
                  <Clock className="h-4 w-4" />
                  {business.isOpen ? 'Abierto' : 'Cerrado'}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default BusinessList;
