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

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

export default function RevenueTab({ _platformMetrics, _user }: RevenueTabProps) {
  const [loading, setLoading] = useState(false);
  const [revenueBreakdown, setRevenueBreakdown] = useState<Record<string, unknown> | null>(null);
  const [monthlyComparison, setMonthlyComparison] = useState<Record<string, unknown> | null>(null);
  const [eventPerformance, setEventPerformance] = useState<Record<string, unknown> | null>(null);
  const [salesVelocity, setSalesVelocity] = useState<Record<string, unknown> | null>(null);

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

  const loadRevenueData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadRevenueBreakdown(),
        loadMonthlyComparison(),
        loadEventPerformance(),
        loadSalesVelocity()
      ]);
    } catch (_error) {
      // Handle error silently
    } finally {
      setLoading(false);
    }
  };

  const loadRevenueBreakdown = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=revenue_breakdown');
      if (result.success) {
        setRevenueBreakdown(result.data);
      }
    } catch (_error) {
      // Handle error silently
    }
  };

  const loadMonthlyComparison = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=sales_trends');
      if (result.success) {
        setMonthlyComparison(result.data);
      }
    } catch (_error) {
      // Handle error silently
    }
  };

  const loadEventPerformance = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=event_analytics');
      if (result.success) {
        setEventPerformance(result.data);
      }
    } catch (_error) {
      // Handle error silently
    }
  };

  const loadSalesVelocity = async () => {
    try {
      const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=sales_trends');
      if (result.success) {
        setSalesVelocity(result.data);
      }
    } catch (_error) {
      // Handle error silently
    }
  };

  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">Revenue & Performance Analysis</h3>
        <button
          onClick={loadRevenueData}
          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 Breakdown */}
        <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 Breakdown</h4>
          {revenueBreakdown ? (
            <div className="space-y-4">
              {(() => {
                const totals = revenueBreakdown.totals || {};
                const processingFees = (totals.grossRevenue || 0) * 0.029;
                const netToOrganizers = (totals.grossRevenue || 0) - (totals.platformFees || 0) - processingFees;
                
                return (
                  <>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Gross Revenue</span>
                      <span className="text-white font-bold">${(totals.grossRevenue || 0).toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Platform Fees</span>
                      <span className="text-white font-bold">${(totals.platformFees || 0).toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Processing Fees</span>
                      <span className="text-white font-bold">${processingFees.toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Net to Organizers</span>
                      <span className="text-white font-bold">${netToOrganizers.toLocaleString()}</span>
                    </div>
                  </>
                );
              })()}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No revenue breakdown available</div>
          )}
        </div>

        {/* Monthly Comparison */}
        <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">Monthly Comparison</h4>
          {monthlyComparison ? (
            <div className="space-y-4">
              {(() => {
                const summary = monthlyComparison.summary || {};
                return (
                  <>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Average Monthly Revenue</span>
                      <span className="text-white font-bold">${(summary.averageMonthlyRevenue || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Revenue Growth</span>
                      <span className={`font-bold ${
                        (summary.growth || 0) > 0 ? 'text-green-400' : 'text-red-400'
                      }`}>
                        {(summary.growth || 0) > 0 ? '+' : ''}{(summary.growth || 0).toFixed(1)}%
                      </span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Average Platform Fees</span>
                      <span className="text-white font-bold">${(summary.averageMonthlyFees || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Total Periods</span>
                      <span className="text-white font-bold">{summary.totalPeriods || 0}</span>
                    </div>
                  </>
                );
              })()}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No monthly comparison available</div>
          )}
        </div>

        {/* Event Performance */}
        <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">Event Performance Metrics</h4>
          {eventPerformance ? (
            <div className="space-y-4">
              {(() => {
                const summary = eventPerformance.summary || {};
                const eventsThisMonth = Math.floor((summary.totalEvents || 0) / 12);
                return (
                  <>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Average Ticket Price</span>
                      <span className="text-white font-bold">${(summary.avgTicketPrice || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Events This Month</span>
                      <span className="text-white font-bold">{eventsThisMonth}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Avg. Tickets per Event</span>
                      <span className="text-white font-bold">
                        {(summary.totalEvents || 0) > 0 ? Math.floor((summary.totalTicketsSold || 0) / (summary.totalEvents || 1)) : 0}
                      </span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Sell-through Rate</span>
                      <span className="text-white font-bold">{(summary.avgSellThroughRate || 0).toFixed(1)}%</span>
                    </div>
                  </>
                );
              })()}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No event performance data available</div>
          )}
        </div>

        {/* Sales Velocity */}
        <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">Sales Velocity</h4>
          {salesVelocity ? (
            <div className="space-y-4">
              {(() => {
                const trends = salesVelocity.trends || [];
                const recentTrends = trends.slice(-6);
                const totalTransactions = recentTrends.reduce((sum: number, t: Record<string, unknown>) => sum + (Number(t.transactions) || 0), 0);
                const totalRevenue = recentTrends.reduce((sum: number, t: Record<string, unknown>) => sum + (Number(t.revenue) || 0), 0);
                const avgTransactionValue = totalTransactions > 0 ? totalRevenue / totalTransactions : 0;
                
                const currentMonth = recentTrends[recentTrends.length - 1] || {};
                const previousMonth = recentTrends[recentTrends.length - 2] || {};
                const momGrowth = previousMonth && (Number(previousMonth.revenue) || 0) > 0 ? 
                  (((Number(currentMonth.revenue) || 0) - (Number(previousMonth.revenue) || 0)) / (Number(previousMonth.revenue) || 1)) * 100 : 0;
                
                return (
                  <>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Recent Transactions</span>
                      <span className="text-white font-bold">{totalTransactions}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Avg Transaction Value</span>
                      <span className="text-white font-bold">${avgTransactionValue.toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Month-over-Month</span>
                      <span className={`font-bold ${momGrowth > 0 ? 'text-green-400' : 'text-red-400'}`}>
                        {momGrowth > 0 ? '+' : ''}{momGrowth.toFixed(1)}%
                      </span>
                    </div>
                    <div className="flex justify-between items-center p-3 bg-white/5 rounded-lg">
                      <span className="text-white">Recent Revenue</span>
                      <span className="text-white font-bold">${totalRevenue.toFixed(2)}</span>
                    </div>
                  </>
                );
              })()}
            </div>
          ) : (
            <div className="text-white/60 text-center py-8">No sales velocity data available</div>
          )}
        </div>
      </div>
    </div>
  );
}