import { useState, useEffect } from 'react';
import { makeAuthenticatedRequest } from '../../lib/api-client';

interface ManagementTabProps {
  platformMetrics: Record<string, unknown> | null;
  user: { id: string; email: string } | null;
}

export default function ManagementTab({ _platformMetrics, _user }: ManagementTabProps) {
  const [activeSection, setActiveSection] = useState('features');
  const [loading, setLoading] = useState(false);
  const [territoryManagerStats, setTerritoryManagerStats] = useState<Record<string, unknown>>({});
  const [featureToggles, setFeatureToggles] = useState<Record<string, unknown>>({});

  useEffect(() => {
    if (activeSection === 'features') {
      loadFeaturesData();
    }
  }, [activeSection]);

  const loadFeaturesData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadTerritoryManagerStats(),
        loadFeatureToggles()
      ]);
    } catch (_error) {
      // Handle error silently
    } finally {
      setLoading(false);
    }
  };

  const loadTerritoryManagerStats = async () => {
    try {
      // Mock data for now - replace with actual API call
      setTerritoryManagerStats({
        activeManagers: 3,
        pendingApplications: 2,
        totalCommissions: 5910.00
      });
    } catch (_error) {
      // Handle error silently
    }
  };

  const loadFeatureToggles = async () => {
    try {
      // For now, Territory Manager is always enabled (development)
      setFeatureToggles({
        territoryManagerEnabled: true
      });
    } catch (_error) {
      // Handle error silently
    }
  };

  const handleTerritoryManagerToggle = (enabled: boolean) => {
    // Show development warning
    alert('⚠️ Development Feature: The Territory Manager system is currently in development. Toggle changes will not persist between sessions.');
    
    setFeatureToggles(prev => ({
      ...prev,
      territoryManagerEnabled: enabled
    }));

  };

  const exportData = async (type: string) => {
    setLoading(true);
    try {
      let data: Record<string, unknown>[] = [];
      let filename = '';

      switch (type) {
        case 'revenue': {
          {
            const revenueResponse = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=revenue_breakdown');
            if (revenueResponse.success) {
              const totals = revenueResponse.data.totals || {};
              data = [{
                gross_revenue: totals.grossRevenue || 0,
                platform_fees: totals.platformFees || 0,
                net_revenue: (totals.grossRevenue || 0) - (totals.platformFees || 0),
                export_date: new Date().toISOString()
              }];
            }
            filename = `revenue-report-${new Date().toISOString().split('T')[0]}.csv`;
            break;
          }
        }

        case 'organizers': {
          {
            const organizerResponse = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=organizer_performance');
            if (organizerResponse.success) {
              data = (organizerResponse.data.organizers || []).map((org: Record<string, unknown>) => ({
                name: org.name,
                events: org.eventCount || 0,
                tickets_sold: org.ticketsSold || 0,
                total_revenue: org.totalRevenue || 0,
                platform_fees: org.platformFees || 0,
                avg_ticket_price: org.avgTicketPrice || 0,
                join_date: org.joinDate || ''
              }));
            }
            filename = `organizers-${new Date().toISOString().split('T')[0]}.csv`;
            break;
          }
        }

        case 'events': {
          {
            const eventResponse = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=event_analytics');
            if (eventResponse.success) {
              data = (eventResponse.data.events || []).map((event: Record<string, unknown>) => ({
                title: event.title,
                organization_id: event.organizationId,
                start_time: event.startTime,
                is_published: event.isPublished,
                category: event.category || '',
                tickets_sold: event.ticketsSold || 0,
                total_revenue: event.totalRevenue || 0,
                sell_through_rate: event.sellThroughRate || 0
              }));
            }
            filename = `events-${new Date().toISOString().split('T')[0]}.csv`;
            break;
          }
        }

        case 'tickets': {
          {
            const ticketResponse = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=platform_overview');
            if (ticketResponse.success) {
              const summary = ticketResponse.data.summary || {};
              data = [{
                total_tickets: summary.totalTickets || 0,
                total_revenue: summary.totalRevenue || 0,
                platform_fees: summary.totalPlatformFees || 0,
                export_note: 'Summary data only - detailed ticket data available on request'
              }];
            }
            filename = `tickets-summary-${new Date().toISOString().split('T')[0]}.csv`;
            break;
          }
        }
      }

      // Convert to CSV and download
      const csvContent = convertToCSV(data);
      downloadCSV(csvContent, filename);

    } catch (_error) {
      alert('Error exporting data');
    } finally {
      setLoading(false);
    }
  };

  const convertToCSV = (data: Record<string, unknown>[]) => {
    if (!data.length) return '';
    
    const headers = Object.keys(data[0]).join(',');
    const rows = data.map(row => 
      Object.values(row).map(value => 
        typeof value === 'string' ? `"${value}"` : value
      ).join(',')
    );
    
    return [headers, ...rows].join('\n');
  };

  const downloadCSV = (csvContent: string, filename: string) => {
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="p-4 md:p-6 space-y-6">
      <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
        <h3 className="text-xl md:text-2xl font-light text-white">Platform Management</h3>
        
        {/* Section Toggle */}
        <div className="flex items-center bg-white/10 rounded-lg p-1">
          <button
            onClick={() => setActiveSection('features')}
            className={`px-3 py-1 rounded-lg text-sm transition-all ${
              activeSection === 'features' 
                ? 'bg-white/20 text-white' 
                : 'text-white/60 hover:text-white'
            }`}
          >
            Features
          </button>
          <button
            onClick={() => setActiveSection('export')}
            className={`px-3 py-1 rounded-lg text-sm transition-all ${
              activeSection === 'export' 
                ? 'bg-white/20 text-white' 
                : 'text-white/60 hover:text-white'
            }`}
          >
            Data Export
          </button>
        </div>
      </div>

      {activeSection === 'features' ? (
        <div className="space-y-6">
          {/* Territory Manager Feature */}
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
              <div>
                <h4 className="text-lg font-medium text-white mb-2">Territory Manager System</h4>
                <p className="text-white/70 text-sm">
                  Enable and manage the territory-based commission system for event organizers.
                </p>
              </div>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="territory-manager-toggle"
                  checked={featureToggles.territoryManagerEnabled}
                  onChange={(e) => handleTerritoryManagerToggle(e.target.checked)}
                  className="sr-only"
                />
                <label
                  htmlFor="territory-manager-toggle"
                  className={`relative inline-block w-12 h-6 rounded-full cursor-pointer transition-colors ${
                    featureToggles.territoryManagerEnabled ? 'status-pill status-success' : 'status-pill status-neutral'
                  }`}
                >
                  <span
                    className={`absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                      featureToggles.territoryManagerEnabled ? 'translate-x-6' : 'translate-x-0'
                    }`}
                  />
                </label>
              </div>
            </div>

            {/* Territory Manager Stats */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
              <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                <div className="text-sm text-white/60">Active Managers</div>
                <div className="text-2xl font-bold text-white">{territoryManagerStats.activeManagers || 0}</div>
              </div>
              <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                <div className="text-sm text-white/60">Pending Applications</div>
                <div className="text-2xl font-bold text-yellow-400">{territoryManagerStats.pendingApplications || 0}</div>
              </div>
              <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                <div className="text-sm text-white/60">Total Commissions</div>
                <div className="text-2xl font-bold style={{ color: 'var(--success-color)' }}">
                  ${(territoryManagerStats.totalCommissions || 0).toFixed(2)}
                </div>
              </div>
            </div>

            {/* Quick Actions */}
            <div className="flex flex-col sm:flex-row gap-3">
              <button
                onClick={() => window.open('/admin/territory-manager/applications', '_blank')}
                className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white rounded-lg text-sm font-medium transition-all"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                View Applications
              </button>
              <button
                onClick={() => window.open('/territory-manager/dashboard', '_blank')}
                className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-lg text-white text-sm transition-colors"
              >
                <svg className="w-4 h-4" 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>
                Territory Dashboard
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="space-y-6">
          {/* Export Options */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
            {/* Revenue Export */}
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500/20 to-emerald-500/20 rounded-lg flex items-center justify-center">
                  <svg className="w-5 h-5 style={{ color: 'var(--success-color)' }}" 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>
                </div>
                <div>
                  <h4 className="text-lg font-medium text-white">Revenue Data</h4>
                  <p className="text-white/60 text-sm">Export platform revenue breakdown</p>
                </div>
              </div>
              <button
                onClick={() => exportData('revenue')}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white rounded-lg text-sm font-medium transition-all disabled:opacity-50"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                {loading ? 'Exporting...' : 'Export Revenue'}
              </button>
            </div>

            {/* Organizers Export */}
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500/20 to-cyan-500/20 rounded-lg flex items-center justify-center">
                  <svg className="w-5 h-5 style={{ color: 'var(--glass-text-accent)' }}" 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>
                </div>
                <div>
                  <h4 className="text-lg font-medium text-white">Organizer Data</h4>
                  <p className="text-white/60 text-sm">Export organizer performance metrics</p>
                </div>
              </div>
              <button
                onClick={() => exportData('organizers')}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white rounded-lg text-sm font-medium transition-all disabled:opacity-50"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                {loading ? 'Exporting...' : 'Export Organizers'}
              </button>
            </div>

            {/* Events Export */}
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500/20 to-pink-500/20 rounded-lg flex items-center justify-center">
                  <svg className="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3a2 2 0 012-2h4a2 2 0 012 2v4M8 7V5a2 2 0 012-2h4a2 2 0 012 2v2m-8 0v12a2 2 0 002 2h8a2 2 0 002-2V7m-8 0h8" />
                  </svg>
                </div>
                <div>
                  <h4 className="text-lg font-medium text-white">Event Data</h4>
                  <p className="text-white/60 text-sm">Export all platform events</p>
                </div>
              </div>
              <button
                onClick={() => exportData('events')}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white rounded-lg text-sm font-medium transition-all disabled:opacity-50"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                {loading ? 'Exporting...' : 'Export Events'}
              </button>
            </div>

            {/* Tickets Export */}
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-lg flex items-center justify-center">
                  <svg className="w-5 h-5 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" />
                  </svg>
                </div>
                <div>
                  <h4 className="text-lg font-medium text-white">Ticket Data</h4>
                  <p className="text-white/60 text-sm">Export ticket summary data</p>
                </div>
              </div>
              <button
                onClick={() => exportData('tickets')}
                disabled={loading}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-yellow-600 to-orange-600 hover:from-yellow-700 hover:to-orange-700 text-white rounded-lg text-sm font-medium transition-all disabled:opacity-50"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                {loading ? 'Exporting...' : 'Export Tickets'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}