import React, { useState, useMemo } from 'react';
import { Package, TrendingUp, DollarSign, AlertTriangle, XCircle } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { formatMoney, getStoreCurrency } from '@/lib/currency';
import { useDashboardPeriod } from '@/hooks/useDashboardPeriod';
import { useProductsAnalytics } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DUMMY_PRODUCTS_DATA, ProductsData, TopProduct, ProductByCategory, StockAnalysisProduct } from './data/dummyProducts';

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

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

  // Filter sales data by period (stock data is global, not date-based)
  const periodMetrics = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return {
      items_sold: Math.round(data.overview.items_sold * factor),
      revenue: Math.round(data.overview.revenue * factor),
      change_percent: data.overview.change_percent,
    };
  }, [data.overview, period]);

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

  const filteredCategories = useMemo(() => {
    const factor = period === 'all' ? 1 : parseInt(period) / 30;
    return data.by_category.map((c: any) => ({
      ...c,
      items_sold: Math.round(c.items_sold * factor),
      revenue: Math.round(c.revenue * factor),
    }));
  }, [data.by_category, 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 products 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,
    });
  };

  // Table columns
  const productColumns: Column<TopProduct>[] = [
    { 
      key: 'image', 
      label: '', 
      render: (value) => <span className="text-2xl">{value}</span>,
    },
    { key: 'name', label: __('Product'), sortable: true },
    { key: 'sku', label: __('SKU'), sortable: true },
    { 
      key: 'items_sold', 
      label: __('Sold'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatCurrency(value),
    },
    { 
      key: 'stock', 
      label: __('Stock'), 
      sortable: true,
      align: 'right',
      render: (value, row) => (
        <span className={row.stock_status === 'lowstock' ? 'text-amber-600 font-medium' : ''}>
          {value}
        </span>
      ),
    },
    { 
      key: 'conversion_rate', 
      label: __('Conv. Rate'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}%`,
    },
  ];

  const categoryColumns: Column<ProductByCategory>[] = [
    { key: 'name', label: __('Category'), sortable: true },
    { 
      key: 'products_count', 
      label: __('Products'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'items_sold', 
      label: __('Items Sold'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'revenue', 
      label: __('Revenue'), 
      sortable: true,
      align: 'right',
      render: (value) => formatCurrency(value),
    },
    { 
      key: 'percentage', 
      label: __('% of Total'), 
      sortable: true,
      align: 'right',
      render: (value) => `${value.toFixed(1)}%`,
    },
  ];

  const stockColumns: Column<StockAnalysisProduct>[] = [
    { key: 'name', label: __('Product'), sortable: true },
    { key: 'sku', label: __('SKU'), sortable: true },
    { 
      key: 'stock', 
      label: __('Stock'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'threshold', 
      label: __('Threshold'), 
      sortable: true,
      align: 'right',
    },
    { 
      key: 'last_sale_date', 
      label: __('Last Sale'), 
      sortable: true,
      render: (value) => new Date(value).toLocaleDateString(),
    },
    { 
      key: 'days_since_sale', 
      label: __('Days Ago'), 
      sortable: true,
      align: 'right',
    },
  ];

  return (
    <div className="space-y-6 lg:p-6 pb-6">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold">{__('Products Performance')}</h1>
        <p className="text-sm text-muted-foreground">{__('Product sales and stock analysis')}</p>
      </div>

      {/* Metric Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title={__('Items Sold')}
          value={periodMetrics.items_sold}
          change={periodMetrics.change_percent}
          icon={Package}
          format="number"
          period={period}
        />
        <StatCard
          title={__('Revenue')}
          value={periodMetrics.revenue}
          change={periodMetrics.change_percent}
          icon={DollarSign}
          format="money"
          period={period}
        />
        <div className="rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm font-medium text-amber-900 dark:text-amber-100">{__('Low Stock Items')}</div>
            <AlertTriangle className="w-4 h-4 text-amber-600 dark:text-amber-500" />
          </div>
          <div className="space-y-1">
            <div className="text-2xl font-bold text-amber-900 dark:text-amber-100">{data.overview.low_stock_count}</div>
            <div className="text-xs text-amber-700 dark:text-amber-300">{__('Products below threshold')}</div>
          </div>
        </div>
        <div className="rounded-lg border border-red-200 bg-red-50 dark:bg-red-950/20 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm font-medium text-red-900 dark:text-red-100">{__('Out of Stock')}</div>
            <XCircle className="w-4 h-4 text-red-600 dark:text-red-500" />
          </div>
          <div className="space-y-1">
            <div className="text-2xl font-bold text-red-900 dark:text-red-100">{data.overview.out_of_stock_count}</div>
            <div className="text-xs text-red-700 dark:text-red-300">{__('Products unavailable')}</div>
          </div>
        </div>
      </div>

      {/* Top Products Table */}
      <ChartCard
        title={__('Top Products')}
        description={__('Best performing products by revenue')}
      >
        <DataTable
          data={filteredProducts}
          columns={productColumns}
        />
      </ChartCard>

      {/* Category Performance */}
      <ChartCard
        title={__('Performance by Category')}
        description={__('Revenue breakdown by product category')}
      >
        <DataTable
          data={filteredCategories}
          columns={categoryColumns}
        />
      </ChartCard>

      {/* Stock Analysis */}
      <Tabs defaultValue="low" className="space-y-4">
        <TabsList>
          <TabsTrigger value="low">
            {__('Low Stock')} ({data.stock_analysis.low_stock.length})
          </TabsTrigger>
          <TabsTrigger value="out">
            {__('Out of Stock')} ({data.stock_analysis.out_of_stock.length})
          </TabsTrigger>
          <TabsTrigger value="slow">
            {__('Slow Movers')} ({data.stock_analysis.slow_movers.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="low">
          <ChartCard
            title={__('Low Stock Products')}
            description={__('Products below minimum stock threshold')}
          >
            <DataTable
              data={data.stock_analysis.low_stock}
              columns={stockColumns}
              emptyMessage={__('No low stock items')}
            />
          </ChartCard>
        </TabsContent>

        <TabsContent value="out">
          <ChartCard
            title={__('Out of Stock Products')}
            description={__('Products currently unavailable')}
          >
            <DataTable
              data={data.stock_analysis.out_of_stock}
              columns={stockColumns}
              emptyMessage={__('No out of stock items')}
            />
          </ChartCard>
        </TabsContent>

        <TabsContent value="slow">
          <ChartCard
            title={__('Slow Moving Products')}
            description={__('Products with no recent sales')}
          >
            <DataTable
              data={data.stock_analysis.slow_movers}
              columns={stockColumns}
              emptyMessage={__('No slow movers')}
            />
          </ChartCard>
        </TabsContent>
      </Tabs>
    </div>
  );
}
