import React, { useState } from 'react';
import { 
  FileText, 
  Globe, 
  Edit, 
  Plus, 
  MapPin, 
  Camera, 
  Bot, 
  Eye, 
  Trash2, 
  Star,
  Users,
  Calendar,
  DollarSign,
  Image,
  Settings,
  Car,
  Clock
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';
import GeolocationTab from './GeolocationTab';

interface ContentTabProps {
  isSuperAdmin: boolean;
  activeSubTab?: string;
}

const ContentTab: React.FC<ContentTabProps> = ({ isSuperAdmin, activeSubTab = 'destinations' }) => {
  const [activeTab, setActiveTab] = useState(activeSubTab || 'destinations');
  
  React.useEffect(() => {
    setActiveTab(activeSubTab || 'destinations');
  }, [activeSubTab]);
  const [destinations, setDestinations] = useState<any[]>([]);
  const [places, setPlaces] = useState<any[]>([]);
  const [guides, setGuides] = useState<any[]>([]);
  const [taxis, setTaxis] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  
  const [newDestination, setNewDestination] = useState({
    name: '',
    description: '',
    category: '',
    countryId: 1,
    coordinates: { x: 0, y: 0 },
    images: ['']
  });
  
  const [newPlace, setNewPlace] = useState({
    name: '',
    description: '',
    destinationId: '',
    category: '',
    address: '',
    phone: '',
    website: '',
    coordinates: { x: 0, y: 0 },
    entranceFee: 0,
    openingHours: {
      monday: '9:00-17:00',
      tuesday: '9:00-17:00',
      wednesday: '9:00-17:00',
      thursday: '9:00-17:00',
      friday: '9:00-17:00',
      saturday: '9:00-17:00',
      sunday: '9:00-17:00'
    },
    historicalInfo: '',
    images: ['']
  });

  const [newGuide, setNewGuide] = useState({
    licenseNumber: '',
    specialties: [''],
    languages: [''],
    hourlyRate: 0,
    dailyRate: 0,
    bio: '',
    certifications: {}
  });

  const [newTaxi, setNewTaxi] = useState({
    licenseNumber: '',
    vehiclePlate: '',
    vehicleModel: '',
    vehicleYear: new Date().getFullYear(),
    vehicleColor: '',
    vehicleCapacity: 4
  });

  // Promocional & IA forms
  const [newCampaign, setNewCampaign] = useState({
    title: '',
    message: '',
    segment: 'all'
  });
  const [aiGuideConfig, setAiGuideConfig] = useState({
    name: '',
    language: 'es',
    personality: ''
  });

  // Load initial data
  const loadData = async () => {
    setLoading(true);
    try {
      const [destData, placesData, guidesData, taxisData] = await Promise.all([
        apiClient.get('/tourism/destinations?page=1&limit=50'),
        apiClient.get('/tourism/places?page=1&limit=50'),
        apiClient.get('/tourism/guides?page=1&limit=50'),
        apiClient.get('/tourism/taxis/available')
      ]);

      setDestinations((destData as any)?.destinations || (Array.isArray(destData) ? (destData as any) : []) );
      setPlaces((placesData as any)?.places || (Array.isArray(placesData) ? (placesData as any) : []) );
      setGuides((guidesData as any)?.guides || (Array.isArray(guidesData) ? (guidesData as any) : []) );
      const taxisArr = Array.isArray(taxisData) ? taxisData : (taxisData as any)?.taxis || (taxisData as any)?.drivers || (taxisData as any)?.data || [];
      setTaxis(taxisArr as any[]);
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };
  React.useEffect(() => {
    loadData();
  }, []);

  const { toast } = useToast();

  const handleCreateDestination = async () => {
    try {
      await apiClient.post('/tourism/destinations', {
        name: newDestination.name,
        description: newDestination.description,
        category: newDestination.category,
        countryId: newDestination.countryId,
        coordinates: `(${newDestination.coordinates.x},${newDestination.coordinates.y})`,
        images: newDestination.images.filter(img => img.trim() !== '')
      });
      setNewDestination({ name: '', description: '', category: '', countryId: 1, coordinates: { x: 0, y: 0 }, images: [''] });
      loadData();
      toast({ title: 'Destino creado', description: 'El destino se creó correctamente.' });
    } catch (error: any) {
      console.error('Error creating destination:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo crear el destino.' });
    }
  };

  const handleCreatePlace = async () => {
    try {
      await apiClient.post('/tourism/places', {
        name: newPlace.name,
        description: newPlace.description,
        destinationId: parseInt(newPlace.destinationId),
        category: newPlace.category,
        address: newPlace.address,
        phone: newPlace.phone,
        website: newPlace.website,
        coordinates: `(${newPlace.coordinates.x},${newPlace.coordinates.y})`,
        entranceFee: newPlace.entranceFee,
        openingHours: newPlace.openingHours,
        historicalInfo: newPlace.historicalInfo,
        images: newPlace.images.filter(img => img.trim() !== '')
      });
      setNewPlace({
        name: '', description: '', destinationId: '', category: '', address: '', phone: '', website: '',
        coordinates: { x: 0, y: 0 }, entranceFee: 0, historicalInfo: '', images: [''],
        openingHours: {
          monday: '9:00-17:00', tuesday: '9:00-17:00', wednesday: '9:00-17:00', thursday: '9:00-17:00',
          friday: '9:00-17:00', saturday: '9:00-17:00', sunday: '9:00-17:00'
        }
      });
      loadData();
      toast({ title: 'Lugar creado', description: 'El lugar se creó correctamente.' });
    } catch (error: any) {
      console.error('Error creating place:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo crear el lugar.' });
    }
  };

  const handleDeleteDestination = async (id: string) => {
    try {
      await apiClient.delete(`/tourism/destinations/${id}`);
    } catch (error: any) {
      console.error('Error deleting destination:', error);
      // Algunos endpoints devuelven 204 sin cuerpo
    }
    await loadData();
    toast({ title: 'Destino eliminado', description: 'Se eliminó correctamente.' });
  };

  const handleDeletePlace = async (id: string) => {
    try {
      await apiClient.delete(`/tourism/places/${id}`);
    } catch (error: any) {
      console.error('Error deleting place:', error);
      // Algunos endpoints devuelven 204 sin cuerpo
    }
    await loadData();
    toast({ title: 'Lugar eliminado', description: 'Se eliminó correctamente.' });
  };

  const handleCreateCampaign = async () => {
    try {
      await apiClient.post('/notifications', {
        title: newCampaign.title,
        message: newCampaign.message,
        segment: newCampaign.segment || 'all',
        type: 'promotion'
      });
      toast({ title: 'Campaña creada', description: 'La campaña promocional fue creada.' });
      setNewCampaign({ title: '', message: '', segment: 'all' });
    } catch (error: any) {
      console.error('Error creating campaign:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo crear la campaña.' });
    }
  };

  const handleSetupAIGuide = async () => {
    try {
      await apiClient.post('/ai-generator/generate', {
        template: 'virtual-guide',
        inputs: {
          name: aiGuideConfig.name,
          language: aiGuideConfig.language,
          personality: aiGuideConfig.personality
        }
      });
      toast({ title: 'Guía IA creada', description: 'La guía virtual fue configurada.' });
      setAiGuideConfig({ name: '', language: 'es', personality: '' });
    } catch (error: any) {
      console.error('Error setting up AI guide:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo configurar la guía IA.' });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold text-gray-900">Gestión de Contenido Turístico</h2>
        <div className="flex gap-2">
          <Badge variant="secondary" className="text-sm">
            {destinations.length} Destinos
          </Badge>
          <Badge variant="secondary" className="text-sm">
            {places.length} Lugares
          </Badge>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">

        <TabsContent value="destinations" className="space-y-4">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">Gestión de Destinos Turísticos</h3>
            {isSuperAdmin && (
              <Dialog>
                <DialogTrigger asChild>
                  <Button className="flex items-center gap-2">
                    <Plus className="w-4 h-4" />
                    Nuevo Destino
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-2xl">
                  <DialogHeader>
                    <DialogTitle>Crear Nuevo Destino</DialogTitle>
                  </DialogHeader>
                  <div className="grid gap-4">
                    <div>
                      <Label htmlFor="dest-name">Nombre del Destino</Label>
                      <Input
                        id="dest-name"
                        value={newDestination.name}
                        onChange={(e) => setNewDestination({ ...newDestination, name: e.target.value })}
                        placeholder="Ej: Punta Cana"
                      />
                    </div>
                    <div>
                      <Label htmlFor="dest-category">Categoría</Label>
                      <Select value={newDestination.category} onValueChange={(value) => setNewDestination({ ...newDestination, category: value })}>
                        <SelectTrigger>
                          <SelectValue placeholder="Selecciona una categoría" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="beach">Playa</SelectItem>
                          <SelectItem value="cultural">Cultural</SelectItem>
                          <SelectItem value="nature">Naturaleza</SelectItem>
                          <SelectItem value="luxury">Lujo</SelectItem>
                          <SelectItem value="adventure">Aventura</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label htmlFor="dest-description">Descripción</Label>
                      <Textarea
                        id="dest-description"
                        value={newDestination.description}
                        onChange={(e) => setNewDestination({ ...newDestination, description: e.target.value })}
                        placeholder="Describe el destino turístico..."
                        rows={3}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="dest-lat">Latitud</Label>
                        <Input
                          id="dest-lat"
                          type="number"
                          step="any"
                          value={newDestination.coordinates.y}
                          onChange={(e) => setNewDestination({ 
                            ...newDestination, 
                            coordinates: { ...newDestination.coordinates, y: parseFloat(e.target.value) || 0 }
                          })}
                          placeholder="18.4861"
                        />
                      </div>
                      <div>
                        <Label htmlFor="dest-lng">Longitud</Label>
                        <Input
                          id="dest-lng"
                          type="number"
                          step="any"
                          value={newDestination.coordinates.x}
                          onChange={(e) => setNewDestination({ 
                            ...newDestination, 
                            coordinates: { ...newDestination.coordinates, x: parseFloat(e.target.value) || 0 }
                          })}
                          placeholder="-69.9312"
                        />
                      </div>
                    </div>
                    <div>
                      <Label htmlFor="dest-image">URLs de Imágenes (separadas por coma)</Label>
                      <Textarea
                        id="dest-image"
                        value={newDestination.images.join(', ')}
                        onChange={(e) => setNewDestination({ 
                          ...newDestination, 
                          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={handleCreateDestination} className="w-full">
                      Crear Destino
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
            )}
          </div>
          
          <div className="grid gap-4">
            {destinations.map((destination) => (
              <Card key={destination.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">
                    <img 
                      src={destination.images?.[0] || '/placeholder.svg'} 
                      alt={destination.name}
                      className="w-16 h-16 rounded-lg object-cover"
                    />
                    <div>
                      <CardTitle className="text-lg">{destination.name}</CardTitle>
                      <p className="text-sm text-muted-foreground">{destination.category}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="flex items-center gap-1">
                      <Star className="w-3 h-3" />
                      {destination.rating || 4.5}
                    </Badge>
                    {isSuperAdmin && (
                      <div className="flex gap-1">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => console.log('Edit destination:', destination.id)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => handleDeleteDestination(destination.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600 mb-3">{destination.description}</p>
                  <div className="flex flex-wrap gap-2">
                    <Badge variant="secondary" className="text-xs">
                      {destination.active ? 'Activo' : 'Inactivo'}
                    </Badge>
                    {destination.country_id && (
                      <Badge variant="outline" className="text-xs">
                        País ID: {destination.country_id}
                      </Badge>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="places" className="space-y-4">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">Gestión de Lugares de Interés</h3>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2">
                  <Plus className="w-4 h-4" />
                  Nuevo Lugar
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Crear Nuevo Lugar</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label htmlFor="place-name">Nombre del Lugar</Label>
                    <Input
                      id="place-name"
                      value={newPlace.name}
                      onChange={(e) => setNewPlace({ ...newPlace, name: e.target.value })}
                      placeholder="Ej: Hoyo Azul"
                    />
                  </div>
                  <div>
                    <Label htmlFor="place-destination">Destino</Label>
                    <Select value={newPlace.destinationId} onValueChange={(value) => setNewPlace({ ...newPlace, destinationId: value })}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona un destino" />
                      </SelectTrigger>
                      <SelectContent>
                        {destinations.map((dest) => (
                          <SelectItem key={dest.id} value={dest.id.toString()}>
                            {dest.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="place-category">Categoría</Label>
                    <Select value={newPlace.category} onValueChange={(value) => setNewPlace({ ...newPlace, category: value })}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona una categoría" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="attraction">Atracción</SelectItem>
                        <SelectItem value="restaurant">Restaurante</SelectItem>
                        <SelectItem value="hotel">Hotel</SelectItem>
                        <SelectItem value="beach">Playa</SelectItem>
                        <SelectItem value="adventure">Aventura</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Button onClick={handleCreatePlace} className="w-full">
                    Crear Lugar
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>

          <div className="grid gap-4">
            {places.map((place) => (
              <Card key={place.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">
                    <img 
                      src={place.images?.[0] || '/placeholder.svg'} 
                      alt={place.name}
                      className="w-16 h-16 rounded-lg object-cover"
                    />
                    <div>
                      <CardTitle className="text-lg">{place.name}</CardTitle>
                      <p className="text-sm text-muted-foreground">{place.category}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="flex items-center gap-1">
                      <Star className="w-3 h-3" />
                      {place.rating || 4.5}
                    </Badge>
                    <div className="flex gap-1">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => console.log('Edit place:', place.id)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => handleDeletePlace(place.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600">{place.description}</p>
                  <p className="text-xs text-gray-500 mt-2">{place.address}</p>
                  {place.phone && (
                    <p className="text-xs text-gray-500 mt-1">📞 {place.phone}</p>
                  )}
                  {place.website && (
                    <p className="text-xs text-gray-500 mt-1">🌐 {place.website}</p>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>
        <TabsContent value="guides" className="space-y-4">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">Gestión de Guías Turísticos</h3>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2">
                  <Plus className="w-4 h-4" />
                  Nuevo Guía
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Crear Nuevo Guía</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label>Número de Licencia</Label>
                    <Input
                      value={newGuide.licenseNumber}
                      onChange={(e) => setNewGuide({ ...newGuide, licenseNumber: e.target.value })}
                      placeholder="Ej: GUIDE-2024-001"
                    />
                  </div>
                  <div>
                    <Label>Especialidades (separadas por coma)</Label>
                    <Input
                      value={newGuide.specialties.join(', ')}
                      onChange={(e) => setNewGuide({ 
                        ...newGuide, 
                        specialties: e.target.value.split(',').map(s => s.trim())
                      })}
                      placeholder="Historia, Naturaleza, Aventura"
                    />
                  </div>
                  <div>
                    <Label>Idiomas (separados por coma)</Label>
                    <Input
                      value={newGuide.languages.join(', ')}
                      onChange={(e) => setNewGuide({ 
                        ...newGuide, 
                        languages: e.target.value.split(',').map(l => l.trim())
                      })}
                      placeholder="Español, Inglés, Francés"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>Tarifa por Hora ($)</Label>
                      <Input
                        type="number"
                        value={newGuide.hourlyRate}
                        onChange={(e) => setNewGuide({ ...newGuide, hourlyRate: parseFloat(e.target.value) || 0 })}
                      />
                    </div>
                    <div>
                      <Label>Tarifa Diaria ($)</Label>
                      <Input
                        type="number"
                        value={newGuide.dailyRate}
                        onChange={(e) => setNewGuide({ ...newGuide, dailyRate: parseFloat(e.target.value) || 0 })}
                      />
                    </div>
                  </div>
                  <div>
                    <Label>Biografía</Label>
                    <Textarea
                      value={newGuide.bio}
                      onChange={(e) => setNewGuide({ ...newGuide, bio: e.target.value })}
                      placeholder="Experiencia y descripción del guía..."
                      rows={3}
                    />
                  </div>
                  <Button onClick={async () => {
                    try {
                      await apiClient.post('/tourism/guides', {
                        ...newGuide,
                        userId: 1
                      });
                      setNewGuide({ licenseNumber: '', specialties: [''], languages: [''], hourlyRate: 0, dailyRate: 0, bio: '', certifications: {} });
                      loadData();
                      toast({ title: 'Guía creado', description: 'El guía se creó correctamente.' });
                    } catch (error: any) {
                      toast({ title: 'Error', description: error?.message || 'No se pudo crear el guía.' });
                    }
                  }}>
                    Crear Guía
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
          
          <div className="grid gap-4">
            {(Array.isArray(guides) ? guides : []).map((guide) => (
              <Card key={guide.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">
                      <Users className="w-8 h-8 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-lg">{guide.user?.firstName} {guide.user?.lastName}</CardTitle>
                      <p className="text-sm text-muted-foreground">Licencia: {guide.licenseNumber}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="flex items-center gap-1">
                      <Star className="w-3 h-3" />
                      {guide.rating}
                    </Badge>
                    <Badge variant={guide.isVerified ? "default" : "secondary"}>
                      {guide.isVerified ? 'Verificado' : 'Pendiente'}
                    </Badge>
                    {isSuperAdmin && (
                      <div className="flex gap-1">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => console.log('Edit guide:', guide.id)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={async () => {
                            try {
                              await apiClient.delete(`/tourism/guides/${guide.id}`);
                              loadData();
                              toast({ title: 'Guía eliminado', description: 'Se eliminó correctamente.' });
                            } catch (error) {
                              toast({ title: 'Error', description: 'No se pudo eliminar el guía.' });
                            }
                          }}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600 mb-2">{guide.bio}</p>
                  <div className="flex flex-wrap gap-2 mb-2">
                    {guide.specialties?.map((specialty: string, idx: number) => (
                      <Badge key={idx} variant="outline" className="text-xs">
                        {specialty}
                      </Badge>
                    ))}
                  </div>
                  <div className="flex justify-between text-sm text-gray-500">
                    <span>Tarifa por hora: ${guide.hourlyRate}</span>
                    <span>Tours realizados: {guide.totalTours}</span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="taxis" className="space-y-4">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">Gestión de Taxis</h3>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2">
                  <Plus className="w-4 h-4" />
                  Nuevo Taxi
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Registrar Nuevo Taxi</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label>Número de Licencia</Label>
                    <Input
                      value={newTaxi.licenseNumber}
                      onChange={(e) => setNewTaxi({ ...newTaxi, licenseNumber: e.target.value })}
                      placeholder="Ej: TAXI-2024-001"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>Placa del Vehículo</Label>
                      <Input
                        value={newTaxi.vehiclePlate}
                        onChange={(e) => setNewTaxi({ ...newTaxi, vehiclePlate: e.target.value })}
                        placeholder="ABC-123"
                      />
                    </div>
                    <div>
                      <Label>Modelo</Label>
                      <Input
                        value={newTaxi.vehicleModel}
                        onChange={(e) => setNewTaxi({ ...newTaxi, vehicleModel: e.target.value })}
                        placeholder="Toyota Corolla"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <Label>Año</Label>
                      <Input
                        type="number"
                        value={newTaxi.vehicleYear}
                        onChange={(e) => setNewTaxi({ ...newTaxi, vehicleYear: parseInt(e.target.value) || new Date().getFullYear() })}
                      />
                    </div>
                    <div>
                      <Label>Color</Label>
                      <Input
                        value={newTaxi.vehicleColor}
                        onChange={(e) => setNewTaxi({ ...newTaxi, vehicleColor: e.target.value })}
                        placeholder="Blanco"
                      />
                    </div>
                    <div>
                      <Label>Capacidad</Label>
                      <Input
                        type="number"
                        value={newTaxi.vehicleCapacity}
                        onChange={(e) => setNewTaxi({ ...newTaxi, vehicleCapacity: parseInt(e.target.value) || 4 })}
                      />
                    </div>
                  </div>
                  <Button onClick={async () => {
                    try {
                      await apiClient.post('/tourism/taxis', {
                        ...newTaxi,
                        userId: 1 // You should get this from auth
                      });
                      setNewTaxi({ licenseNumber: '', vehiclePlate: '', vehicleModel: '', vehicleYear: new Date().getFullYear(), vehicleColor: '', vehicleCapacity: 4 });
                      loadData();
                      toast({ title: 'Taxi registrado', description: 'El taxi se registró correctamente.' });
                    } catch (error: any) {
                      toast({ title: 'Error', description: error?.message || 'No se pudo registrar el taxi.' });
                    }
                  }}>
                    Registrar Taxi
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
          
          <div className="grid gap-4">
            {(Array.isArray(taxis) ? taxis : []).map((taxi) => (
              <Card key={taxi.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">
                      <Car className="w-8 h-8 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-lg">{taxi.user?.firstName} {taxi.user?.lastName}</CardTitle>
                      <p className="text-sm text-muted-foreground">{taxi.vehicleModel} {taxi.vehicleYear}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="flex items-center gap-1">
                      <Star className="w-3 h-3" />
                      {taxi.rating}
                    </Badge>
                    <Badge variant={taxi.isAvailable ? "default" : "secondary"}>
                      {taxi.isAvailable ? 'Disponible' : 'Ocupado'}
                    </Badge>
                    {isSuperAdmin && (
                      <div className="flex gap-1">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => console.log('Edit taxi:', taxi.id)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={async () => {
                            try {
                              await apiClient.delete(`/tourism/taxis/${taxi.id}`);
                              loadData();
                              toast({ title: 'Taxi eliminado', description: 'Se eliminó correctamente.' });
                            } catch (error) {
                              toast({ title: 'Error', description: 'No se pudo eliminar el taxi.' });
                            }
                          }}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="font-medium">Placa:</span> {taxi.vehiclePlate}
                    </div>
                    <div>
                      <span className="font-medium">Capacidad:</span> {taxi.vehicleCapacity} pasajeros
                    </div>
                    <div>
                      <span className="font-medium">Color:</span> {taxi.vehicleColor}
                    </div>
                    <div>
                      <span className="font-medium">Viajes:</span> {taxi.totalTrips}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="geolocation" className="space-y-4">
          <GeolocationTab activeSubTab="geofences" />
        </TabsContent>

        <TabsContent value="promotional" className="space-y-4">
          <div className="text-center py-12">
            <Image className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">Contenido Promocional</h3>
            <p className="text-gray-600 mb-4">Gestiona banners, ofertas especiales y campañas promocionales</p>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2 mx-auto">
                  <Plus className="w-4 h-4" />
                  Crear Campaña
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Crear Nueva Campaña Promocional</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label>Título</Label>
                    <Input value={newCampaign.title} onChange={(e) => setNewCampaign({ ...newCampaign, title: e.target.value })} />
                  </div>
                  <div>
                    <Label>Mensaje</Label>
                    <Textarea rows={3} value={newCampaign.message} onChange={(e) => setNewCampaign({ ...newCampaign, message: e.target.value })} />
                  </div>
                  <div>
                    <Label>Segmento</Label>
                    <Select value={newCampaign.segment} onValueChange={(v) => setNewCampaign({ ...newCampaign, segment: v })}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona segmento" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Todos</SelectItem>
                        <SelectItem value="tourists">Turistas</SelectItem>
                        <SelectItem value="guides">Guías</SelectItem>
                        <SelectItem value="business">Comercios</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Button onClick={handleCreateCampaign}>Crear Campaña</Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </TabsContent>

        <TabsContent value="ai-guides" className="space-y-4">
          <div className="text-center py-12">
            <Bot className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">Guías Virtuales con IA</h3>
            <p className="text-gray-600 mb-4">Configura y entrena asistentes virtuales para guiar a los turistas</p>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2 mx-auto">
                  <Settings className="w-4 h-4" />
                  Configurar IA
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Configuración de Guías IA</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label>Nombre</Label>
                    <Input value={aiGuideConfig.name} onChange={(e) => setAiGuideConfig({ ...aiGuideConfig, name: e.target.value })} />
                  </div>
                  <div>
                    <Label>Idioma</Label>
                    <Select value={aiGuideConfig.language} onValueChange={(v) => setAiGuideConfig({ ...aiGuideConfig, language: v })}>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="es">Español</SelectItem>
                        <SelectItem value="en">Inglés</SelectItem>
                        <SelectItem value="fr">Francés</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Personalidad</Label>
                    <Textarea rows={3} value={aiGuideConfig.personality} onChange={(e) => setAiGuideConfig({ ...aiGuideConfig, personality: e.target.value })} />
                  </div>
                  <Button onClick={handleSetupAIGuide}>Crear Guía IA</Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </TabsContent>

        <TabsContent value="ar-content" className="space-y-4">
          <div className="text-center py-12">
            <Camera className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">Contenido de Realidad Aumentada</h3>
            <p className="text-gray-600 mb-4">Crea experiencias inmersivas con realidad aumentada para destinos</p>
            <Button className="flex items-center gap-2 mx-auto">
              <Eye className="w-4 h-4" />
              Crear Experiencia AR
            </Button>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default ContentTab;