'use client';

import React, { useEffect, useState } from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { Line, Doughnut, Bar } from 'react-chartjs-2';
import { TrendingUp, PieChart, BarChart3 } from 'lucide-react';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

interface OrderItem {
  id: string;
  productName: string;
  quantity: number;
  lineTotal: number;
  unitPrice: number;
}

interface Order {
  id: string;
  orderNumber: string;
  totalAmount: number;
  status: string;
  paymentStatus: string;
  customerName: string;
  createdAt: string;
  items?: OrderItem[];
}

interface OverviewChartsProps {
  orders: Order[];
  timeRange: '24h' | '7d' | '30d' | 'all';
}

function useTheme() {
  const [theme, setTheme] = useState<'dark' | 'light'>('dark');

  useEffect(() => {
    const checkTheme = () => {
      const isLight = document.documentElement.classList.contains('light');
      setTheme(isLight ? 'light' : 'dark');
    };

    checkTheme();

    const observer = new MutationObserver(checkTheme);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class'],
    });

    return () => observer.disconnect();
  }, []);

  return theme;
}

export default function OverviewCharts({ orders, timeRange }: OverviewChartsProps) {
  const theme = useTheme();
  const [mounted, setMounted] = useState(false);
  const [trendMetric, setTrendMetric] = useState<'revenue' | 'orders'>('revenue');

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 min-h-[350px]">
        <div className="lg:col-span-8 glass-panel h-[350px] rounded-xl flex items-center justify-center">
          <div className="inline-block h-6 w-6 animate-spin rounded-full border-2 border-emerald-500 border-t-transparent"></div>
        </div>
        <div className="lg:col-span-4 glass-panel h-[350px] rounded-xl flex items-center justify-center">
          <div className="inline-block h-6 w-6 animate-spin rounded-full border-2 border-emerald-500 border-t-transparent"></div>
        </div>
      </div>
    );
  }

  // --- Common Chart Styling Options ---
  const isDark = theme === 'dark';
  const textColor = isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)';
  const gridColor = isDark ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)';
  const tooltipBg = isDark ? 'rgba(15, 23, 42, 0.95)' : 'rgba(255, 255, 255, 0.95)';
  const tooltipBorder = isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)';
  const tooltipTextColor = isDark ? '#ffffff' : '#0f172a';

  // --- Calculate Trend Data based on timeRange ---
  let trendLabels: string[] = [];
  let dailyRevenue: number[] = [];
  let dailyOrdersCount: number[] = [];

  const isOrderPaidAndProcessed = (o: Order) => {
    return o.paymentStatus === 'PAID' && (o.status === 'PROCESSING' || o.status === 'COMPLETED' || o.status === 'DELIVERED');
  };

  if (timeRange === '24h') {
    // Generate 12 two-hour intervals for the past 24 hours
    const now = new Date();
    const intervals = Array.from({ length: 12 }, (_, i) => {
      const d = new Date(now);
      d.setHours(now.getHours() - (11 - i) * 2);
      d.setMinutes(0, 0, 0);
      return d;
    });

    trendLabels = intervals.map((d) =>
      d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
    );

    dailyRevenue = intervals.map((binStart) => {
      const binEnd = new Date(binStart.getTime() + 2 * 60 * 60 * 1000);
      return orders
        .filter((o) => {
          const oDate = new Date(o.createdAt);
          return isOrderPaidAndProcessed(o) && oDate >= binStart && oDate < binEnd;
        })
        .reduce((sum, o) => sum + o.totalAmount, 0);
    });

    dailyOrdersCount = intervals.map((binStart) => {
      const binEnd = new Date(binStart.getTime() + 2 * 60 * 60 * 1000);
      return orders.filter((o) => {
        const oDate = new Date(o.createdAt);
        return oDate >= binStart && oDate < binEnd;
      }).length;
    });
  } else if (timeRange === '30d') {
    // Generate 30 daily intervals
    const last30Days = Array.from({ length: 30 }, (_, i) => {
      const d = new Date();
      d.setDate(d.getDate() - (29 - i));
      return d;
    });

    trendLabels = last30Days.map((d) =>
      d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
    );

    const matchDate = (date1: Date, date2Str: string) => {
      const d2 = new Date(date2Str);
      return (
        date1.getFullYear() === d2.getFullYear() &&
        date1.getMonth() === d2.getMonth() &&
        date1.getDate() === d2.getDate()
      );
    };

    dailyRevenue = last30Days.map((d) =>
      orders
        .filter((o) => isOrderPaidAndProcessed(o) && matchDate(d, o.createdAt))
        .reduce((sum, o) => sum + o.totalAmount, 0)
    );

    dailyOrdersCount = last30Days.map(
      (d) => orders.filter((o) => matchDate(d, o.createdAt)).length
    );
  } else if (timeRange === 'all') {
    // Generate monthly intervals for the past 6 months
    const last6Months = Array.from({ length: 6 }, (_, i) => {
      const d = new Date();
      d.setMonth(d.getMonth() - (5 - i));
      return d;
    });

    trendLabels = last6Months.map((d) =>
      d.toLocaleDateString('en-US', { month: 'short', year: '2-digit' })
    );

    const matchMonth = (date1: Date, date2Str: string) => {
      const d2 = new Date(date2Str);
      return date1.getFullYear() === d2.getFullYear() && date1.getMonth() === d2.getMonth();
    };

    dailyRevenue = last6Months.map((d) =>
      orders
        .filter((o) => isOrderPaidAndProcessed(o) && matchMonth(d, o.createdAt))
        .reduce((sum, o) => sum + o.totalAmount, 0)
    );

    dailyOrdersCount = last6Months.map(
      (d) => orders.filter((o) => matchMonth(d, o.createdAt)).length
    );
  } else {
    // Default to '7d'
    const last7Days = Array.from({ length: 7 }, (_, i) => {
      const d = new Date();
      d.setDate(d.getDate() - (6 - i));
      return d;
    });

    trendLabels = last7Days.map((d) =>
      d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
    );

    const matchDate = (date1: Date, date2Str: string) => {
      const d2 = new Date(date2Str);
      return (
        date1.getFullYear() === d2.getFullYear() &&
        date1.getMonth() === d2.getMonth() &&
        date1.getDate() === d2.getDate()
      );
    };

    dailyRevenue = last7Days.map((d) =>
      orders
        .filter((o) => isOrderPaidAndProcessed(o) && matchDate(d, o.createdAt))
        .reduce((sum, o) => sum + o.totalAmount, 0)
    );

    dailyOrdersCount = last7Days.map(
      (d) => orders.filter((o) => matchDate(d, o.createdAt)).length
    );
  }

  const dayLabels = trendLabels;

  const salesTrendData = {
    labels: dayLabels,
    datasets: [
      {
        fill: true,
        label: trendMetric === 'revenue' ? 'Revenue ($)' : 'Orders Count',
        data: trendMetric === 'revenue' ? dailyRevenue : dailyOrdersCount,
        borderColor: '#25d366', // Bright WhatsApp Green
        backgroundColor: (context: any) => {
          const chart = context.chart;
          const { ctx, chartArea } = chart;
          if (!chartArea) return 'transparent';
          const gradient = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
          gradient.addColorStop(0, 'rgba(37, 211, 102, 0.25)');
          gradient.addColorStop(1, 'rgba(37, 211, 102, 0.00)');
          return gradient;
        },
        tension: 0.4,
        borderWidth: 2.5,
        pointBackgroundColor: '#25d366',
        pointBorderColor: isDark ? '#0e1612' : '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 6,
        pointHoverBackgroundColor: '#25d366',
        pointHoverBorderColor: isDark ? '#0e1612' : '#ffffff',
        pointHoverBorderWidth: 3,
      },
    ],
  };

  const salesTrendOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: tooltipBg,
        titleColor: tooltipTextColor,
        bodyColor: tooltipTextColor,
        borderColor: tooltipBorder,
        borderWidth: 1,
        padding: 12,
        cornerRadius: 0,
        displayColors: false,
        callbacks: {
          label: (context: any) => {
            if (trendMetric === 'revenue') {
              return ` Revenue: $${context.raw.toLocaleString('en-US', { minimumFractionDigits: 2 })}`;
            }
            return ` Orders: ${context.raw}`;
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          display: false,
        },
        ticks: {
          color: textColor,
          font: {
            family: 'inherit',
            size: 10,
          },
        },
      },
      y: {
        grid: {
          color: gridColor,
        },
        ticks: {
          color: textColor,
          font: {
            family: 'inherit',
            size: 10,
          },
          callback: (value: any) => {
            if (trendMetric === 'revenue') {
              return `$${value}`;
            }
            return value;
          },
        },
      },
    },
  };

  // --- 2. Doughnut Chart: Order Status Data ---
  const orderStatuses = ['PENDING', 'PROCESSING', 'COMPLETED', 'CANCELLED'];
  const statusCounts = orderStatuses.map(
    (status) => orders.filter((o) => o.status === status).length
  );

  const doughnutData = {
    labels: ['Pending', 'Processing', 'Completed', 'Cancelled'],
    datasets: [
      {
        data: statusCounts,
        backgroundColor: [
          'rgba(245, 158, 11, 0.8)',  // Pending: Amber
          'rgba(18, 140, 126, 0.8)',  // Processing: WhatsApp Medium Green/Teal
          'rgba(37, 211, 102, 0.8)',  // Completed: WhatsApp Bright Green
          'rgba(239, 68, 68, 0.8)',   // Cancelled: Rose/Red
        ],
        borderColor: isDark ? 'rgba(32, 44, 51, 1)' : 'rgba(255, 255, 255, 1)',
        borderWidth: 2,
        hoverOffset: 6,
      },
    ],
  };

  const doughnutOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'bottom' as const,
        labels: {
          color: textColor,
          padding: 16,
          font: {
            family: 'inherit',
            size: 10,
          },
        },
      },
      tooltip: {
        backgroundColor: tooltipBg,
        titleColor: tooltipTextColor,
        bodyColor: tooltipTextColor,
        borderColor: tooltipBorder,
        borderWidth: 1,
        padding: 10,
        cornerRadius: 0,
      },
    },
    cutout: '65%',
  };

  // --- 3. Bar Chart: Top 5 Best-Selling Products ---
  const productSalesMap: { [name: string]: { quantity: number; revenue: number } } = {};
  orders.filter(isOrderPaidAndProcessed).forEach((order) => {
    if (order.items) {
      order.items.forEach((item) => {
        const name = item.productName || 'Unknown Product';
        if (!productSalesMap[name]) {
          productSalesMap[name] = { quantity: 0, revenue: 0 };
        }
        productSalesMap[name].quantity += item.quantity;
        productSalesMap[name].revenue += item.lineTotal;
      });
    }
  });

  const topProducts = Object.entries(productSalesMap)
    .map(([name, stats]) => ({ name, ...stats }))
    .sort((a, b) => b.revenue - a.revenue)
    .slice(0, 5);

  const barData = {
    labels: topProducts.map((p) =>
      p.name.length > 15 ? p.name.substring(0, 15) + '...' : p.name
    ),
    datasets: [
      {
        label: 'Revenue ($)',
        data: topProducts.map((p) => p.revenue),
        backgroundColor: (context: any) => {
          const chart = context.chart;
          const { ctx, chartArea } = chart;
          if (!chartArea) return 'rgba(18, 140, 126, 0.8)';
          const gradient = ctx.createLinearGradient(chartArea.left, 0, chartArea.right, 0);
          gradient.addColorStop(0, 'rgba(18, 140, 126, 0.4)');
          gradient.addColorStop(1, 'rgba(37, 211, 102, 0.85)');
          return gradient;
        },
        borderWidth: 0,
        borderRadius: 0,
        barThickness: 12,
      },
    ],
  };

  const barOptions = {
    indexAxis: 'y' as const,
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: tooltipBg,
        titleColor: tooltipTextColor,
        bodyColor: tooltipTextColor,
        borderColor: tooltipBorder,
        borderWidth: 1,
        padding: 10,
        cornerRadius: 0,
        callbacks: {
          label: (context: any) => {
            const index = context.dataIndex;
            const item = topProducts[index];
            return ` Revenue: $${item.revenue.toFixed(2)} (${item.quantity} sold)`;
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          color: gridColor,
        },
        ticks: {
          color: textColor,
          font: {
            family: 'inherit',
            size: 9,
          },
          callback: (value: any) => `$${value}`,
        },
      },
      y: {
        grid: {
          display: false,
        },
        ticks: {
          color: textColor,
          font: {
            family: 'inherit',
            size: 9,
          },
        },
      },
    },
  };

  const totalOrdersCount = orders.length;

  const subtitleText = 
    timeRange === '24h' ? 'Transaction activity for the last 24 hours.' :
    timeRange === '30d' ? 'Daily transaction activity for the last 30 days.' :
    timeRange === 'all' ? 'Monthly transaction activity over all time.' :
    'Daily transaction activity for the last 7 days.';

  return (
    <div className="space-y-6">
      {/* Top Row: Sales Trend + Order Status */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        {/* Sales Trend Line Chart */}
        <div className="lg:col-span-8 glass-panel p-6 rounded-xl flex flex-col justify-between">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
            <div className="flex items-center gap-2">
              <div className="p-2 bg-emerald-500/10 rounded-lg text-emerald-500">
                <TrendingUp className="h-4 w-4" />
              </div>
              <div>
                <h3 className="font-bold text-sm text-white font-sans tracking-tight">
                  Sales Trend Performance
                </h3>
                <p className="text-[10px] text-gray-400">
                  {subtitleText}
                </p>
              </div>
            </div>
            
            {/* Metric Selector Toggles */}
            <div className="flex border border-white/10 dark:border-white/5 rounded-lg overflow-hidden bg-black/10">
              <button
                onClick={() => setTrendMetric('revenue')}
                className={`px-3 py-1.5 text-[10px] font-bold tracking-wider uppercase transition-all border-0 cursor-pointer ${
                  trendMetric === 'revenue'
                    ? 'bg-primary text-[#0f0069]'
                    : 'text-gray-400 hover:text-white'
                }`}
              >
                Revenue ($)
              </button>
              <button
                onClick={() => setTrendMetric('orders')}
                className={`px-3 py-1.5 text-[10px] font-bold tracking-wider uppercase transition-all border-0 cursor-pointer ${
                  trendMetric === 'orders'
                    ? 'bg-primary text-[#0f0069]'
                    : 'text-gray-400 hover:text-white'
                }`}
              >
                Orders
              </button>
            </div>
          </div>

          <div className="h-64 w-full relative">
            <Line data={salesTrendData} options={salesTrendOptions} />
          </div>
        </div>

        {/* Order Status Doughnut Chart */}
        <div className="lg:col-span-4 glass-panel p-6 rounded-xl flex flex-col justify-between">
          <div className="flex items-center gap-2 mb-4">
            <div className="p-2 bg-teal-500/10 rounded-lg text-teal-400">
              <PieChart className="h-4 w-4" />
            </div>
            <div>
              <h3 className="font-bold text-sm text-white font-sans tracking-tight">
                Order Status Distribution
              </h3>
              <p className="text-[10px] text-gray-400">
                Fulfillment workflow breakdown ({totalOrdersCount} total).
              </p>
            </div>
          </div>

          {totalOrdersCount === 0 ? (
            <div className="h-64 flex items-center justify-center text-xs text-gray-500 font-sans">
              No orders recorded yet
            </div>
          ) : (
            <div className="h-64 w-full relative">
              <Doughnut data={doughnutData} options={doughnutOptions} />
            </div>
          )}
        </div>

      </div>

      {/* Bottom Row: Top Best Selling Products */}
      <div className="grid grid-cols-1 gap-6">
        
        {/* Top 5 Products Bar Chart */}
        <div className="glass-panel p-6 rounded-xl flex flex-col justify-between">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <div className="p-2 bg-emerald-500/10 rounded-lg text-emerald-400">
                <BarChart3 className="h-4 w-4" />
              </div>
              <div>
                <h3 className="font-bold text-sm text-white font-sans tracking-tight">
                  Top 5 Best-Selling Products
                </h3>
                <p className="text-[10px] text-gray-400">
                  Leaderboard ranked by total sales revenue.
                </p>
              </div>
            </div>
          </div>

          {topProducts.length === 0 ? (
            <div className="h-48 flex items-center justify-center text-xs text-gray-500 font-sans">
              No sales data available for products
            </div>
          ) : (
            <div className="h-48 w-full relative">
              <Bar data={barData} options={barOptions} />
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
