import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { useAdminData } from '@/hooks/useAdminData';
import { 
  Users, 
  DollarSign, 
  Calendar, 
  Activity, 
  AlertTriangle, 
  Shield,
  Settings,
  BarChart3,
  FileText,
  CreditCard,
  MapPin,
  Phone,
  Bell,
  Search,
  Filter,
  Download,
  Eye,
  Edit,
  Trash2,
  Check,
  X,
  Plus,
  Building,
  Navigation,
  HeadphonesIcon,
  Globe,
  Wifi,
  MessageSquare,
  TrendingUp,
  Star,
  Zap,
  UserCheck,
  Clock,
  RefreshCw,
  Send,
  Target,
  PieChart,
  BarChart,
  Hotel,
  UtensilsCrossed,
  Car,
  Store
} from 'lucide-react';

// Import tab components
import OverviewTab from '@/components/admin/OverviewTab';
import UsersTab from '@/components/admin/UsersTab';
import ServicesTab from '@/components/admin/ServicesTab';
import FinancialTab from '@/components/admin/FinancialTab';
import ContentTab from '@/components/admin/ContentTab';
import EmergencyTab from '@/components/admin/EmergencyTab';
import SupportTab from '@/components/admin/SupportTab';
import ConfigTab from '@/components/admin/ConfigTab';
import GeolocationTab from '@/components/admin/GeolocationTab';

const AdminDashboard = () => {
  const { user } = useAuth();
  const { 
    stats, 
    users, 
    destinations, 
    places, 
    establishments, 
    incidents, 
    reviews,
    loading, 
    error, 
    isAdmin, 
    isSuperAdmin,
    refreshData,
    loadUsers,
    loadDestinations,
    loadPlaces,
    loadEstablishments,
    loadIncidents,
    loadReviews,
    createDestination,
    updateDestination,
    deleteDestination,
    createPlace,
    updatePlace,
    deletePlace
  } = useAdminData();
  
  const [searchParams] = useSearchParams();
  const activeTab = searchParams.get('tab') || 'overview';


  // Listen to global refresh from layout
  useEffect(() => {
    const handler = () => refreshData();
    window.addEventListener('admin:refresh', handler);
    return () => window.removeEventListener('admin:refresh', handler);
  }, [refreshData]);

  // Check permissions
  if (!isAdmin) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <AlertTriangle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Acceso Denegado</h2>
          <p className="text-gray-600">No tienes permisos para acceder al panel de administración.</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-orange-500 mx-auto mb-4"></div>
          <div className="text-lg">Cargando panel de administración...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <div className="text-red-500 text-xl mb-4">{error}</div>
          <button 
            onClick={refreshData}
            className="bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-600"
          >
            Reintentar
          </button>
        </div>
      </div>
    );
  }

  // No mostrar tabs duplicados ya que están en el sidebar
  const tabs: any[] = [];

  // Filter tabs based on permissions
  const availableTabs = tabs.filter(tab => !tab.superAdminOnly || isSuperAdmin);

  const renderTabContent = () => {
    const tabProps = {
      stats,
      users,
      destinations,
      places,
      establishments,
      incidents,
      reviews,
      isAdmin,
      isSuperAdmin,
      refreshData,
      loadUsers,
      loadDestinations,
      loadPlaces,
      loadEstablishments,
      loadIncidents,
      loadReviews,
      onCreateDestination: createDestination,
      onUpdateDestination: updateDestination,
      onDeleteDestination: deleteDestination,
      onCreatePlace: createPlace,
      onUpdatePlace: updatePlace,
      onDeletePlace: deletePlace,
      onRefreshData: refreshData
    };

    switch (activeTab) {
      case 'overview':
        return <OverviewTab {...tabProps} />;
      case 'users':
        return <UsersTab {...tabProps} />;
      case 'services':
        return <ServicesTab {...tabProps} />;
      case 'financial':
        return <FinancialTab {...tabProps} />;
      case 'content':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="destinations" />;
      case 'content-destinations':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="destinations" />;
      case 'content-places':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="places" />;
      case 'content-guides':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="guides" />;
      case 'content-taxis':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="taxis" />;
      case 'content-geolocation':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="geolocation" />;
      case 'content-promotional':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="promotional" />;
      case 'content-ai-guides':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="ai-guides" />;
      case 'content-ar':
        return <ContentTab isSuperAdmin={isSuperAdmin} activeSubTab="ar-content" />;
      case 'geofences':
        return <GeolocationTab activeSubTab="geofences" />;
      case 'analytics':
        return <GeolocationTab activeSubTab="analytics" />;
      case 'testing':
        return <GeolocationTab activeSubTab="testing" />;
      case 'emergency-geo':
        return <GeolocationTab activeSubTab="emergency" />;
      case 'navigation':
        return <GeolocationTab activeSubTab="navigation" />;
      case 'emergency':
        return <EmergencyTab />;
      case 'support':
        return <SupportTab {...tabProps} />;
      case 'config':
        return <ConfigTab {...tabProps} />;
      default:
        return <OverviewTab {...tabProps} />;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 admin-dashboard">
      <div className="px-4 md:px-6 py-4 md:py-8 mobile-content">
        <div className="mobile-card md:bg-transparent md:shadow-none bg-white rounded-lg p-4 md:p-0">
          {renderTabContent()}
        </div>
      </div>
    </div>
  );
};

export default AdminDashboard;