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

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

export default function OrganizersTab({ _platformMetrics, _user }: OrganizersTabProps) {
  const [loading, setLoading] = useState(false);
  const [organizers, setOrganizers] = useState<Record<string, unknown>[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('totalRevenue');

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

  const loadOrganizers = async () => {
    setLoading(true);
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=organizer_performance');
      if (result.success) {
        setOrganizers(result.data.organizers || []);
      }
    } catch (_error) {
      // Handle error silently
    } finally {
      setLoading(false);
    }
  };

  const filteredOrganizers = organizers
    .filter(org => 
      org.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      org.email?.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'events':
          return (b.eventCount || 0) - (a.eventCount || 0);
        case 'revenue':
          return (b.totalRevenue || 0) - (a.totalRevenue || 0);
        case 'joinDate':
          return new Date(b.joinDate || 0).getTime() - new Date(a.joinDate || 0).getTime();
        default:
          return (b.totalRevenue || 0) - (a.totalRevenue || 0);
      }
    });

  const getPerformanceColor = (revenue: number) => {
    if (revenue > 10000) return 'text-green-400';
    if (revenue > 5000) return 'text-yellow-400';
    return 'text-white';
  };

  if (loading) {
    return (
      <div className="p-4 md:p-6">
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-6 space-y-6">
      <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
        <h3 className="text-xl md:text-2xl font-light text-white">Organizer Performance Dashboard</h3>
        <button
          onClick={loadOrganizers}
          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 self-start lg:self-auto"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          Refresh Data
        </button>
      </div>

      {/* Organizer Summary Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6">
          <div className="flex items-center gap-3 mb-3">
            <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 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" />
              </svg>
            </div>
            <div>
              <p className="text-sm font-medium text-white/80">Total Organizers</p>
              <p className="text-2xl font-light text-white">{organizers.length}</p>
            </div>
          </div>
        </div>

        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6">
          <div className="flex items-center gap-3 mb-3">
            <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 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" />
              </svg>
            </div>
            <div>
              <p className="text-sm font-medium text-white/80">Avg Revenue</p>
              <p className="text-2xl font-light text-white">
                ${organizers.length > 0 ? 
                  (organizers.reduce((sum, org) => sum + (org.totalRevenue || 0), 0) / organizers.length).toFixed(0) : 
                  '0'
                }
              </p>
            </div>
          </div>
        </div>

        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6">
          <div className="flex items-center gap-3 mb-3">
            <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="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>
            </div>
            <div>
              <p className="text-sm font-medium text-white/80">Avg Events</p>
              <p className="text-2xl font-light text-white">
                {organizers.length > 0 ? 
                  (organizers.reduce((sum, org) => sum + (org.eventCount || 0), 0) / organizers.length).toFixed(1) : 
                  '0'
                }
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Controls */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="flex-1">
          <input
            type="text"
            placeholder="Search organizers..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>
        <div>
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="revenue">Sort by Revenue</option>
            <option value="name">Sort by Name</option>
            <option value="events">Sort by Events</option>
            <option value="joinDate">Sort by Join Date</option>
          </select>
        </div>
      </div>

      {/* Organizers Table */}
      <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[700px]">
            <thead className="bg-white/10 backdrop-blur-xl">
              <tr>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Organization</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Events</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Revenue</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Platform Fees</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm hidden lg:table-cell">Avg. Ticket Price</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Status</th>
                <th className="text-left p-3 md:p-4 text-white font-medium text-sm">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/10">
              {filteredOrganizers.map(org => (
                <tr key={org.id} className="hover:bg-white/10">
                  <td className="p-3 md:p-4">
                    <div className="text-white font-medium">{org.name}</div>
                    <div className="text-white/60 text-sm">{org.email || 'No email'}</div>
                    <div className="lg:hidden text-white/60 text-xs mt-1">
                      Avg: ${(org.avgTicketPrice || 0).toFixed(2)}
                    </div>
                  </td>
                  <td className="p-3 md:p-4 text-white/80">
                    <div className="font-medium">{org.eventCount || 0}</div>
                    <div className="text-white/60 text-xs">{org.publishedEvents || 0} published</div>
                  </td>
                  <td className="p-3 md:p-4">
                    <div className={`font-bold ${getPerformanceColor(org.totalRevenue || 0)}`}>
                      ${(org.totalRevenue || 0).toLocaleString()}
                    </div>
                    <div className="text-white/60 text-xs">{org.ticketsSold || 0} tickets sold</div>
                  </td>
                  <td className="p-3 md:p-4 text-white/80 font-medium">
                    ${(org.platformFees || 0).toLocaleString()}
                  </td>
                  <td className="p-3 md:p-4 text-white/80 hidden lg:table-cell">
                    ${(org.avgTicketPrice || 0).toFixed(2)}
                  </td>
                  <td className="p-3 md:p-4">
                    <span className="px-2 py-1 bg-green-500/20 text-green-400 rounded-full text-xs">
                      Active
                    </span>
                  </td>
                  <td className="p-3 md:p-4">
                    <div className="flex flex-col sm:flex-row gap-1">
                      <button
                        onClick={() => window.open(`/admin/organizer-view/${org.id}`, '_blank')}
                        className="bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white px-2 py-1 rounded text-xs"
                      >
                        View
                      </button>
                      <button
                        onClick={() => window.open(`/admin/organizer/${org.id}/events`, '_blank')}
                        className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white px-2 py-1 rounded text-xs"
                      >
                        Events
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filteredOrganizers.length === 0 && (
                <tr>
                  <td colSpan={7} className="p-4 text-white/60 text-center">
                    {searchTerm ? 'No organizers match your search' : 'No organizers found'}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}