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

const EstablishmentsList = () => {
  const [establishments, setEstablishments] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const { toast } = useToast();

  const [formData, setFormData] = useState({
    name: '',
    description: '',
    type: 'restaurant',
    address: '',
    phone: '',
    email: '',
    website: '',
    category: '',
    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: '9:00-18:00',
      sunday: 'Closed'
    }
  });

  const loadEstablishments = async () => {
    setLoading(true);
    try {
      const response = await apiClient.get('/commerce/establishments');
      setEstablishments(Array.isArray(response) ? response : (response as any)?.establishments || []);
    } catch (error) {
      console.error('Error loading establishments:', error);
      toast({ title: 'Error', description: 'No se pudieron cargar los establecimientos', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async () => {
    try {
      if (editingId) {
        await apiClient.patch(`/commerce/establishments/${editingId}`, formData);
        toast({ title: 'Éxito', description: 'Establecimiento actualizado correctamente' });
      } else {
        await apiClient.post('/commerce/establishments', formData);
        toast({ title: 'Éxito', description: 'Establecimiento creado correctamente' });
      }
      resetForm();
      loadEstablishments();
    } catch (error: any) {
      toast({ title: 'Error', description: error?.message || 'No se pudo guardar el establecimiento', variant: 'destructive' });
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('¿Estás seguro de eliminar este establecimiento?')) return;
    try {
      await apiClient.delete(`/commerce/establishments/${id}`);
      toast({ title: 'Éxito', description: 'Establecimiento eliminado correctamente' });
      loadEstablishments();
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo eliminar el establecimiento', variant: 'destructive' });
    }
  };

  const handleEdit = (establishment: any) => {
    setEditingId(establishment.id);
    setFormData({
      name: establishment.name || '',
      description: establishment.description || '',
      type: establishment.type || 'restaurant',
      address: establishment.address || '',
      phone: establishment.phone || '',
      email: establishment.email || '',
      website: establishment.website || '',
      category: establishment.category || '',
      coordinates: establishment.coordinates || { x: 0, y: 0 },
      openingHours: establishment.openingHours || formData.openingHours
    });
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData({
      name: '',
      description: '',
      type: 'restaurant',
      address: '',
      phone: '',
      email: '',
      website: '',
      category: '',
      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: '9:00-18:00',
        sunday: 'Closed'
      }
    });
  };

  const filteredEstablishments = establishments.filter(est =>
    est.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    est.category?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <div className="flex-1 max-w-sm">
          <Input
            placeholder="Buscar establecimientos..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button onClick={resetForm}>
              <Plus className="w-4 h-4 mr-2" />
              Nuevo Establecimiento
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editingId ? 'Editar' : 'Crear'} Establecimiento</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Nombre</Label>
                  <Input
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="Nombre del establecimiento"
                  />
                </div>
                <div>
                  <Label>Tipo</Label>
                  <Select value={formData.type} onValueChange={(value) => setFormData({ ...formData, type: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="restaurant">Restaurante</SelectItem>
                      <SelectItem value="hotel">Hotel</SelectItem>
                      <SelectItem value="bar">Bar</SelectItem>
                      <SelectItem value="cafe">Café</SelectItem>
                      <SelectItem value="store">Tienda</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div>
                <Label>Descripción</Label>
                <Textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="Describe el establecimiento..."
                  rows={3}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Categoría</Label>
                  <Input
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    placeholder="Ej: Comida rápida"
                  />
                </div>
                <div>
                  <Label>Teléfono</Label>
                  <Input
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    placeholder="+1 809 123 4567"
                  />
                </div>
              </div>
              <div>
                <Label>Dirección</Label>
                <Input
                  value={formData.address}
                  onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  placeholder="Dirección completa"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Email</Label>
                  <Input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    placeholder="contacto@establecimiento.com"
                  />
                </div>
                <div>
                  <Label>Sitio Web</Label>
                  <Input
                    value={formData.website}
                    onChange={(e) => setFormData({ ...formData, website: e.target.value })}
                    placeholder="https://..."
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Button onClick={handleSubmit} className="flex-1">
                  {editingId ? 'Actualizar' : 'Crear'} Establecimiento
                </Button>
                {editingId && (
                  <Button variant="outline" onClick={resetForm}>
                    Cancelar
                  </Button>
                )}
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {loading ? (
        <div className="text-center py-8">Cargando establecimientos...</div>
      ) : (
        <div className="grid gap-4">
          {filteredEstablishments.map((establishment) => (
            <Card key={establishment.id} className="hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <div className="flex items-center space-x-4">
                  <div className="w-16 h-16 rounded-lg bg-primary/10 flex items-center justify-center">
                    <Store className="w-8 h-8 text-primary" />
                  </div>
                  <div>
                    <CardTitle className="text-lg">{establishment.name}</CardTitle>
                    <p className="text-sm text-muted-foreground">{establishment.category}</p>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <Badge variant={establishment.isActive ? "default" : "secondary"}>
                    {establishment.isActive ? 'Activo' : 'Inactivo'}
                  </Badge>
                  <Badge variant="outline">{establishment.type}</Badge>
                  <Button variant="outline" size="sm" onClick={() => handleEdit(establishment)}>
                    <Edit className="w-4 h-4" />
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => handleDelete(establishment.id)}>
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground mb-3">{establishment.description}</p>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  {establishment.address && (
                    <div className="flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-muted-foreground" />
                      <span className="truncate">{establishment.address}</span>
                    </div>
                  )}
                  {establishment.phone && (
                    <div className="flex items-center gap-2">
                      <Phone className="w-4 h-4 text-muted-foreground" />
                      <span>{establishment.phone}</span>
                    </div>
                  )}
                  {establishment.website && (
                    <div className="flex items-center gap-2">
                      <Globe className="w-4 h-4 text-muted-foreground" />
                      <a href={establishment.website} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
                        Sitio web
                      </a>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default EstablishmentsList;
