import React, { useState, useMemo } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { DollarSign, TrendingUp, TrendingDown, CreditCard, Truck, RefreshCw, Package } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { formatMoney, getStoreCurrency } from '@/lib/currency';
import { useDashboardPeriod } from '@/hooks/useDashboardPeriod';
import { useRevenueAnalytics } from '@/hooks/useAnalytics';
import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling';
import { StatCard } from './components/StatCard';
import { ChartCard } from './components/ChartCard';
import { DataTable, Column } from './components/DataTable';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DUMMY_REVENUE_DATA, RevenueData, RevenueByProduct, RevenueByCategory, RevenueByPaymentMethod, RevenueByShippingMethod } from './data/dummyRevenue';

export default function RevenueAnalytics() {
  const { period } = useDashboardPeriod();
  const [granularity, setGranularity] = useState<'day' | 'week' | 'month'>('day');
  const store = getStoreCurrency();

  // Fetch real data or use dummy data based on toggle
  const { data, isLoading, error, refetch } = useRevenueAnalytics(DUMMY_REVENUE_DATA, granularity);

  // Filter and aggregate chart data by period and granularity
  const chartData = useMemo(() => {
    const filteredData = period === 'all' ? data.chart_data : data.chart_data.slice(-parseInt(period));
    
    if (granularity === 'day') {
      return filteredData;
    }
    
    if (granularity === 'week') {
      // Group by week
      const weeks: Record<string, any> = {};
      filteredData.forEach((d: any) => {
        const date = new Date(d.date);
        const weekStart = new Date(date);
        weekStart.setDate(date.getDate() - date.getDay());
        const weekKey = weekStart.toISOString().split('T')[0];
        
        if (!weeks[weekKey]) {
          weeks[weekKey] = { date: weekKey, gross: 0, net: 0, refunds: 0, tax: 0, shipping: 0 };
        }
        weeks[weekKey].gross += d.gross;
        weeks[weekKey].net += d.net;
        weeks[weekKey].refunds += d.refunds;
        weeks[weekKey].tax += d.tax;
        weeks[weekKey].shipping += d.shipping;
      });
      return Object.values(weeks);
    }
    
    if (granularity === 'month') {
      // Group by month
      const months: Record<string, any> = {};
      filteredData.forEach((d: any) => {
        const date = new Date(d.date);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        
        if (!months[monthKey]) {
          months[monthKey] = { date: monthKey, gross: 0, net: 0, refunds: 0, tax: 0, shipping: 0 };
        }
        months[monthKey].gross += d.gross;
        months[monthKey].net += d.net;
        months[monthKey].refunds += d.refunds;
        months[monthKey].tax += d.tax;
        months[monthKey].shipping += d.shipping;
      });
      return Object.values(months);
    }
    
    return filteredData;
  }, [data.chart_data, period, granularity]);

  // Calculate metrics from filtered period data
  const periodMetrics = useMemo(() => {
    if (period === 'all') {
      const grossRevenue = data.chart_data.reduce((sum: number, d: any) => sum + d.gross, 0);
      const netRevenue = data.chart_data.reduce((sum: number, d: any) => sum + d.net, 0);
      const tax = data.chart_data.reduce((sum: number, d: any) => sum + d.tax, 0);
      const refunds = data.chart_data.reduce((sum: number, d: any) => sum + d.refunds, 0);
      
      return {
        gross_revenue: grossRevenue,
        net_revenue: netRevenue,
        tax: tax,
        refunds: refunds,
        change_percent: undefined, // No comparison for "all time"
      };
    }
    
    const periodData = data.chart_data.slice(-parseInt(period));
    const previousData = data.chart_data.slice(-parseInt(period) * 2, -parseInt(period));
    
    const grossRevenue = periodData.reduce((sum: number, d: any) => sum + d.gross, 0);
    const netRevenue = periodData.reduce((sum: number, d: any) => sum + d.net, 0);
    const tax = periodData.reduce((sum: number, d: any) => sum + d.tax, 0);
    const refunds = periodData.reduce((sum: number, d: any) => sum + d.refunds, 0);
    
    const prevGrossRevenue = previousData.reduce((sum: number, d: any) => sum + d.gross, 0);
    const prevTax = previousData.reduce((sum: number, d: any) => sum + d.tax, 0);
    const prevRefunds = previousData.reduce((sum: number, d: any) => sum + d.refunds, 0);
    
    return {
      gross_revenue: grossRevenue,
      net_revenue: netRevenue,
      tax: tax,
      refunds: refunds,
      change_percent: prevGrossRevenue > 0 ? ((grossRevenue - prevGrossRevenue) / prevGrossRevenue) * 100 : 0,
      tax_change: prevTax > 0 ? ((tax - prevTax) / prevTax) * 100 : 0,
      refunds_change: prevRefunds > 0 ? ((refunds - prevRefunds) / prevRefunds) * 100 : 0,
    };
  }, [data.chart_data, period]);

  // Filter table data by period
  const filteredProducts = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_product.map((p: any) => ({
      ...p,
      revenue: Math.round(p.revenue * factor),
      refunds: Math.round(p.refunds * factor),
      net_revenue: Math.round(p.net_revenue * factor),
    }));
  }, [data.by_product, period]);

  const filteredCategories = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_category.map((c: any) => ({
      ...c,
      revenue: Math.round(c.revenue * factor),
    }));
  }, [data.by_category, period]);

  const filteredPaymentMethods = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_payment_method.map((p: any) => ({
      ...p,
      revenue: Math.round(p.revenue * factor),
    }));
  }, [data.by_payment_method, period]);

  const filteredShippingMethods = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_shipping_method.map((s: any) => ({
      ...s,
      revenue: Math.round(s.revenue * factor),
    }));
  }, [data.by_shipping_method, period]);

  // Show loading state
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">{__('Loading analytics...')}</p>
        </div>
      </div>
    );
  }

  // Show error state
  if (error) {
    return (
      <ErrorCard
        title={__('Failed to load revenue analytics')}
        message={getPageLoadErrorMessage(error)}
        onRetry={() => refetch()}
      />
    );
  }

  // Format currency for charts
  const formatCurrency = (value: number) => {
    if (value >= 1000000) {
      return `${store.symbol}${(value / 1000000).toFixed(1)}M`;
    }
    if (value >= 1000) {
      return `${store.symbol}${(value / 1000).toFixed(0)}K`;
    }
    return formatMoney(value, {
      currency: store.currency,
      symbol: store.symbol,
      thousandSep: store.thousand_sep,
      decimalSep: store.decimal_sep,
      decimals: 0,
      preferSymbol: true,
    });
  };

  // Table columns
  const productColumns: Column<RevenueByProduct>[] = [
    { key: 'name', label: __('Product'), sortable: true },
    { 
      key: 'orders', 
      label: __('Orders'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
    { 
      key: 'refunds', 
      label: __('Refunds'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
    { 
      key: 'net_revenue', 
      label: __('Net Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
  ];

  const categoryColumns: Column<RevenueByCategory>[] = [
    { key: 'name', label: __('Category'), sortable: true },
    { 
      key: 'orders', 
      label: __('Orders'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
    { 
      key: 'percentage', 
      label: __('% of Total'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}%`,
    },
  ];

  const paymentColumns: Column<RevenueByPaymentMethod>[] = [
    { key: 'method_title', label: __('Payment Method'), sortable: true },
    { 
      key: 'orders', 
      label: __('Orders'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
    { 
      key: 'percentage', 
      label: __('% of Total'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}%`,
    },
  ];

  const shippingColumns: Column<RevenueByShippingMethod>[] = [
    { key: 'method_title', label: __('Shipping Method'), sortable: true },
    { 
      key: 'orders', 
      label: __('Orders'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatMoney(value, {
        currency: store.currency,
        symbol: store.symbol,
        thousandSep: store.thousand_sep,
        decimalSep: store.decimal_sep,
        decimals: 0,
        preferSymbol: true,
      }),
    },
    { 
      key: 'percentage', 
      label: __('% of Total'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}%`,
    },
  ];

  return (
    <div className="space-y-6 lg:p-6 pb-6">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold">{__('Revenue Analytics')}</h1>
        <p className="text-sm text-muted-foreground">{__('Detailed revenue breakdown and trends')}</p>
      </div>

      {/* Metric Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title={__('Gross Revenue')}
          value={periodMetrics.gross_revenue}
          change={data.overview.change_percent}
          icon={DollarSign}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Net Revenue')}
          value={periodMetrics.net_revenue}
          change={data.overview.change_percent}
          icon={TrendingUp}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Tax Collected')}
          value={periodMetrics.tax}
          change={periodMetrics.tax_change}
          icon={CreditCard}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Refunds')}
          value={periodMetrics.refunds}
          change={periodMetrics.refunds_change}
          icon={RefreshCw}
          format="money"
          period={period}
        />
      </div>

      {/* Revenue Chart */}
      <ChartCard
        title={__('Revenue Over Time')}
        description={__('Gross and net revenue trends')}
        dataPoints={chartData.length}
        actions={
          <Select value={granularity} onValueChange={(value: any) => setGranularity(value)}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="day">{__('Daily')}</SelectItem>
              <SelectItem value="week">{__('Weekly')}</SelectItem>
              <SelectItem value="month">{__('Monthly')}</SelectItem>
            </SelectContent>
          </Select>
        }
      >
        {chartData.length === 0 || chartData.every((d: any) => d.gross === 0 && d.net === 0) ? (
          <div className="flex items-center justify-center h-[300px]">
            <div className="text-center">
              <Package className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground font-medium">{__('No revenue data available')}</p>
              <p className="text-sm text-muted-foreground mt-1">
                {__('Revenue data will appear once you have completed orders')}
              </p>
            </div>
          </div>
        ) : (
          <ResponsiveContainer width="100%" height={300}>
            <AreaChart data={chartData}>
            <defs>
              <linearGradient id="colorGross" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
              </linearGradient>
              <linearGradient id="colorNet" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#10b981" stopOpacity={0.3}/>
                <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
            <XAxis 
              dataKey="date" 
              className="text-xs"
              tickFormatter={(value) => {
                const date = new Date(value);
                return `${date.getMonth() + 1}/${date.getDate()}`;
              }}
            />
            <YAxis 
              className="text-xs"
              tickFormatter={formatCurrency}
            />
            <Tooltip
              content={({ active, payload }) => {
                if (!active || !payload || !payload.length) return null;
                return (
                  <div className="rounded-lg border bg-background p-3 shadow-lg">
                    <p className="text-sm font-medium mb-2">
                      {new Date(payload[0].payload.date).toLocaleDateString()}
                    </p>
                    {payload.map((entry: any) => (
                      <div key={entry.dataKey} className="flex items-center justify-between gap-4 text-sm">
                        <span style={{ color: entry.color }}>{entry.name}:</span>
                        <span className="font-medium">
                          {formatMoney(entry.value, {
                            currency: store.currency,
                            symbol: store.symbol,
                            thousandSep: store.thousand_sep,
                            decimalSep: store.decimal_sep,
                            decimals: 0,
                            preferSymbol: true,
                          })}
                        </span>
                      </div>
                    ))}
                  </div>
                );
              }}
            />
            <Legend />
            <Area
              type="monotone"
              dataKey="gross"
              name={__('Gross Revenue')}
              stroke="#3b82f6"
              fillOpacity={1}
              fill="url(#colorGross)"
            />
            <Area
              type="monotone"
              dataKey="net"
              name={__('Net Revenue')}
              stroke="#10b981"
              fillOpacity={1}
              fill="url(#colorNet)"
            />
          </AreaChart>
        </ResponsiveContainer>
        )}
      </ChartCard>

      {/* Revenue Breakdown Tables */}
      <Tabs defaultValue="products" className="space-y-4">
        <TabsList>
          <TabsTrigger value="products">{__('By Product')}</TabsTrigger>
          <TabsTrigger value="categories">{__('By Category')}</TabsTrigger>
          <TabsTrigger value="payment">{__('By Payment Method')}</TabsTrigger>
          <TabsTrigger value="shipping">{__('By Shipping Method')}</TabsTrigger>
        </TabsList>

        <TabsContent value="products" className="space-y-4">
          <ChartCard title={__('Revenue by Product')} description={__('Top performing products')}>
            <DataTable
              data={filteredProducts}
              columns={productColumns}
            />
          </ChartCard>
        </TabsContent>

        <TabsContent value="categories" className="space-y-4">
          <ChartCard title={__('Revenue by Category')} description={__('Performance by product category')}>
            <DataTable
              data={filteredCategories}
              columns={categoryColumns}
            />
          </ChartCard>
        </TabsContent>

        <TabsContent value="payment" className="space-y-4">
          <ChartCard title={__('Revenue by Payment Method')} description={__('Payment methods breakdown')}>
            <DataTable
              data={filteredPaymentMethods}
              columns={paymentColumns}
            />
          </ChartCard>
        </TabsContent>

        <TabsContent value="shipping" className="space-y-4">
          <ChartCard title={__('Revenue by Shipping Method')} description={__('Shipping methods breakdown')}>
            <DataTable
              data={filteredShippingMethods}
              columns={shippingColumns}
            />
          </ChartCard>
        </TabsContent>
      </Tabs>
    </div>
  );
}
