import React, { useState, useEffect } from 'react';
import {
  BarChart3,
  TrendingUp,
  Users,
  DollarSign,
  Calendar,
  Download,
  RefreshCw,
  Building2,
  Activity,
  Star,
  CreditCard,
  Target,
  Award,
  ArrowDown,
  Plus,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { useAsync } from '../../shared/hooks/useAsync';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import analyticsService, {
  ComprehensiveAnalyticsData,
  RevPARData,
  ADRData,
  OccupancyRateData,
  RevenueForecastData,
  MarketPenetrationData,
  StaffPerformanceData,
  ServiceUsageData,
  OperationalEfficiencyData,
  GuestLTVData,
  RepeatGuestRateData,
  GuestSatisfactionTrendsData,
  ProfitLossData,
  PaymentMethodAnalyticsData,
  RefundAnalysisData,
} from '../../features/analytics/services/analyticsService';
import { SimpleBarChart, SimpleLineChart, SimplePieChart, KPICard } from '../../features/analytics/components/SimpleChart';
import { exportData } from '../../shared/utils/exportUtils';
import CustomReportBuilder from '../../features/analytics/components/CustomReportBuilder';

type AnalyticsCategory = 'revenue' | 'operational' | 'guest' | 'financial' | 'comprehensive';

const AdvancedAnalyticsPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [activeCategory, setActiveCategory] = useState<AnalyticsCategory>('comprehensive');
  const [showReportBuilder, setShowReportBuilder] = useState(false);
  const [dateRange, setDateRange] = useState({
    from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
  });

  // Revenue Analytics
  const { data: revparData, loading: revparLoading, execute: fetchRevPAR } = useAsync<RevPARData>(
    () => analyticsService.getRevPAR({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: adrData, loading: adrLoading, execute: fetchADR } = useAsync<ADRData>(
    () => analyticsService.getADR({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: occupancyData, loading: occupancyLoading, execute: fetchOccupancy } = useAsync<OccupancyRateData>(
    () => analyticsService.getOccupancyRate({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: forecastData, execute: fetchForecast } = useAsync<RevenueForecastData>(
    () => analyticsService.getRevenueForecast(30).then(r => r.data),
    { immediate: false }
  );

  const { data: marketPenetrationData, execute: fetchMarketPenetration } = useAsync<MarketPenetrationData>(
    () => analyticsService.getMarketPenetration({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  // Operational Analytics
  const { data: staffPerformanceData, loading: staffLoading, execute: fetchStaffPerformance } = useAsync<StaffPerformanceData>(
    () => analyticsService.getStaffPerformance({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: serviceUsageData, loading: serviceLoading, execute: fetchServiceUsage } = useAsync<ServiceUsageData>(
    () => analyticsService.getServiceUsageAnalytics({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: efficiencyData, loading: efficiencyLoading, execute: fetchEfficiency } = useAsync<OperationalEfficiencyData>(
    () => analyticsService.getOperationalEfficiency({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  // Guest Analytics
  const { data: ltvData, loading: ltvLoading, execute: fetchLTV } = useAsync<GuestLTVData>(
    () => analyticsService.getGuestLifetimeValue({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: repeatRateData, loading: repeatLoading, execute: fetchRepeatRate } = useAsync<RepeatGuestRateData>(
    () => analyticsService.getRepeatGuestRate({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: satisfactionData, loading: satisfactionLoading, execute: fetchSatisfaction } = useAsync<GuestSatisfactionTrendsData>(
    () => analyticsService.getGuestSatisfactionTrends({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  // Financial Analytics
  const { data: profitLossData, loading: profitLossLoading, execute: fetchProfitLoss } = useAsync<ProfitLossData>(
    () => analyticsService.getProfitLoss({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: paymentMethodData, loading: paymentMethodLoading, execute: fetchPaymentMethods } = useAsync<PaymentMethodAnalyticsData>(
    () => analyticsService.getPaymentMethodAnalytics({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: refundData, loading: refundLoading, execute: fetchRefunds } = useAsync<RefundAnalysisData>(
    () => analyticsService.getRefundAnalysis({ from: dateRange.from, to: dateRange.to }).then(r => r.data),
    { immediate: false }
  );

  // Comprehensive Analytics
  const { data: comprehensiveData, loading: comprehensiveLoading, execute: fetchComprehensive } = useAsync<ComprehensiveAnalyticsData>(
    () => analyticsService.getComprehensiveAnalytics({
      from: dateRange.from,
      to: dateRange.to,
      include_revenue: true,
      include_operational: true,
      include_guest: true,
      include_financial: true,
    }).then(r => r.data),
    { immediate: true }
  );

  useEffect(() => {
    loadCategoryData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeCategory, dateRange]);

  const loadCategoryData = async () => {
    try {
      if (activeCategory === 'comprehensive') {
        await fetchComprehensive();
      } else if (activeCategory === 'revenue') {
        await Promise.all([fetchRevPAR(), fetchADR(), fetchOccupancy(), fetchForecast(), fetchMarketPenetration()]);
      } else if (activeCategory === 'operational') {
        await Promise.all([fetchStaffPerformance(), fetchServiceUsage(), fetchEfficiency()]);
      } else if (activeCategory === 'guest') {
        await Promise.all([fetchLTV(), fetchRepeatRate(), fetchSatisfaction()]);
      } else if (activeCategory === 'financial') {
        await Promise.all([fetchProfitLoss(), fetchPaymentMethods(), fetchRefunds()]);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load analytics data');
    }
  };

  const handleExport = (format: 'csv' | 'xlsx' | 'pdf' | 'json') => {
    try {
      let exportDataArray: Array<Record<string, unknown>> = [];
      let filename = 'analytics';
      let title = 'Analytics Report';

      if (activeCategory === 'revenue' && comprehensiveData?.revenue) {
        const revenue = comprehensiveData.revenue;
        exportDataArray = [
          { Metric: 'RevPAR', Value: revenue.revpar.revpar },
          { Metric: 'ADR', Value: revenue.adr.adr },
          { Metric: 'Occupancy Rate', Value: `${revenue.occupancy_rate.occupancy_rate}%` },
        ];
        filename = 'revenue-analytics';
        title = 'Revenue Analytics Report';
      } else if (activeCategory === 'operational' && comprehensiveData?.operational) {
        const operational = comprehensiveData.operational;
        exportDataArray = operational.staff_performance.staff_performance.map(staff => ({
          'Staff Name': staff.staff_name,
          'Email': staff.email,
          'Check-ins Handled': staff.check_ins_handled,
          'Performance Score': staff.performance_score,
        }));
        filename = 'operational-analytics';
        title = 'Operational Analytics Report';
      } else if (activeCategory === 'guest' && comprehensiveData?.guest) {
        const guest = comprehensiveData.guest;
        exportDataArray = guest.lifetime_value.guests.slice(0, 50).map(g => ({
          'Guest Name': g.name,
          'Email': g.email,
          'Total Bookings': g.total_bookings,
          'Lifetime Value': g.lifetime_value,
          'Average Booking Value': g.average_booking_value,
        }));
        filename = 'guest-analytics';
        title = 'Guest Analytics Report';
      } else if (activeCategory === 'financial' && comprehensiveData?.financial) {
        const financial = comprehensiveData.financial;
        exportDataArray = financial.payment_methods.payment_methods.map(pm => ({
          'Payment Method': pm.payment_method,
          'Transaction Count': pm.transaction_count,
          'Total Amount': pm.total_amount,
          'Average Amount': pm.average_amount,
          'Percentage': `${pm.percentage}%`,
        }));
        filename = 'financial-analytics';
        title = 'Financial Analytics Report';
      } else if (comprehensiveData) {
        // Export comprehensive data
        exportDataArray = [comprehensiveData];
        filename = 'comprehensive-analytics';
        title = 'Comprehensive Analytics Report';
      }

      if (exportDataArray.length > 0) {
        exportData({
          filename,
          title,
          data: exportDataArray,
          format,
        });
        toast.success(`Exported ${format.toUpperCase()} successfully`);
      } else {
        toast.error('No data to export');
      }
    } catch (error: unknown) {
      toast.error(`Export failed: ${getUserFriendlyError(error)}`);
    }
  };

  const isLoading = comprehensiveLoading || 
    (activeCategory === 'revenue' && (revparLoading || adrLoading || occupancyLoading)) ||
    (activeCategory === 'operational' && (staffLoading || serviceLoading || efficiencyLoading)) ||
    (activeCategory === 'guest' && (ltvLoading || repeatLoading || satisfactionLoading)) ||
    (activeCategory === 'financial' && (profitLossLoading || paymentMethodLoading || refundLoading));

  const categories = [
    { id: 'comprehensive' as AnalyticsCategory, label: 'Comprehensive', icon: BarChart3, color: 'blue' },
    { id: 'revenue' as AnalyticsCategory, label: 'Revenue', icon: DollarSign, color: 'green' },
    { id: 'operational' as AnalyticsCategory, label: 'Operational', icon: Activity, color: 'orange' },
    { id: 'guest' as AnalyticsCategory, label: 'Guest', icon: Users, color: 'purple' },
    { id: 'financial' as AnalyticsCategory, label: 'Financial', icon: CreditCard, color: 'red' },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
        {/* Header */}
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 mb-2">Advanced Analytics & BI</h1>
              <p className="text-gray-600">Comprehensive business intelligence and analytics dashboard</p>
            </div>
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2">
                <Calendar className="w-5 h-5 text-gray-500" />
                <input
                  type="date"
                  value={dateRange.from}
                  onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
                  className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                />
                <span className="text-gray-500">to</span>
                <input
                  type="date"
                  value={dateRange.to}
                  onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
                  className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                />
              </div>
              <button
                onClick={loadCategoryData}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2"
              >
                <RefreshCw className="w-4 h-4" />
                Refresh
              </button>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowReportBuilder(true)}
                  className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" />
                  Custom Report
                </button>
                <button
                  onClick={() => handleExport('csv')}
                  className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors flex items-center gap-2"
                >
                  <Download className="w-4 h-4" />
                  Export
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Category Tabs */}
        <div className="bg-white rounded-xl shadow-lg p-2 border border-gray-100">
          <div className="flex flex-wrap gap-2">
            {categories.map((category) => {
              const Icon = category.icon;
              const isActive = activeCategory === category.id;
              return (
                <button
                  key={category.id}
                  onClick={() => setActiveCategory(category.id)}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all ${
                    isActive
                      ? 'bg-indigo-600 text-white shadow-md'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {category.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Content */}
        {isLoading ? (
          <Loading fullScreen text="Loading analytics..." />
        ) : (
          <div className="space-y-6">
            {activeCategory === 'comprehensive' && comprehensiveData && (
              <ComprehensiveView data={comprehensiveData} formatCurrency={formatCurrency} />
            )}
            {activeCategory === 'revenue' && (
              <RevenueView
                revparData={revparData ?? undefined}
                adrData={adrData ?? undefined}
                occupancyData={occupancyData ?? undefined}
                forecastData={forecastData ?? undefined}
                marketPenetrationData={marketPenetrationData ?? undefined}
                formatCurrency={formatCurrency}
              />
            )}
            {activeCategory === 'operational' && (
              <OperationalView
                staffPerformanceData={staffPerformanceData ?? undefined}
                serviceUsageData={serviceUsageData ?? undefined}
                efficiencyData={efficiencyData ?? undefined}
                formatCurrency={formatCurrency}
              />
            )}
            {activeCategory === 'guest' && (
              <GuestView
                ltvData={ltvData ?? undefined}
                repeatRateData={repeatRateData ?? undefined}
                satisfactionData={satisfactionData ?? undefined}
                formatCurrency={formatCurrency}
              />
            )}
            {activeCategory === 'financial' && (
              <FinancialView
                profitLossData={profitLossData ?? undefined}
                paymentMethodData={paymentMethodData ?? undefined}
                refundData={refundData ?? undefined}
                formatCurrency={formatCurrency}
              />
            )}
          </div>
        )}

        {/* Custom Report Builder Modal */}
        {showReportBuilder && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="max-w-4xl w-full max-h-[90vh] overflow-y-auto">
              <CustomReportBuilder onClose={() => setShowReportBuilder(false)} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Comprehensive View Component
const ComprehensiveView: React.FC<{ data: ComprehensiveAnalyticsData; formatCurrency: (amount: number) => string }> = ({ data, formatCurrency }) => {
  return (
    <div className="space-y-6">
      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {data.revenue && (
          <>
            <KPICard
              title="RevPAR"
              value={formatCurrency(data.revenue.revpar.revpar)}
              icon={<TrendingUp className="w-6 h-6" />}
              color="blue"
            />
            <KPICard
              title="ADR"
              value={formatCurrency(data.revenue.adr.adr)}
              icon={<DollarSign className="w-6 h-6" />}
              color="green"
            />
            <KPICard
              title="Occupancy Rate"
              value={`${data.revenue.occupancy_rate.occupancy_rate.toFixed(1)}%`}
              icon={<Building2 className="w-6 h-6" />}
              color="orange"
            />
            <KPICard
              title="Net Revenue"
              value={data.financial ? formatCurrency(data.financial.profit_loss.net_revenue) : 'N/A'}
              icon={<CreditCard className="w-6 h-6" />}
              color="purple"
            />
          </>
        )}
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {data.revenue && data.revenue.market_penetration && (
          <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Market Penetration by Room Type</h3>
            <SimpleBarChart
              data={data.revenue.market_penetration.penetration_by_room_type.map((item) => ({
                label: item.room_type,
                value: item.market_share,
              }))}
              height={200}
            />
          </div>
        )}

        {data.financial && data.financial.payment_methods && (
          <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Payment Methods Distribution</h3>
            <SimplePieChart
              data={data.financial.payment_methods.payment_methods.map((item) => ({
                label: item.payment_method,
                value: item.percentage,
              }))}
              size={200}
            />
          </div>
        )}
      </div>
    </div>
  );
};

// Revenue View Component
const RevenueView: React.FC<{
  revparData?: RevPARData;
  adrData?: ADRData;
  occupancyData?: OccupancyRateData;
  forecastData?: RevenueForecastData;
  marketPenetrationData?: MarketPenetrationData;
  formatCurrency: (amount: number) => string;
}> = ({ revparData, adrData, occupancyData, forecastData, marketPenetrationData, formatCurrency }) => {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {revparData && (
          <KPICard
            title="RevPAR"
            value={formatCurrency(revparData.revpar)}
            subtitle={`${revparData.period_days} days`}
            icon={<TrendingUp className="w-6 h-6" />}
            color="blue"
          />
        )}
        {adrData && (
          <KPICard
            title="ADR"
            value={formatCurrency(adrData.adr)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
        )}
        {occupancyData && (
          <KPICard
            title="Occupancy Rate"
            value={`${occupancyData.occupancy_rate.toFixed(1)}%`}
            subtitle={`${occupancyData.occupied_room_nights} / ${occupancyData.available_room_nights} nights`}
            icon={<Building2 className="w-6 h-6" />}
            color="orange"
          />
        )}
      </div>

      {forecastData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Revenue Forecast (Next 30 Days)</h3>
          <SimpleLineChart
            data={forecastData.forecast.slice(0, 30).map(item => ({
              label: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
              value: item.forecasted_revenue,
            }))}
            height={200}
          />
        </div>
      )}

      {marketPenetrationData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Market Penetration by Room Type</h3>
          <SimpleBarChart
            data={marketPenetrationData.penetration_by_room_type.map((item) => ({
              label: item.room_type,
              value: item.market_share,
            }))}
            height={200}
          />
        </div>
      )}
    </div>
  );
};

// Operational View Component
const OperationalView: React.FC<{
  staffPerformanceData?: StaffPerformanceData;
  serviceUsageData?: ServiceUsageData;
  efficiencyData?: OperationalEfficiencyData;
  formatCurrency: (amount: number) => string;
}> = ({ serviceUsageData, efficiencyData, formatCurrency }) => {
  return (
    <div className="space-y-6">
      {efficiencyData && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <KPICard
            title="Conversion Rate"
            value={`${efficiencyData.conversion_rate.toFixed(1)}%`}
            icon={<Target className="w-6 h-6" />}
            color="blue"
          />
          <KPICard
            title="Avg Booking Value"
            value={formatCurrency(efficiencyData.average_booking_value)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
          <KPICard
            title="Cancellation Rate"
            value={`${efficiencyData.cancellation_rate.toFixed(1)}%`}
            icon={<Activity className="w-6 h-6" />}
            color="red"
          />
        </div>
      )}

      {serviceUsageData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Top Services by Revenue</h3>
          <SimpleBarChart
            data={serviceUsageData.services.slice(0, 10).map(item => ({
              label: item.service_name,
              value: item.total_revenue,
            }))}
            height={250}
          />
        </div>
      )}
    </div>
  );
};

// Guest View Component
const GuestView: React.FC<{
  ltvData?: GuestLTVData;
  repeatRateData?: RepeatGuestRateData;
  satisfactionData?: GuestSatisfactionTrendsData;
  formatCurrency: (amount: number) => string;
}> = ({ ltvData, repeatRateData, satisfactionData, formatCurrency }) => {
  return (
    <div className="space-y-6">
      {repeatRateData && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <KPICard
            title="Repeat Guest Rate"
            value={`${repeatRateData.repeat_guest_rate.toFixed(1)}%`}
            subtitle={`${repeatRateData.repeat_guests} repeat / ${repeatRateData.total_guests} total`}
            icon={<Users className="w-6 h-6" />}
            color="purple"
          />
          {ltvData && (
            <KPICard
              title="Average LTV"
              value={formatCurrency(ltvData.average_ltv)}
              subtitle={`${ltvData.total_guests_analyzed} guests`}
              icon={<Award className="w-6 h-6" />}
              color="blue"
            />
          )}
          {satisfactionData && (
            <KPICard
              title="Avg Satisfaction"
              value={`${satisfactionData.overall_average_rating.toFixed(1)}/5`}
              subtitle={`${satisfactionData.total_reviews} reviews`}
              icon={<Star className="w-6 h-6" />}
              color="orange"
            />
          )}
        </div>
      )}

      {satisfactionData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Satisfaction Trends</h3>
          <SimpleLineChart
            data={satisfactionData.trends.map(item => ({
              label: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
              value: item.average_rating,
            }))}
            height={200}
          />
        </div>
      )}
    </div>
  );
};

// Financial View Component
const FinancialView: React.FC<{
  profitLossData?: ProfitLossData;
  paymentMethodData?: PaymentMethodAnalyticsData;
  refundData?: RefundAnalysisData;
  formatCurrency: (amount: number) => string;
}> = ({ profitLossData, paymentMethodData, formatCurrency }) => {
  return (
    <div className="space-y-6">
      {profitLossData && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <KPICard
            title="Total Revenue"
            value={formatCurrency(profitLossData.total_revenue)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
          <KPICard
            title="Refunds"
            value={formatCurrency(profitLossData.refunds)}
            icon={<ArrowDown className="w-6 h-6" />}
            color="red"
          />
          <KPICard
            title="Net Revenue"
            value={formatCurrency(profitLossData.net_revenue)}
            icon={<TrendingUp className="w-6 h-6" />}
            color="blue"
          />
          <KPICard
            title="Gross Profit"
            value={formatCurrency(profitLossData.gross_profit)}
            icon={<Award className="w-6 h-6" />}
            color="purple"
          />
        </div>
      )}

      {paymentMethodData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Payment Methods Distribution</h3>
          <SimplePieChart
            data={paymentMethodData.payment_methods.map((item) => ({
              label: item.payment_method,
              value: item.percentage,
            }))}
            size={250}
          />
        </div>
      )}
    </div>
  );
};

export default AdvancedAnalyticsPage;

