import React, { useState, useMemo } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { Tag, DollarSign, TrendingUp, ShoppingCart, Package } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { formatMoney, getStoreCurrency } from '@/lib/currency';
import { useDashboardPeriod } from '@/hooks/useDashboardPeriod';
import { useCouponsAnalytics } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DUMMY_COUPONS_DATA, CouponsData, CouponPerformance } from './data/dummyCoupons';

export default function CouponsReport() {
  const { period } = useDashboardPeriod();
  const store = getStoreCurrency();

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

  const chartData = useMemo(() => {
    return period === 'all' ? data.usage_chart : data.usage_chart.slice(-parseInt(period));
  }, [data.usage_chart, period]);

  // Calculate period metrics
  const periodMetrics = useMemo(() => {
    if (period === 'all') {
      const totalDiscount = data.usage_chart.reduce((sum: number, d: any) => sum + d.discount, 0);
      const totalUses = data.usage_chart.reduce((sum: number, d: any) => sum + d.uses, 0);
      
      return {
        total_discount: totalDiscount,
        coupons_used: totalUses,
        revenue_with_coupons: data.overview.revenue_with_coupons,
        avg_discount_per_order: data.overview.avg_discount_per_order,
        change_percent: undefined,
      };
    }
    
    const periodData = data.usage_chart.slice(-parseInt(period));
    const previousData = data.usage_chart.slice(-parseInt(period) * 2, -parseInt(period));
    
    const totalDiscount = periodData.reduce((sum: number, d: any) => sum + d.discount, 0);
    const totalUses = periodData.reduce((sum: number, d: any) => sum + d.uses, 0);
    
    const prevTotalDiscount = previousData.reduce((sum: number, d: any) => sum + d.discount, 0);
    const prevTotalUses = previousData.reduce((sum: number, d: any) => sum + d.uses, 0);
    
    const factor = parseInt(period) / 30;
    const revenueWithCoupons = Math.round(data.overview.revenue_with_coupons * factor);
    const prevRevenueWithCoupons = Math.round(data.overview.revenue_with_coupons * factor * 0.92); // Simulate previous
    
    const avgDiscountPerOrder = Math.round(data.overview.avg_discount_per_order * factor);
    const prevAvgDiscountPerOrder = Math.round(data.overview.avg_discount_per_order * factor * 1.05); // Simulate previous
    
    return {
      total_discount: totalDiscount,
      coupons_used: totalUses,
      revenue_with_coupons: revenueWithCoupons,
      avg_discount_per_order: avgDiscountPerOrder,
      change_percent: prevTotalDiscount > 0 ? ((totalDiscount - prevTotalDiscount) / prevTotalDiscount) * 100 : 0,
      coupons_used_change: prevTotalUses > 0 ? ((totalUses - prevTotalUses) / prevTotalUses) * 100 : 0,
      revenue_with_coupons_change: prevRevenueWithCoupons > 0 ? ((revenueWithCoupons - prevRevenueWithCoupons) / prevRevenueWithCoupons) * 100 : 0,
      avg_discount_per_order_change: prevAvgDiscountPerOrder > 0 ? ((avgDiscountPerOrder - prevAvgDiscountPerOrder) / prevAvgDiscountPerOrder) * 100 : 0,
    };
  }, [data.usage_chart, period, data.overview]);

  // Filter coupon performance table by period
  const filteredCoupons = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.coupons.map((c: CouponPerformance) => ({
      ...c,
      uses: Math.round(c.uses * factor),
      discount_amount: Math.round(c.discount_amount * factor),
      revenue_generated: Math.round(c.revenue_generated * factor),
    }));
  }, [data.coupons, 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 coupons analytics')}
        message={getPageLoadErrorMessage(error)}
        onRetry={() => refetch()}
      />
    );
  }

  // Format money with M/B abbreviations
  const formatMoneyAxis = (value: number) => {
    if (value >= 1000000000) {
      return `${(value / 1000000000).toFixed(1)}${__('B')}`;
    }
    if (value >= 1000000) {
      return `${(value / 1000000).toFixed(1)}${__('M')}`;
    }
    if (value >= 1000) {
      return `${(value / 1000).toFixed(0)}${__('K')}`;
    }
    return value.toString();
  };

  const formatCurrency = (value: number) => {
    return formatMoney(value, {
      currency: store.currency,
      symbol: store.symbol,
      thousandSep: store.thousand_sep,
      decimalSep: store.decimal_sep,
      decimals: 0,
      preferSymbol: true,
    });
  };

  const couponColumns: Column<CouponPerformance>[] = [
    { key: 'code', label: __('Coupon Code'), sortable: true },
    { 
      key: 'type', 
      label: __('Type'), 
      sortable: true,
      render: (value) => {
        const labels: Record<string, string> = {
          percent: __('Percentage'),
          fixed_cart: __('Fixed Cart'),
          fixed_product: __('Fixed Product'),
        };
        return labels[value] || value;
      },
    },
    { 
      key: 'amount', 
      label: __('Amount'), 
      sortable: true,
      align: 'right',
      render: (value, row) => row.type === 'percent' ? `${value}%` : formatCurrency(value),
    },
    { 
      key: 'uses', 
      label: __('Uses'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'discount_amount', 
      label: __('Total Discount'), 
      sortable: true,
      align: 'right',
      render: (value) => formatCurrency(value),
    },
    { 
      key: 'revenue_generated', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatCurrency(value),
    },
    { 
      key: 'roi', 
      label: __('ROI'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}x`,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold">{__('Coupons Report')}</h1>
        <p className="text-sm text-muted-foreground">{__('Coupon usage and effectiveness')}</p>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title={__('Total Discount')}
          value={periodMetrics.total_discount}
          change={periodMetrics.change_percent}
          icon={Tag}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Coupons Used')}
          value={periodMetrics.coupons_used}
          change={periodMetrics.coupons_used_change}
          icon={ShoppingCart}
          format="number"
          period={period}
        />
        <StatCard
          title={__('Revenue with Coupons')}
          value={periodMetrics.revenue_with_coupons}
          change={periodMetrics.revenue_with_coupons_change}
          icon={DollarSign}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Avg Discount/Order')}
          value={periodMetrics.avg_discount_per_order}
          change={periodMetrics.avg_discount_per_order_change}
          icon={TrendingUp}
          format="money"
          period={period}
        />
      </div>

      <ChartCard
        title={__('Coupon Usage Over Time')}
        description={__('Daily coupon usage and discount amount')}
        dataPoints={chartData.length}
      >
        {chartData.length === 0 || chartData.every((d: any) => d.uses === 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 coupon usage data available')}</p>
              <p className="text-sm text-muted-foreground mt-1">
                {__('Coupon data will appear once customers use coupons')}
              </p>
            </div>
          </div>
        ) : (
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={chartData}>
            <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 
              yAxisId="left"
              className="text-xs" 
            />
            <YAxis 
              yAxisId="right"
              orientation="right"
              className="text-xs"
              tickFormatter={formatMoneyAxis}
            />
            <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">
                          {entry.dataKey === 'uses' ? entry.value : formatCurrency(entry.value)}
                        </span>
                      </div>
                    ))}
                  </div>
                );
              }}
            />
            <Legend />
            <Line
              yAxisId="left"
              type="monotone"
              dataKey="uses"
              name={__('Uses')}
              stroke="#3b82f6"
              strokeWidth={2}
            />
            <Line
              yAxisId="right"
              type="monotone"
              dataKey="discount"
              name={__('Discount Amount')}
              stroke="#10b981"
              strokeWidth={2}
            />
          </LineChart>
        </ResponsiveContainer>
        )}
      </ChartCard>

      <ChartCard
        title={__('Coupon Performance')}
        description={__('All active coupons with usage statistics')}
      >
        <DataTable
          data={filteredCoupons}
          columns={couponColumns}
        />
      </ChartCard>
    </div>
  );
}
