import React, { useState, useMemo, useRef } from 'react';
import { BarChart, Bar, LineChart, Line, AreaChart, Area, ComposedChart, PieChart, Pie, Cell, Label, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { ShoppingCart, TrendingUp, Package, XCircle, DollarSign, CheckCircle, Clock } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { formatMoney, getStoreCurrency } from '@/lib/currency';
import { useDashboardPeriod } from '@/hooks/useDashboardPeriod';
import { useOrdersAnalytics } 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_ORDERS_DATA, OrdersData } from './data/dummyOrders';

export default function OrdersAnalytics() {
  const { period } = useDashboardPeriod();
  const store = getStoreCurrency();
  const [hoverIndex, setHoverIndex] = useState<number | undefined>(undefined);
  const chartRef = useRef<any>(null);

  // Fetch real data or use dummy data based on toggle
  const { data, isLoading, error, refetch } = useOrdersAnalytics(DUMMY_ORDERS_DATA);
  
  // Auto-select first status (completed) on load
  const [activeStatus, setActiveStatus] = useState(data.by_status[0]?.status_label || 'All');

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

  // Calculate period metrics
  const periodMetrics = useMemo(() => {
    if (period === 'all') {
      const totalOrders = data.chart_data.reduce((sum: number, d: any) => sum + d.completed + d.processing + d.pending + d.cancelled, 0);
      const completed = data.chart_data.reduce((sum: number, d: any) => sum + d.completed, 0);
      const cancelled = data.chart_data.reduce((sum: number, d: any) => sum + d.cancelled, 0);
      
      return {
        total_orders: totalOrders,
        avg_order_value: data.overview.avg_order_value,
        fulfillment_rate: totalOrders > 0 ? (completed / totalOrders) * 100 : 0,
        cancellation_rate: totalOrders > 0 ? (cancelled / totalOrders) * 100 : 0,
        avg_processing_time: data.overview.avg_processing_time,
        change_percent: undefined,
      };
    }
    
    const periodData = data.chart_data.slice(-parseInt(period));
    const previousData = data.chart_data.slice(-parseInt(period) * 2, -parseInt(period));
    
    const totalOrders = periodData.reduce((sum: number, d: any) => sum + d.completed + d.processing + d.pending + d.cancelled, 0);
    const completed = periodData.reduce((sum: number, d: any) => sum + d.completed, 0);
    const cancelled = periodData.reduce((sum: number, d: any) => sum + d.cancelled, 0);
    
    const prevTotalOrders = previousData.reduce((sum: number, d: any) => sum + d.completed + d.processing + d.pending + d.cancelled, 0);
    const prevCompleted = previousData.reduce((sum: number, d: any) => sum + d.completed, 0);
    const prevCancelled = previousData.reduce((sum: number, d: any) => sum + d.cancelled, 0);
    
    const factor = parseInt(period) / 30;
    const avgOrderValue = Math.round(data.overview.avg_order_value * factor);
    const prevAvgOrderValue = Math.round(data.overview.avg_order_value * factor * 0.9); // Simulate previous
    
    const fulfillmentRate = totalOrders > 0 ? (completed / totalOrders) * 100 : 0;
    const prevFulfillmentRate = prevTotalOrders > 0 ? (prevCompleted / prevTotalOrders) * 100 : 0;
    
    const cancellationRate = totalOrders > 0 ? (cancelled / totalOrders) * 100 : 0;
    const prevCancellationRate = prevTotalOrders > 0 ? (prevCancelled / prevTotalOrders) * 100 : 0;
    
    return {
      total_orders: totalOrders,
      avg_order_value: avgOrderValue,
      fulfillment_rate: fulfillmentRate,
      cancellation_rate: cancellationRate,
      avg_processing_time: data.overview.avg_processing_time,
      change_percent: prevTotalOrders > 0 ? ((totalOrders - prevTotalOrders) / prevTotalOrders) * 100 : 0,
      avg_order_value_change: prevAvgOrderValue > 0 ? ((avgOrderValue - prevAvgOrderValue) / prevAvgOrderValue) * 100 : 0,
      fulfillment_rate_change: prevFulfillmentRate > 0 ? ((fulfillmentRate - prevFulfillmentRate) / prevFulfillmentRate) * 100 : 0,
      cancellation_rate_change: prevCancellationRate > 0 ? ((cancellationRate - prevCancellationRate) / prevCancellationRate) * 100 : 0,
    };
  }, [data.chart_data, period, data.overview]);

  // Filter day of week and hour data by period
  const filteredByDay = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_day_of_week.map((d: any) => ({
      ...d,
      orders: Math.round(d.orders * factor),
    }));
  }, [data.by_day_of_week, period]);

  const filteredByHour = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_hour.map((h: any) => ({
      ...h,
      orders: Math.round(h.orders * factor),
    }));
  }, [data.by_hour, period]);

  // Find active pie index
  const activePieIndex = useMemo(
    () => data.by_status.findIndex((item: any) => item.status_label === activeStatus),
    [activeStatus, data.by_status]
  );

  // Pie chart handlers
  const onPieEnter = (_: any, index: number) => {
    setHoverIndex(index);
  };

  const onPieLeave = () => {
    setHoverIndex(undefined);
  };

  const handleChartMouseLeave = () => {
    setHoverIndex(undefined);
  };

  const handleChartMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    (document.activeElement as HTMLElement)?.blur();
  };

  // 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 orders analytics')}
        message={getPageLoadErrorMessage(error)}
        onRetry={() => refetch()}
      />
    );
  }

  // Format currency
  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,
    });
  };

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

      {/* Metric Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title={__('Total Orders')}
          value={periodMetrics.total_orders}
          change={periodMetrics.change_percent}
          icon={ShoppingCart}
          format="number"
          period={period}
        />
        <StatCard
          title={__('Avg Order Value')}
          value={periodMetrics.avg_order_value}
          change={periodMetrics.avg_order_value_change}
          icon={DollarSign}
          format="money"
          period={period}
        />
        <StatCard
          title={__('Fulfillment Rate')}
          value={periodMetrics.fulfillment_rate}
          change={periodMetrics.fulfillment_rate_change}
          icon={CheckCircle}
          format="percent"
          period={period}
        />
        <StatCard
          title={__('Cancellation Rate')}
          value={periodMetrics.cancellation_rate}
          change={periodMetrics.cancellation_rate_change}
          icon={XCircle}
          format="percent"
          period={period}
        />
      </div>

      {/* Orders Timeline Chart */}
      <ChartCard
        title={__('Orders Over Time')}
        description={__('Daily order count and status breakdown')}
        dataPoints={chartData.length}
      >
        {chartData.length === 0 || chartData.every((d: any) => d.orders === 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 orders data available')}</p>
              <p className="text-sm text-muted-foreground mt-1">
                {__('Order data will appear once you have orders')}
              </p>
            </div>
          </div>
        ) : (
          <ResponsiveContainer width="100%" height={300}>
            <ComposedChart data={chartData}>
            <defs>
              <linearGradient id="totalOrdersGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                <stop offset="95%" stopColor="#3b82f6" stopOpacity={0.05}/>
              </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" />
            <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.value}</span>
                      </div>
                    ))}
                  </div>
                );
              }}
            />
            <Legend />
            {/* Total Orders as Area (background) */}
            <Area
              type="monotone"
              dataKey="orders"
              name={__('Total Orders')}
              stroke="#3b82f6"
              strokeWidth={2}
              fill="url(#totalOrdersGradient)"
            />
            {/* Individual statuses as Lines */}
            <Line
              type="monotone"
              dataKey="completed"
              name={__('Completed')}
              stroke="#10b981"
              strokeWidth={2}
              dot={{ r: 3 }}
            />
            <Line
              type="monotone"
              dataKey="processing"
              name={__('Processing')}
              stroke="#60a5fa"
              strokeWidth={2}
              dot={{ r: 3 }}
            />
            <Line
              type="monotone"
              dataKey="pending"
              name={__('Pending')}
              stroke="#f59e0b"
              strokeWidth={2}
              dot={{ r: 3 }}
            />
            <Line
              type="monotone"
              dataKey="cancelled"
              name={__('Cancelled')}
              stroke="#ef4444"
              strokeWidth={2}
              dot={{ r: 3 }}
            />
          </ComposedChart>
        </ResponsiveContainer>
        )}
      </ChartCard>

      {/* Two Column Layout */}
      <div className="grid gap-6 md:grid-cols-2">
        {/* Order Status Breakdown - Interactive Pie Chart */}
        <div 
          className="rounded-lg border bg-card p-6"
          onMouseDown={handleChartMouseDown}
        >
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-semibold">{__('Order Status Distribution')}</h3>
              <p className="text-sm text-muted-foreground">{__('Breakdown by order status')}</p>
            </div>
            <Select value={activeStatus} onValueChange={setActiveStatus}>
              <SelectTrigger className="w-[160px] h-8">
                <SelectValue />
              </SelectTrigger>
              <SelectContent align="end">
                {data.by_status.map((status: any) => (
                  <SelectItem key={status.status} value={status.status_label}>
                    <span className="flex items-center gap-2 text-xs">
                      <span className="flex h-3 w-3 shrink-0 rounded" style={{ backgroundColor: status.color }} />
                      {status.status_label}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <ResponsiveContainer width="100%" height={280}>
            <PieChart 
              ref={chartRef}
              onMouseLeave={handleChartMouseLeave}
            >
              <Pie
                data={data.by_status as any}
                dataKey="count"
                nameKey="status_label"
                cx="50%"
                cy="50%"
                innerRadius={70}
                outerRadius={110}
                strokeWidth={5}
                onMouseEnter={onPieEnter}
                onMouseLeave={onPieLeave}
                isAnimationActive={false}
              >
                {data.by_status.map((entry: any, index: number) => {
                  const isActive = index === (hoverIndex !== undefined ? hoverIndex : activePieIndex);
                  return (
                    <Cell 
                      key={`cell-${index}`} 
                      fill={entry.color}
                      stroke={isActive ? entry.color : undefined}
                      strokeWidth={isActive ? 8 : 5}
                      opacity={isActive ? 1 : 0.7}
                    />
                  );
                })}
                
                <Label
                  content={({ viewBox }) => {
                    if (viewBox && 'cx' in viewBox && 'cy' in viewBox) {
                      const displayIndex = hoverIndex !== undefined ? hoverIndex : activePieIndex;
                      const selectedData = data.by_status[displayIndex];
                      return (
                        <text
                          x={viewBox.cx}
                          y={viewBox.cy}
                          textAnchor="middle"
                          dominantBaseline="middle"
                        >
                          <tspan
                            x={viewBox.cx}
                            y={viewBox.cy}
                            className="fill-foreground text-3xl font-bold"
                          >
                            {selectedData?.count.toLocaleString()}
                          </tspan>
                          <tspan
                            x={viewBox.cx}
                            y={(viewBox.cy || 0) + 24}
                            className="fill-muted-foreground text-sm"
                          >
                            {selectedData?.status_label}
                          </tspan>
                        </text>
                      );
                    }
                    return null;
                  }}
                />
              </Pie>
            </PieChart>
          </ResponsiveContainer>
        </div>

        {/* Orders by Day of Week */}
        <ChartCard
          title={__('Orders by Day of Week')}
          description={__('Which days are busiest')}
        >
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={filteredByDay}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="day" className="text-xs" />
              <YAxis className="text-xs" />
              <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-1">{payload[0].payload.day}</p>
                      <p className="text-sm">
                        {__('Orders')}: <span className="font-medium">{payload[0].value}</span>
                      </p>
                    </div>
                  );
                }}
              />
              <Bar dataKey="orders" fill="#3b82f6" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>
      </div>

      {/* Orders by Hour Heatmap */}
      <ChartCard
        title={__('Orders by Hour of Day')}
        description={__('Peak ordering times throughout the day')}
      >
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={filteredByHour}>
            <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
            <XAxis 
              dataKey="hour" 
              className="text-xs"
              tickFormatter={(value) => `${value}:00`}
            />
            <YAxis className="text-xs" />
            <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-1">
                      {payload[0].payload.hour}:00 - {payload[0].payload.hour + 1}:00
                    </p>
                    <p className="text-sm">
                      {__('Orders')}: <span className="font-medium">{payload[0].value}</span>
                    </p>
                  </div>
                );
              }}
            />
            <Bar 
              dataKey="orders" 
              fill="#10b981" 
              radius={[4, 4, 0, 0]}
            />
          </BarChart>
        </ResponsiveContainer>
      </ChartCard>

      {/* Additional Metrics */}
      <div className="grid gap-4 md:grid-cols-2">
        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3 mb-4">
            <Clock className="w-5 h-5 text-muted-foreground" />
            <h3 className="font-semibold">{__('Average Processing Time')}</h3>
          </div>
          <p className="text-3xl font-bold">{periodMetrics.avg_processing_time}</p>
          <p className="text-sm text-muted-foreground mt-2">
            {__('Time from order placement to completion')}
          </p>
        </div>

        <div className="rounded-lg border bg-card p-6">
          <div className="flex items-center gap-3 mb-4">
            <TrendingUp className="w-5 h-5 text-muted-foreground" />
            <h3 className="font-semibold">{__('Performance Summary')}</h3>
          </div>
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{__('Completed')}:</span>
              <span className="font-medium">{data.by_status.find((s: any) => s.status === 'completed')?.count || 0}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{__('Processing')}:</span>
              <span className="font-medium">{data.by_status.find((s: any) => s.status === 'processing')?.count || 0}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{__('Pending')}:</span>
              <span className="font-medium">{data.by_status.find((s: any) => s.status === 'pending')?.count || 0}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
