import { useState, useEffect } from 'react';
import SuperAdminTabNavigation from './admin/SuperAdminTabNavigation';
import AnalyticsTab from './admin/AnalyticsTab';
import RevenueTab from './admin/RevenueTab';
import EventsTab from './admin/EventsTab';
import OrganizersTab from './admin/OrganizersTab';
import ManagementTab from './admin/ManagementTab';
import { makeAuthenticatedRequest } from '../lib/api-client';

interface SuperAdminDashboardProps {
  // No props needed for now - keeping interface for future expansion
  readonly _placeholder?: never;
}

interface PlatformMetrics {
  totalRevenue: number;
  totalFees: number;
  activeOrganizers: number;
  totalTickets: number;
  revenueChange: number;
  feesChange: number;
  organizersChange: number;
  ticketsChange: number;
}

export default function SuperAdminDashboard(_props: SuperAdminDashboardProps) {
  const [activeTab, setActiveTab] = useState('analytics');
  const [platformMetrics, setPlatformMetrics] = useState<PlatformMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [user, setUser] = useState<{ id: string; email: string } | null>(null);

  const tabs = [
    {
      id: 'analytics',
      name: 'Analytics',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 002 2h2a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2z" />
        </svg>
      ),
      component: AnalyticsTab
    },
    {
      id: 'revenue',
      name: 'Revenue & Performance',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
        </svg>
      ),
      component: RevenueTab
    },
    {
      id: 'events',
      name: 'Events & Tickets',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
        </svg>
      ),
      component: EventsTab
    },
    {
      id: 'organizers',
      name: 'Organizers',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>
      ),
      component: OrganizersTab
    },
    {
      id: 'management',
      name: 'Management',
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      ),
      component: ManagementTab
    }
  ];

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

  const initializeComponent = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // Check super admin authentication
      const authResult = await checkSuperAdminAuth();
      if (!authResult) {
        window.location.href = '/login-new';
        return;
      }
      
      setUser(authResult.user);
      
      // Load platform metrics
      await loadPlatformMetrics();
    } catch (err) {
      console.error('SuperAdminDashboard initialization error:', err);
      setError('Failed to load dashboard data. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const checkSuperAdminAuth = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/check-super-admin');
      if (result.success && result.data.isSuperAdmin) {
        return result.data;
      }
      return null;
    } catch (error) {
      console.error('Super admin auth check error:', error);
      return null;
    }
  };

  const loadPlatformMetrics = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=platform_overview');
      
      if (result.success) {
        const data = result.data.summary;
        setPlatformMetrics({
          totalRevenue: data.totalRevenue || 0,
          totalFees: data.totalPlatformFees || 0,
          activeOrganizers: data.activeOrganizers || 0,
          totalTickets: data.totalTickets || 0,
          revenueChange: data.revenueGrowth || 0,
          feesChange: data.feesGrowth || 0,
          organizersChange: data.organizersThisMonth || 0,
          ticketsChange: data.ticketsThisMonth || 0
        });
      }
    } catch (error) {
      console.error('Platform metrics loading error:', error);
      // Silently handle error - metrics are non-critical
    }
  };

  // Loading state
  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent mx-auto mb-4"></div>
          <p className="text-white/80">Loading super admin dashboard...</p>
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="w-12 h-12 bg-red-500/20 rounded-xl flex items-center justify-center mx-auto mb-4">
            <svg className="w-6 h-6 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <p className="text-red-400 font-medium mb-2">Error Loading Dashboard</p>
          <p className="text-white/70 text-sm mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-lg text-white text-sm transition-colors"
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="mb-8">
        <h2 className="text-4xl md:text-5xl font-light text-white tracking-wide">Business Intelligence</h2>
        <p className="text-white/80 mt-2 text-lg font-light">Platform-wide analytics and performance insights</p>
      </div>

      {/* Key Metrics Dashboard */}
      {platformMetrics && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="w-12 h-12 bg-gradient-to-br from-green-500/20 to-emerald-500/20 rounded-xl flex items-center justify-center">
                <svg className="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path>
                </svg>
              </div>
              <div className="text-right">
                <p className="text-sm font-medium text-white/80">Platform Revenue</p>
                <p className="text-2xl font-light text-white">${platformMetrics.totalRevenue.toLocaleString()}</p>
                <p className="text-sm text-green-400">+{platformMetrics.revenueChange}% vs last month</p>
              </div>
            </div>
          </div>

          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="w-12 h-12 bg-gradient-to-br from-purple-500/20 to-pink-500/20 rounded-xl flex items-center justify-center">
                <svg className="w-6 h-6 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                </svg>
              </div>
              <div className="text-right">
                <p className="text-sm font-medium text-white/80">Platform Fees</p>
                <p className="text-2xl font-light text-white">${platformMetrics.totalFees.toLocaleString()}</p>
                <p className="text-sm text-purple-400">+{platformMetrics.feesChange}% vs last month</p>
              </div>
            </div>
          </div>

          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="w-12 h-12 bg-gradient-to-br from-blue-500/20 to-cyan-500/20 rounded-xl flex items-center justify-center">
                <svg className="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                </svg>
              </div>
              <div className="text-right">
                <p className="text-sm font-medium text-white/80">Active Organizers</p>
                <p className="text-2xl font-light text-white">{platformMetrics.activeOrganizers}</p>
                <p className="text-sm text-blue-400">+{platformMetrics.organizersChange} this month</p>
              </div>
            </div>
          </div>

          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="w-12 h-12 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-xl flex items-center justify-center">
                <svg className="w-6 h-6 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"></path>
                </svg>
              </div>
              <div className="text-right">
                <p className="text-sm font-medium text-white/80">Tickets Sold</p>
                <p className="text-2xl font-light text-white">{platformMetrics.totalTickets}</p>
                <p className="text-sm text-yellow-400">+{platformMetrics.ticketsChange} this month</p>
              </div>
            </div>
          </div>
        </div>
      )}

      <SuperAdminTabNavigation
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        platformMetrics={platformMetrics}
        user={user}
      />
    </div>
  );
}