import React, { useState, useEffect } from 'react';
import { 
  MapPin, 
  Plus, 
  Settings, 
  Shield, 
  AlertTriangle, 
  Activity,
  Navigation,
  Target,
  Eye,
  Trash2,
  Edit
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent } 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 { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

import { Loader } from '@googlemaps/js-api-loader';
import { useToast } from '@/hooks/use-toast';
import { Label } from '@/components/ui/label';
import { apiClient } from '@/services/adminApi';
import { useAuth } from '@/contexts/AuthContext';
import { ResponsiveContainer, AreaChart, Area, BarChart as RBarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

interface GeolocationTabProps {
  activeSubTab: string;
}

const GeolocationTab: React.FC<GeolocationTabProps> = ({ activeSubTab }) => {
  const [activeTab, setActiveTab] = useState(activeSubTab);
  useEffect(() => { setActiveTab(activeSubTab); }, [activeSubTab]);
  const [geofences, setGeofences] = useState<any[]>([]);
  const [analytics, setAnalytics] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const { isLoading: authLoading, isAuthenticated } = useAuth();
  
  const [newGeofence, setNewGeofence] = useState({
    name: '',
    latitude: 0,
    longitude: 0,
    radius: 500,
    type: 'tourist-zone',
    description: '',
    entryMessage: '',
    exitMessage: ''
  });

  const [locationTest, setLocationTest] = useState({
    latitude: 18.4735,
    longitude: -69.8849,
    activity: 'walking'
  });

  const [routeTest, setRouteTest] = useState({
    startLat: 18.4735,
    startLng: -69.8849,
    endLat: 18.4620,
    endLng: -69.9071,
    includeAttractions: true
  });

  const [panicTest, setPanicTest] = useState({
    latitude: 18.4740,
    longitude: -69.8855,
    message: 'Necesito ayuda'
  });

  // Maps & API key
  const { toast } = useToast();
  const [mapsApiKey, setMapsApiKey] = useState<string>(() => localStorage.getItem('googleMapsApiKey') || '');
  const [showApiKeyInput, setShowApiKeyInput] = useState(!localStorage.getItem('googleMapsApiKey'));
  const [googleObj, setGoogleObj] = useState<any>(null);
  const testMapRef = React.useRef<HTMLDivElement>(null);
  const navMapRef = React.useRef<HTMLDivElement>(null);
  const [testMap, setTestMap] = useState<any>(null);
  const [navMap, setNavMap] = useState<any>(null);
  const [directionsRenderer, setDirectionsRenderer] = useState<any>(null);

  const loadGoogle = async () => {
    if (googleObj) return googleObj;

    // Reusar instancia existente si ya está cargada
    if (typeof window !== 'undefined' && (window as any).google?.maps) {
      setGoogleObj((window as any).google);
      return (window as any).google;
    }

    // Si el script ya existe (posiblemente con otra API key), esperar su carga y reutilizarlo
    const existingScript = typeof document !== 'undefined'
      ? (document.getElementById('__googleMapsScriptId') as HTMLScriptElement | null)
      : null;

    if (existingScript) {
      await new Promise<void>((resolve, reject) => {
        if ((window as any).google?.maps) return resolve();
        existingScript.addEventListener('load', () => resolve(), { once: true });
        existingScript.addEventListener('error', () => reject(new Error('Fallo al cargar Google Maps script')), { once: true });
      });
      setGoogleObj((window as any).google);
      return (window as any).google;
    }

    if (!mapsApiKey) {
      toast({ 
        title: 'Google Maps no configurado', 
        description: 'Necesitas configurar una API key de Google Maps. Ingresa tu clave abajo.' 
      });
      setShowApiKeyInput(true);
      return null;
    }
    
    try {
      const loader = new Loader({ apiKey: mapsApiKey, version: 'weekly', libraries: ['places'], id: '__googleMapsScriptIdKaribeo' });
      const g = await loader.load();
      setGoogleObj(g);
      return g;
    } catch (err: any) {
      console.error('Error cargando Google Maps:', err);
      const msg = err?.message || '';
      if (msg.includes('RefererNotAllowedMapError')) {
        toast({ 
          title: 'Dominio no autorizado', 
          description: `Autoriza el dominio ${window.location.origin} en Google Cloud Console (restricción por HTTP Referrer).`,
          variant: 'destructive'
        });
        setShowApiKeyInput(true);
      } else if (msg.includes('Loader must not be called again with different options')) {
        // Si ya existe una instancia con otra configuración, reusar google si está disponible
        if ((window as any).google?.maps) {
          setGoogleObj((window as any).google);
          return (window as any).google;
        }
      } else {
        toast({ 
          title: 'Error con Google Maps', 
          description: msg || 'Error desconocido con la API de Google Maps.'
        });
      }
      return null;
    }
  };

  const handleSaveApiKey = () => {
    if (mapsApiKey.trim()) {
      localStorage.setItem('googleMapsApiKey', mapsApiKey.trim());
      setShowApiKeyInput(false);
      toast({ title: 'API Key guardada', description: 'Intenta usar los mapas nuevamente.' });
    }
  };

  // Espera hasta que el elemento esté en el DOM y tenga tamaño visible
  const waitForVisible = (el: HTMLElement | null, maxTries = 60): Promise<void> => {
    return new Promise((resolve) => {
      let tries = 0;
      const check = () => {
        if (el && el.isConnected && el.clientHeight > 0 && el.clientWidth > 0) {
          resolve();
          return;
        }
        if (tries++ >= maxTries) {
          resolve();
          return;
        }
        requestAnimationFrame(check);
      };
      check();
    });
  };

  const initTestMap = async () => {
    const g = await loadGoogle();
    if (!g) return;
    if (testMapRef.current && testMapRef.current instanceof HTMLElement && !testMap) {
      await waitForVisible(testMapRef.current);
      try {
        const m = new g.maps.Map(testMapRef.current as HTMLElement, {
          center: { lat: locationTest.latitude, lng: locationTest.longitude },
          zoom: 13,
        });
        setTestMap(m);
      } catch (e) {
        console.warn('Error inicializando Test Map:', e);
      }
    }
  };

  const initNavMap = async () => {
    const g = await loadGoogle();
    if (!g) return;
    if (navMapRef.current && navMapRef.current instanceof HTMLElement && !navMap) {
      await waitForVisible(navMapRef.current);
      try {
        const m = new g.maps.Map(navMapRef.current as HTMLElement, { center: { lat: routeTest.startLat, lng: routeTest.startLng }, zoom: 12 });
        setNavMap(m);
        const dr = new g.maps.DirectionsRenderer({ map: m });
        setDirectionsRenderer(dr);
      } catch (e) {
        console.warn('Error inicializando Nav Map:', e);
      }
    }
  };

  useEffect(() => {
    if (activeTab === 'testing') initTestMap();
    if (activeTab === 'navigation') initNavMap();
    // Reintentar si se guarda la API key
  }, [activeTab, mapsApiKey]);

  // Load geofences
  const loadGeofences = async () => {
    try {
      const data = await apiClient.get('/geolocation/geofences');
      setGeofences(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error loading geofences:', error);
    }
  };

  // Load analytics
  const loadAnalytics = async () => {
    try {
      const data = await apiClient.get('/geolocation/analytics?timeframe=7d');
      setAnalytics(data);
    } catch (error) {
      console.error('Error loading analytics:', error);
    }
  };

  useEffect(() => {
    const hasToken = !!(typeof window !== 'undefined' && (localStorage.getItem('karibeo-token') || localStorage.getItem('karibeo_token')));
    if (!authLoading && (isAuthenticated || hasToken)) {
      loadGeofences();
      loadAnalytics();
    }
  }, [authLoading, isAuthenticated]);

  // Create geofence
  const handleCreateGeofence = async () => {
    try {
      await apiClient.post('/geolocation/geofences', {
        name: newGeofence.name,
        latitude: newGeofence.latitude,
        longitude: newGeofence.longitude,
        radius: newGeofence.radius,
        type: newGeofence.type,
        description: newGeofence.description,
        entryMessage: newGeofence.entryMessage,
        exitMessage: newGeofence.exitMessage
      });
      setNewGeofence({
        name: '', latitude: 0, longitude: 0, radius: 500, type: 'tourist-zone',
        description: '', entryMessage: '', exitMessage: ''
      });
      loadGeofences();
      toast({ title: 'Geofence creado', description: 'Se creó correctamente.' });
    } catch (error: any) {
      console.error('Error creating geofence:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo crear el geofence.' });
    }
  };

  const handleDeleteGeofence = async (id: string) => {
    let success = false;
    try {
      await apiClient.delete(`/geolocation/geofences/${id}`);
      success = true;
    } catch (error: any) {
      // Many backends don't implement DELETE; try to soft-deactivate
      try {
        await apiClient.patch(`/geolocation/geofences/${id}`, { isActive: false });
        success = true;
      } catch (e2) {
        console.warn('Delete/patch not supported, removing locally:', id, e2);
        // Final fallback: remove locally to avoid UX dead-ends
        setGeofences((prev) => prev.filter((g) => g.id !== id));
        toast({ title: 'Eliminado localmente', description: 'El backend no permite eliminar este geofence. Se ocultó en la interfaz.' });
        return;
      }
    }

    if (success) {
      await loadGeofences();
      toast({ title: 'Geofence eliminado', description: 'Se eliminó o desactivó correctamente.' });
    }
  };
  // Test location update
  const handleLocationUpdate = async () => {
    try {
      const result = await apiClient.post('/geolocation/location/update', {
        latitude: locationTest.latitude,
        longitude: locationTest.longitude,
        accuracy: 10,
        speed: 5,
        activity: locationTest.activity
      });
      console.log('Location update result:', result);
      toast({ title: 'Ubicación actualizada', description: 'Se envió la ubicación de prueba.' });
      // Center marker on test map
      if (testMap && googleObj) {
        const marker = new googleObj.maps.Marker({ position: { lat: locationTest.latitude, lng: locationTest.longitude }, map: testMap });
        testMap.setCenter(marker.getPosition());
      }
    } catch (error: any) {
      console.error('Error updating location:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo actualizar la ubicación.' });
    }
  };

  // Test geofence check
  const handleGeofenceCheck = async () => {
    try {
      const result = await apiClient.post('/geolocation/geofences/check', {
        latitude: locationTest.latitude,
        longitude: locationTest.longitude
      });
      console.log('Geofence check result:', result);
      const matched = (result as any)?.geofences?.length || 0;
      toast({ title: 'Verificación de geofences', description: `Coincidencias: ${matched}` });
    } catch (error: any) {
      console.error('Error checking geofences:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo verificar geofences.' });
    }
  };

  // Test smart suggestions
  const handleSmartSuggestions = async () => {
    try {
      const result = await apiClient.post('/geolocation/suggestions/smart', {
        latitude: locationTest.latitude,
        longitude: locationTest.longitude,
        activity: locationTest.activity
      });
      console.log('Smart suggestions result:', result);
      toast({ title: 'Sugerencias IA', description: 'Sugerencias recibidas, revisa la consola.' });
    } catch (error: any) {
      console.error('Error getting smart suggestions:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo obtener sugerencias.' });
    }
  };

  // Test panic button
  const handlePanicButton = async () => {
    try {
      // Enviar alerta a POLITUR (backend de seguridad)
      const result = await apiClient.post('/security/emergency-alerts', {
        type: 'emergency',
        channel: 'politur',
        location: { latitude: panicTest.latitude, longitude: panicTest.longitude },
        message: panicTest.message || 'Alerta de emergencia',
      });
      console.log('Panic button result:', result);
      toast({ title: 'Emergencia', description: 'Alerta enviada a POLITUR.' });
    } catch (error: any) {
      console.error('Error triggering panic button:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo activar el botón de pánico.' });
    }
  };

  // Test route planning
  const handleRoutePlanning = async () => {
    try {
      const result = await apiClient.post('/geolocation/navigation/route', {
        startLat: routeTest.startLat,
        startLng: routeTest.startLng,
        endLat: routeTest.endLat,
        endLng: routeTest.endLng,
        includeAttractions: routeTest.includeAttractions
      });
      console.log('Route planning result:', result);
      toast({ title: 'Ruta planificada', description: 'Ruta generada correctamente.' });
      // Draw route on Google Maps
      if (navMap && googleObj) {
        const ds = new googleObj.maps.DirectionsService();
        const dr = directionsRenderer || new googleObj.maps.DirectionsRenderer({ map: navMap });
        setDirectionsRenderer(dr);
        const req = {
          origin: { lat: routeTest.startLat, lng: routeTest.startLng },
          destination: { lat: routeTest.endLat, lng: routeTest.endLng },
          travelMode: googleObj.maps.TravelMode.DRIVING,
        } as any;
        // Usar callback para máxima compatibilidad
        ds.route(req, (res: any, status: any) => {
          if (status === 'OK' || status === 200) {
            dr.setDirections(res);
          } else {
            console.warn('DirectionsService status:', status);
            toast({ title: 'Ruta no disponible', description: `Google Directions status: ${status}` });
          }
        });
      } else {
        toast({ title: 'Mapa no inicializado', description: 'Abre la pestaña Navegación para inicializar el mapa antes de planificar.' });
      }
    } catch (error: any) {
      console.error('Error planning route:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo planificar la ruta.' });
    }
  };

  // Test nearby attractions
  const handleNearbyAttractions = async () => {
    try {
      const result = await apiClient.get(`/geolocation/nearby/attractions?latitude=${locationTest.latitude}&longitude=${locationTest.longitude}&radius=500`);
      console.log('Nearby attractions result:', result);
      const count = Array.isArray(result) ? result.length : ((result as any)?.length || (result as any)?.data?.length || 0);
      toast({ title: 'Atracciones cercanas', description: `Resultados: ${count}` });
    } catch (error: any) {
      console.error('Error getting nearby attractions:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo obtener atracciones.' });
    }
  };

  // Test safety zones
  const handleSafetyZones = async () => {
    try {
      const result = await apiClient.get(`/geolocation/safety/zones?latitude=${locationTest.latitude}&longitude=${locationTest.longitude}`);
      console.log('Safety zones result:', result);
      toast({ title: 'Zonas de seguridad', description: 'Consulta completada. Revisa la consola.' });
    } catch (error: any) {
      console.error('Error getting safety zones:', error);
      toast({ title: 'Error', description: error?.message || 'No se pudo obtener zonas de seguridad.' });
    }
  };

  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 Geolocalización</h2>
        <div className="flex gap-2">
          <Badge variant="secondary" className="text-sm">
            {geofences.length} Geofences
          </Badge>
          <Badge variant="secondary" className="text-sm">
            {analytics?.totalUsers || 0} Usuarios Activos
          </Badge>
        </div>
      </div>

      {/* API Key Configuration */}
      {showApiKeyInput && (
        <Card className="border-orange-200 bg-orange-50">
          <CardHeader>
            <CardTitle className="text-orange-800">Configurar Google Maps API Key</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-orange-700">
              Para usar los mapas, necesitas una API key de Google Maps. 
              <a href="https://console.cloud.google.com/google/maps-apis/credentials" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline ml-1">
                Consigue una aquí
              </a>
            </p>
            <div className="flex gap-2">
              <Input
                placeholder="Ingresa tu Google Maps API Key"
                value={mapsApiKey}
                onChange={(e) => setMapsApiKey(e.target.value)}
                className="flex-1"
              />
              <Button onClick={handleSaveApiKey} disabled={!mapsApiKey.trim()}>
                Guardar
              </Button>
            </div>
            <p className="text-xs text-orange-600">
              Asegúrate de autorizar el dominio: <code className="bg-orange-100 px-1 rounded">{window.location.origin}</code> en tu Google Cloud Console
            </p>
          </CardContent>
        </Card>
      )}

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

        <TabsContent value="geofences" className="space-y-4">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">Gestión de Geofences</h3>
            <Dialog>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2">
                  <Plus className="w-4 h-4" />
                  Nuevo Geofence
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Crear Nuevo Geofence</DialogTitle>
                </DialogHeader>
                <div className="grid gap-4">
                  <div>
                    <Label htmlFor="geo-name">Nombre</Label>
                    <Input
                      id="geo-name"
                      value={newGeofence.name}
                      onChange={(e) => setNewGeofence({ ...newGeofence, name: e.target.value })}
                      placeholder="Ej: Zona Colonial"
                    />
                  </div>
                  <div>
                    <Label htmlFor="geo-type">Tipo</Label>
                    <Select value={newGeofence.type} onValueChange={(value) => setNewGeofence({ ...newGeofence, type: value })}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona el tipo" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="tourist-zone">Zona Turística</SelectItem>
                        <SelectItem value="attraction">Atracción</SelectItem>
                        <SelectItem value="safety-alert">Alerta de Seguridad</SelectItem>
                        <SelectItem value="restricted">Zona Restringida</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="geo-lat">Latitud</Label>
                      <Input
                        id="geo-lat"
                        type="number"
                        step="any"
                        value={newGeofence.latitude}
                        onChange={(e) => setNewGeofence({ ...newGeofence, latitude: parseFloat(e.target.value) || 0 })}
                        placeholder="18.4735"
                      />
                    </div>
                    <div>
                      <Label htmlFor="geo-lng">Longitud</Label>
                      <Input
                        id="geo-lng"
                        type="number"
                        step="any"
                        value={newGeofence.longitude}
                        onChange={(e) => setNewGeofence({ ...newGeofence, longitude: parseFloat(e.target.value) || 0 })}
                        placeholder="-69.8849"
                      />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="geo-radius">Radio (metros)</Label>
                    <Input
                      id="geo-radius"
                      type="number"
                      value={newGeofence.radius}
                      onChange={(e) => setNewGeofence({ ...newGeofence, radius: parseInt(e.target.value) || 500 })}
                      placeholder="500"
                    />
                  </div>
                  <div>
                    <Label htmlFor="geo-description">Descripción</Label>
                    <Textarea
                      id="geo-description"
                      value={newGeofence.description}
                      onChange={(e) => setNewGeofence({ ...newGeofence, description: e.target.value })}
                      placeholder="Descripción del área..."
                      rows={2}
                    />
                  </div>
                  <div>
                    <Label htmlFor="geo-entry">Mensaje de Entrada</Label>
                    <Input
                      id="geo-entry"
                      value={newGeofence.entryMessage}
                      onChange={(e) => setNewGeofence({ ...newGeofence, entryMessage: e.target.value })}
                      placeholder="Mensaje al entrar al área"
                    />
                  </div>
                  <div>
                    <Label htmlFor="geo-exit">Mensaje de Salida</Label>
                    <Input
                      id="geo-exit"
                      value={newGeofence.exitMessage}
                      onChange={(e) => setNewGeofence({ ...newGeofence, exitMessage: e.target.value })}
                      placeholder="Mensaje al salir del área"
                    />
                  </div>
                  <Button onClick={handleCreateGeofence} className="w-full">
                    Crear Geofence
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
          
          <div className="grid gap-4">
            {geofences.map((geofence) => (
              <Card key={geofence.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">
                      <Target className="w-8 h-8 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-lg">{geofence.name}</CardTitle>
                      <p className="text-sm text-muted-foreground">{geofence.type}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant="outline" className="flex items-center gap-1">
                      <Activity className="w-3 h-3" />
                      {geofence.entryCount} entradas
                    </Badge>
                    <div className="flex gap-1">
                      <Button variant="outline" size="sm">
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => handleDeleteGeofence(geofence.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600 mb-3">{geofence.description}</p>
                  <div className="flex flex-wrap gap-2">
                    <Badge variant="secondary" className="text-xs">
                      Radio: {geofence.radius}m
                    </Badge>
                    <Badge variant={geofence.isActive ? "default" : "secondary"} className="text-xs">
                      {geofence.isActive ? 'Activo' : 'Inactivo'}
                    </Badge>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="analytics" className="space-y-4">
          <h3 className="text-lg font-semibold">Analíticas de Geolocalización</h3>
          
          {analytics && (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Usuarios Totales</CardTitle>
                  <Activity className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{analytics.totalUsers}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Usuarios Activos</CardTitle>
                  <Activity className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{analytics.activeUsers}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Zonas Populares</CardTitle>
                  <MapPin className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{analytics.popularZones?.length || 0}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Total Geofences</CardTitle>
                  <Target className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{analytics.geofenceStats?.length || 0}</div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Área: Usuarios activos últimos 7 días */}
            <Card>
              <CardHeader>
                <CardTitle>Usuarios activos (últimos 7 días)</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    {(() => {
                      const labels = analytics?.dailyLabels || ['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'];
                      const values = (analytics?.dailyActiveUsers || [12,18,14,22,17,25,21]).map((n: any) => Number(n) || 0);
                      const data = labels.map((name: string, i: number) => ({ name, value: values[i] ?? 0 }));
                      return (
                        <AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                          <defs>
                            <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
                              <stop offset="5%" stopColor="#F84525" stopOpacity={0.4}/>
                              <stop offset="95%" stopColor="#F84525" stopOpacity={0}/>
                            </linearGradient>
                          </defs>
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="name" />
                          <YAxis allowDecimals={false} />
                          <Tooltip />
                          <Legend />
                          <Area type="monotone" dataKey="value" stroke="#F84525" fill="url(#colorValue)" name="Usuarios activos" />
                        </AreaChart>
                      );
                    })()}
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>

            {/* Barras: Entradas por geofence */}
            <Card>
              <CardHeader>
                <CardTitle>Entradas por geofence</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    {(() => {
                      const stats = analytics?.geofenceStats || [];
                      const labels = (stats.length ? stats.map((s: any) => s.name) : ['A','B','C','D']);
                      const values = (stats.length ? stats.map((s: any) => Number(s.entries) || 0) : [10,8,6,12]);
                      const data = labels.map((name: string, i: number) => ({ name, entries: values[i] ?? 0 }));
                      return (
                        <RBarChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="name" />
                          <YAxis allowDecimals={false} />
                          <Tooltip />
                          <Legend />
                          <Bar dataKey="entries" fill="#F84525" name="Entradas" />
                        </RBarChart>
                      );
                    })()}
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>
          </div>

          {analytics?.geofenceStats && (
            <Card>
              <CardHeader>
                <CardTitle>Estadísticas por Geofence</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {analytics.geofenceStats.map((stat: any, index: number) => (
                    <div key={index} className="flex justify-between items-center">
                      <span className="text-sm font-medium">{stat.name}</span>
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">{stat.type}</Badge>
                        <span className="text-sm text-muted-foreground">{stat.entries} entradas</span>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="testing" className="space-y-4">
          <h3 className="text-lg font-semibold">Pruebas de Funcionalidad</h3>
          
          <Card>
            <CardHeader>
              <CardTitle>Prueba de Ubicación (requiere Maps)</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label>Latitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={locationTest.latitude}
                    onChange={(e) => setLocationTest({ ...locationTest, latitude: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Longitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={locationTest.longitude}
                    onChange={(e) => setLocationTest({ ...locationTest, longitude: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Actividad</Label>
                  <Select value={locationTest.activity} onValueChange={(value) => setLocationTest({ ...locationTest, activity: value })}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="walking">Caminando</SelectItem>
                      <SelectItem value="driving">Conduciendo</SelectItem>
                      <SelectItem value="dining">Comiendo</SelectItem>
                      <SelectItem value="shopping">Comprando</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="flex gap-2">
                <Button onClick={handleLocationUpdate}>Actualizar Ubicación</Button>
                <Button onClick={handleGeofenceCheck}>Verificar Geofences</Button>
                <Button onClick={handleSmartSuggestions}>Sugerencias IA</Button>
                <Button onClick={handleNearbyAttractions}>Atracciones Cercanas</Button>
                <Button onClick={handleSafetyZones}>Zonas de Seguridad</Button>
              </div>
              <div className="mt-4">
                <div ref={testMapRef} className="w-full h-64 rounded-lg border relative">
                  {!mapsApiKey && (
                    <div className="absolute inset-0 flex items-center justify-center text-center p-4">
                      <p className="text-sm text-muted-foreground">Mapa deshabilitado. Configura una Google Maps API key restringida por dominio y autoriza este dominio en Google Cloud Console.</p>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="emergency" className="space-y-4">
          <h3 className="text-lg font-semibold">Sistema de Emergencias</h3>
          
          <Card>
            <CardHeader>
              <CardTitle>Prueba de Botón de Pánico</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Latitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={panicTest.latitude}
                    onChange={(e) => setPanicTest({ ...panicTest, latitude: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Longitud</Label>
                  <Input
                    type="number"
                    step="any"
                    value={panicTest.longitude}
                    onChange={(e) => setPanicTest({ ...panicTest, longitude: parseFloat(e.target.value) })}
                  />
                </div>
              </div>
              <div>
                <Label>Mensaje de Emergencia</Label>
                <Textarea
                  value={panicTest.message}
                  onChange={(e) => setPanicTest({ ...panicTest, message: e.target.value })}
                  placeholder="Describe la emergencia..."
                />
              </div>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="destructive" className="flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4" />
                    Activar Botón de Pánico
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Confirmar activación</AlertDialogTitle>
                    <AlertDialogDescription>
                      Se notificará a los servicios de emergencia con tu ubicación.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancelar</AlertDialogCancel>
                    <AlertDialogAction onClick={handlePanicButton}>Activar</AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="navigation" className="space-y-4">
          <h3 className="text-lg font-semibold">Sistema de Navegación</h3>
          
          <Card>
            <CardHeader>
              <CardTitle>Planificación de Rutas</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Latitud Origen</Label>
                  <Input
                    type="number"
                    step="any"
                    value={routeTest.startLat}
                    onChange={(e) => setRouteTest({ ...routeTest, startLat: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Longitud Origen</Label>
                  <Input
                    type="number"
                    step="any"
                    value={routeTest.startLng}
                    onChange={(e) => setRouteTest({ ...routeTest, startLng: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Latitud Destino</Label>
                  <Input
                    type="number"
                    step="any"
                    value={routeTest.endLat}
                    onChange={(e) => setRouteTest({ ...routeTest, endLat: parseFloat(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Longitud Destino</Label>
                  <Input
                    type="number"
                    step="any"
                    value={routeTest.endLng}
                    onChange={(e) => setRouteTest({ ...routeTest, endLng: parseFloat(e.target.value) })}
                  />
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={routeTest.includeAttractions}
                  onChange={(e) => setRouteTest({ ...routeTest, includeAttractions: e.target.checked })}
                />
                <Label>Incluir atracciones en la ruta</Label>
              </div>
              <Button onClick={handleRoutePlanning} className="flex items-center gap-2">
                <Navigation className="w-4 h-4" />
                Planificar Ruta
              </Button>
              <div className="mt-4">
                <div ref={navMapRef} className="w-full h-72 rounded-lg border relative">
                  {!mapsApiKey && (
                    <div className="absolute inset-0 flex items-center justify-center text-center p-4">
                      <p className="text-sm text-muted-foreground">Mapa deshabilitado. Configura una Google Maps API key restringida por dominio y autoriza este dominio en Google Cloud Console.</p>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default GeolocationTab;