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

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

export default function AnalyticsTab({ _platformMetrics, _user }: AnalyticsTabProps) {
  const [loading, setLoading] = useState(false);
  const [revenueChartData, setRevenueChartData] = useState<Record<string, unknown> | null>(null);
  const [topOrganizers, setTopOrganizers] = useState<Record<string, unknown>[]>([]);
  const [recentActivity, setRecentActivity] = useState<Record<string, unknown>[]>([]);

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

  const loadAnalyticsData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadRevenueChart(),
        loadTopOrganizers(),
        loadRecentActivity()
      ]);
    } catch (error) {
      console.error('Analytics data loading error:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadRevenueChart = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=sales_trends');
      if (result.success) {
        setRevenueChartData(result.data);
      }
    } catch (error) {
      console.error('Revenue chart loading error:', error);
    }
  };

  const loadTopOrganizers = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=organizer_performance&limit=5');
      if (result.success) {
        setTopOrganizers(result.data.organizers || []);
      }
    } catch (error) {
      console.error('Top organizers loading error:', error);
    }
  };

  const loadRecentActivity = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=recent_activity');
      if (result.success) {
        setRecentActivity(result.data.activities || []);
      }
    } catch (error) {
      console.error('Recent activity loading error:', error);
    }
  };

  const formatActivity = (activity: Record<string, unknown>) => {
    let icon = '📊';
    let title = '';
    let subtitle = '';

    switch (activity.type) {
      case 'ticket_sale':
        icon = '🎫';
        title = `New ticket sale: $${activity.amount}`;
        subtitle = `${activity.event_name} by ${activity.organization_name}`;
        break;
      case 'event_created':
        icon = '📅';
        title = `New event: ${activity.name}`;
        subtitle = `Created by ${activity.organization_name}`;
        break;
      case 'organizer_joined':
        icon = '🏢';
        title = `New organizer: ${activity.name}`;
        subtitle = `Organization registered`;
        break;
      default:
        title = activity.description || 'Platform activity';
        subtitle = activity.details || '';
    }

    return { icon, title, subtitle };
  };

  if (loading) {
    return (
      <div className="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-6 space-y-6">
      <div className="flex justify-between items-center">
        <h3 className="text-2xl font-light text-white">Platform Analytics</h3>
        <button
          onClick={loadAnalyticsData}
          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="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>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 md:gap-6">
        {/* Revenue Trends Chart */}
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
          <h4 className="text-base md:text-lg font-medium text-white mb-3 md:mb-4">Revenue Trends</h4>
          {revenueChartData ? (
            <div className="space-y-4">
              <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                <span className="text-white">Total Revenue</span>
                <span className="text-white font-bold">
                  ${revenueChartData.summary?.totalRevenue?.toLocaleString() || '0'}
                </span>
              </div>
              <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                <span className="text-white">Average Monthly</span>
                <span className="text-white font-bold">
                  ${revenueChartData.summary?.averageMonthlyRevenue?.toFixed(2) || '0.00'}
                </span>
              </div>
              <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                <span className="text-white">Growth Rate</span>
                <span className={`font-bold ${
                  (revenueChartData.summary?.growth || 0) > 0 ? 'text-green-400' : 'text-red-400'
                }`}>
                  {(revenueChartData.summary?.growth || 0) > 0 ? '+' : ''}
                  {revenueChartData.summary?.growth?.toFixed(1) || '0.0'}%
                </span>
              </div>
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No revenue data available</div>
          )}
        </div>

        {/* Top Organizers */}
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4 md:p-6 shadow-lg">
          <h4 className="text-base md:text-lg font-medium text-white mb-3 md:mb-4">Top Organizers</h4>
          {topOrganizers.length > 0 ? (
            <div className="space-y-3">
              {topOrganizers.slice(0, 5).map((organizer, index) => (
                <div key={organizer.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-lg flex items-center justify-center">
                      <span className="text-white font-bold text-sm">#{index + 1}</span>
                    </div>
                    <div>
                      <div className="text-white font-medium">{organizer.name}</div>
                      <div className="text-white/60 text-sm">{organizer.eventCount} events</div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="text-white font-bold">${organizer.totalRevenue?.toLocaleString() || '0'}</div>
                    <div className="text-white/60 text-sm">{organizer.ticketsSold || 0} tickets</div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No organizer data available</div>
          )}
        </div>

        {/* Recent Activity */}
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6 shadow-lg lg:col-span-2">
          <h4 className="text-base md:text-lg font-medium text-white mb-3 md:mb-4">Recent Activity</h4>
          {recentActivity.length > 0 ? (
            <div className="space-y-3 max-h-64 overflow-y-auto">
              {recentActivity.slice(0, 10).map((activity, index) => {
                const { icon, title, subtitle } = formatActivity(activity);
                return (
                  <div key={index} className="flex items-start space-x-3 p-3 bg-white/5 rounded-lg">
                    <div className="text-lg">{icon}</div>
                    <div className="flex-1">
                      <p className="text-white font-medium text-sm">{title}</p>
                      <p className="text-white/60 text-xs">{subtitle}</p>
                      <p className="text-white/40 text-xs mt-1">
                        {new Date(activity.date || activity.created_at).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No recent activity</div>
          )}
        </div>
      </div>
    </div>
  );
}