import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Download, Filter, Package, PackageCheck, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus';
import type { DateRange, ProductAnalyticsItem } from '../types';
import { exportToCSV, fetchProductAnalytics } from '../dataService';
import { endOfLocalDay, formatDateParam, parseLocalDateInput, rangeForDay, rangeForLastDays, rangeForPreviousDay, startOfLocalDay } from '../dateRanges';

type StockRisk = 'rupture' | 'critical' | 'attention' | 'monitor' | 'healthy' | 'no_sales';
type StockStatusFilter = 'all' | StockRisk;
type StockQuantityFilter = 'all' | 'zero' | 'positive' | 'low' | 'high';
type SalesFilter = 'all' | 'sold' | 'not_sold';
type CoverageFilter = 'all' | 'up_to_7' | 'up_to_14' | 'up_to_30' | 'over_30' | 'none';
type ProductSortOption = 'sold_desc' | 'sold_asc' | 'revenue_desc' | 'revenue_asc' | 'stock_asc' | 'stock_desc' | 'coverage_asc' | 'coverage_desc' | 'name_asc';

type ProductRow = ProductAnalyticsItem & {
  dailySales: number;
  daysOfCover: number | null;
  risk: StockRisk;
  riskLabel: string;
};

const riskStyles: Record<StockRisk, { label: string; className: string; dotClass: string }> = {
  rupture: {
    label: 'Sem estoque',
    className: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-300',
    dotClass: 'bg-zinc-400'
  },
  critical: {
    label: '0-7 dias',
    className: 'border-red-400/35 bg-red-400/10 text-red-300',
    dotClass: 'bg-red-400'
  },
  attention: {
    label: '8-14 dias',
    className: 'border-amber-400/35 bg-amber-400/10 text-amber-300',
    dotClass: 'bg-amber-400'
  },
  monitor: {
    label: '15-30 dias',
    className: 'border-sky-400/35 bg-sky-400/10 text-sky-300',
    dotClass: 'bg-sky-400'
  },
  healthy: {
    label: '>30 dias',
    className: 'border-emerald-400/35 bg-emerald-400/10 text-emerald-300',
    dotClass: 'bg-emerald-400'
  },
  no_sales: {
    label: 'Sem venda',
    className: 'border-dark-border bg-dark-input text-dark-muted',
    dotClass: 'bg-dark-muted'
  }
};

const stockStatusOptions: Array<{ value: StockStatusFilter; label: string }> = [
  { value: 'all', label: 'Todos' },
  { value: 'rupture', label: 'Sem estoque' },
  { value: 'critical', label: '0-7 dias' },
  { value: 'attention', label: '8-14 dias' },
  { value: 'monitor', label: '15-30 dias' },
  { value: 'healthy', label: '>30 dias' },
  { value: 'no_sales', label: 'Sem venda' }
];

const dateFilterPresets = [
  { value: 'today', label: 'Hoje', getRange: () => rangeForDay(new Date()) },
  { value: 'yesterday', label: 'Ontem', getRange: () => rangeForPreviousDay() },
  { value: '7d', label: 'Últimos 7 dias', getRange: () => rangeForLastDays(7) },
  { value: '30d', label: 'Últimos 30 dias', getRange: () => rangeForLastDays(30) },
  { value: 'month', label: 'Este mês', getRange: () => {
    const end = endOfLocalDay(new Date());
    return { start: startOfLocalDay(new Date(end.getFullYear(), end.getMonth(), 1)), end };
  } },
  { value: 'previous-month', label: 'Mês passado', getRange: () => {
    const today = new Date();
    return {
      start: startOfLocalDay(new Date(today.getFullYear(), today.getMonth() - 1, 1)),
      end: endOfLocalDay(new Date(today.getFullYear(), today.getMonth(), 0))
    };
  } },
  { value: '90d', label: 'Últimos 90 dias', getRange: () => rangeForLastDays(90) },
  { value: 'year', label: 'Este ano', getRange: () => {
    const end = endOfLocalDay(new Date());
    return { start: startOfLocalDay(new Date(end.getFullYear(), 0, 1)), end };
  } },
  { value: 'all', label: 'Todo o período', getRange: () => ({
    start: startOfLocalDay(new Date(2000, 0, 1)),
    end: endOfLocalDay(new Date())
  }) }
];

const filterSelectClassName = "w-full h-9 bg-dark-input border border-dark-border text-dark-text text-sm rounded-lg px-3 focus:outline-none focus:border-brand-primary transition-colors cursor-pointer";

const getRangeDays = (range: DateRange) => {
  const start = new Date(range.start);
  const end = new Date(range.end);
  start.setHours(0, 0, 0, 0);
  end.setHours(0, 0, 0, 0);
  return Math.max(1, Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1);
};

const classifyStockRisk = (stock: number, dailySales: number): StockRisk => {
  if (stock <= 0) return 'rupture';
  if (dailySales <= 0) return 'no_sales';

  const daysOfCover = stock / dailySales;
  if (daysOfCover <= 7) return 'critical';
  if (daysOfCover <= 14) return 'attention';
  if (daysOfCover <= 30) return 'monitor';
  return 'healthy';
};

const formatNumber = (value: number, maximumFractionDigits = 0) => (
  new Intl.NumberFormat('pt-BR', { maximumFractionDigits }).format(value)
);

const formatDays = (value: number | null) => {
  if (value === null) return '-';
  if (value > 999) return '999+ dias';
  return `${formatNumber(value, value < 10 ? 1 : 0)} dias`;
};

const ProductTableSkeleton = () => (
  <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm" aria-label="Carregando produtos">
    <div className="border-b border-zinc-100 p-4 dark:border-dark-border">
      <div className="grid grid-cols-[100px_1.5fr_120px_110px_100px_120px_120px_130px_110px] gap-6">
        {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(item => (
          <div key={`products-head-skeleton-${item}`} className="skeleton h-3" />
        ))}
      </div>
    </div>
    <div className="divide-y divide-zinc-100 dark:divide-dark-border">
      {[0, 1, 2, 3, 4, 5, 6, 7].map(row => (
        <div key={`products-row-skeleton-${row}`} className="grid grid-cols-[100px_1.5fr_120px_110px_100px_120px_120px_130px_110px] gap-6 px-6 py-4">
          <div className="skeleton h-4" />
          <div>
            <div className="skeleton h-4 w-4/5" />
            <div className="skeleton mt-2 h-3 w-32" />
          </div>
          <div className="skeleton h-6 rounded-full" />
          <div className="skeleton h-4" />
          <div className="skeleton h-4" />
          <div className="skeleton h-4" />
          <div className="skeleton h-4" />
          <div className="skeleton h-4" />
          <div className="skeleton h-7 rounded-lg" />
        </div>
      ))}
    </div>
    <div className="flex items-center justify-between border-t border-zinc-100 p-4 dark:border-dark-border">
      <div className="skeleton h-4 w-48" />
      <div className="skeleton h-8 w-56" />
    </div>
  </div>
);

const Products = () => {
  const { dateRange, setDateRange } = useOutletContext<{
    dateRange: DateRange,
    setDateRange: (range: DateRange) => void
  }>();
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<ProductSortOption>('sold_desc');
  const [stockStatusFilter, setStockStatusFilter] = useState<StockStatusFilter>('all');
  const [stockQuantityFilter, setStockQuantityFilter] = useState<StockQuantityFilter>('all');
  const [salesFilter, setSalesFilter] = useState<SalesFilter>('all');
  const [coverageFilter, setCoverageFilter] = useState<CoverageFilter>('all');
  const [isFilterMenuOpen, setIsFilterMenuOpen] = useState(false);
  const filterMenuRef = useRef<HTMLDivElement>(null);
  const [productAnalytics, setProductAnalytics] = useState<ProductAnalyticsItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  useEffect(() => {
    let isMounted = true;

    const loadProducts = async () => {
      setIsLoading(true);
      const products = await fetchProductAnalytics(dateRange);

      if (isMounted) {
        setProductAnalytics(products);
        setIsLoading(false);
      }
    };

    void loadProducts();

    return () => {
      isMounted = false;
    };
  }, [dateRange]);

  useEffect(() => {
    if (!isFilterMenuOpen) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (!filterMenuRef.current?.contains(event.target as Node)) {
        setIsFilterMenuOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isFilterMenuOpen]);

  const productsData = useMemo<ProductRow[]>(() => {
    const days = getRangeDays(dateRange);
    const normalizedSearch = searchTerm.trim().toLowerCase();
    const products = productAnalytics.map(product => {
      const dailySales = product.quantitySold / days;
      const risk = classifyStockRisk(product.stock, dailySales);
      const style = riskStyles[risk];

      return {
        ...product,
        dailySales,
        daysOfCover: dailySales > 0 ? product.stock / dailySales : null,
        risk,
        riskLabel: style.label
      };
    });

    const filteredProducts = normalizedSearch
      ? products.filter(product =>
        product.name.toLowerCase().includes(normalizedSearch) ||
        product.id.toLowerCase().includes(normalizedSearch)
      )
      : products;

    const detailedFilteredProducts = filteredProducts.filter(product => {
      const matchesStatus = stockStatusFilter === 'all' || product.risk === stockStatusFilter;
      const matchesStockQuantity =
        stockQuantityFilter === 'all' ||
        (stockQuantityFilter === 'zero' && product.stock <= 0) ||
        (stockQuantityFilter === 'positive' && product.stock > 0) ||
        (stockQuantityFilter === 'low' && product.stock > 0 && product.stock <= 10) ||
        (stockQuantityFilter === 'high' && product.stock > 100);
      const matchesSales =
        salesFilter === 'all' ||
        (salesFilter === 'sold' && product.quantitySold > 0) ||
        (salesFilter === 'not_sold' && product.quantitySold === 0);
      const matchesCoverage =
        coverageFilter === 'all' ||
        (coverageFilter === 'none' && product.daysOfCover === null) ||
        (coverageFilter === 'up_to_7' && product.daysOfCover !== null && product.daysOfCover <= 7) ||
        (coverageFilter === 'up_to_14' && product.daysOfCover !== null && product.daysOfCover <= 14) ||
        (coverageFilter === 'up_to_30' && product.daysOfCover !== null && product.daysOfCover <= 30) ||
        (coverageFilter === 'over_30' && product.daysOfCover !== null && product.daysOfCover > 30);

      return matchesStatus && matchesStockQuantity && matchesSales && matchesCoverage;
    });

    return detailedFilteredProducts.sort((a, b) => {
      switch (sortBy) {
        case 'sold_asc': return a.quantitySold - b.quantitySold;
        case 'revenue_desc': return b.revenue - a.revenue;
        case 'revenue_asc': return a.revenue - b.revenue;
        case 'stock_asc': return a.stock - b.stock;
        case 'stock_desc': return b.stock - a.stock;
        case 'coverage_asc': return (a.daysOfCover ?? Number.POSITIVE_INFINITY) - (b.daysOfCover ?? Number.POSITIVE_INFINITY);
        case 'coverage_desc': return (b.daysOfCover ?? -1) - (a.daysOfCover ?? -1);
        case 'name_asc': return a.name.localeCompare(b.name, 'pt-BR');
        case 'sold_desc':
        default:
          return b.quantitySold - a.quantitySold;
      }
    });
  }, [coverageFilter, dateRange, productAnalytics, salesFilter, searchTerm, sortBy, stockQuantityFilter, stockStatusFilter]);

  const activeFilterCount =
    (sortBy === 'sold_desc' ? 0 : 1) +
    (stockStatusFilter === 'all' ? 0 : 1) +
    (stockQuantityFilter === 'all' ? 0 : 1) +
    (salesFilter === 'all' ? 0 : 1) +
    (coverageFilter === 'all' ? 0 : 1);
  const hasActiveFilters = activeFilterCount > 0;

  const resetProductFilters = () => {
    setSortBy('sold_desc');
    setStockStatusFilter('all');
    setStockQuantityFilter('all');
    setSalesFilter('all');
    setCoverageFilter('all');
    setCurrentPage(1);
  };

  const datePresetValue = useMemo(() => {
    const currentStart = formatDateParam(dateRange.start);
    const currentEnd = formatDateParam(dateRange.end);
    const preset = dateFilterPresets.find(option => {
      const range = option.getRange();
      return formatDateParam(range.start) === currentStart && formatDateParam(range.end) === currentEnd;
    });

    return preset?.value || 'custom';
  }, [dateRange]);

  const updateDatePreset = (value: string) => {
    if (value === 'custom') return;

    const preset = dateFilterPresets.find(option => option.value === value);
    if (!preset) return;

    setDateRange(preset.getRange());
    setCurrentPage(1);
  };

  const updateDateStart = (value: string) => {
    const nextStart = parseLocalDateInput(value);
    if (!nextStart) return;

    const start = startOfLocalDay(nextStart);
    const end = dateRange.end < start ? endOfLocalDay(start) : dateRange.end;
    setDateRange({ start, end });
    setCurrentPage(1);
  };

  const updateDateEnd = (value: string) => {
    const nextEnd = parseLocalDateInput(value);
    if (!nextEnd) return;

    const end = endOfLocalDay(nextEnd);
    const start = dateRange.start > end ? startOfLocalDay(end) : dateRange.start;
    setDateRange({ start, end });
    setCurrentPage(1);
  };

  const totalPages = Math.ceil(productsData.length / itemsPerPage);
  const safeCurrentPage = Math.min(currentPage, totalPages || 1);
  const startIndex = (safeCurrentPage - 1) * itemsPerPage;
  const paginatedData = productsData.slice(startIndex, startIndex + itemsPerPage);
  const isRefreshing = isLoading && productAnalytics.length > 0;

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
  };

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 gap-4 2xl:grid-cols-[minmax(520px,1fr)_auto] 2xl:items-start">
        <div>
          <h1 className="text-2xl font-bold mb-2 text-zinc-900 dark:text-dark-text">Produtos</h1>
          <p className="text-zinc-500 dark:text-dark-muted font-medium">Performance de vendas, saldo e cobertura por produto.</p>
        </div>

        <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
          <div className="relative w-full sm:w-72">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-zinc-400 dark:text-dark-muted w-5 h-5" />
            <input
              type="text"
              placeholder="Buscar por nome ou ID..."
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full bg-dark-card border border-dark-border text-dark-text rounded-xl pl-10 pr-4 py-2.5 focus:outline-none focus:border-brand-primary hover:border-brand-primary transition-colors shadow-sm"
            />
          </div>

          <div ref={filterMenuRef} className="relative w-full sm:w-auto">
            <button
              type="button"
              onClick={() => setIsFilterMenuOpen(open => !open)}
              className={`flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-medium shadow-sm transition-colors sm:w-auto ${
                hasActiveFilters
                  ? 'cursor-pointer border-brand-primary bg-brand-primary/10 text-brand-primary'
                  : 'cursor-pointer border-dark-border bg-dark-card text-dark-text hover:border-brand-primary'
              }`}
            >
              <Filter className="h-4 w-4" />
              Filtros
              {hasActiveFilters && (
                <span className="rounded-full bg-brand-primary px-1.5 py-0.5 text-[10px] font-bold text-brand-contrast">
                  {activeFilterCount}
                </span>
              )}
            </button>

            {isFilterMenuOpen && (
              <div className="absolute right-0 top-full z-20 mt-2 w-[min(28rem,calc(100vw-2rem))] rounded-xl border border-dark-border bg-dark-card p-3 shadow-2xl">
                <div className="mb-3 flex items-center justify-between">
                  <h3 className="text-sm font-bold text-dark-text">Filtros</h3>
                  <button
                    type="button"
                    onClick={() => setIsFilterMenuOpen(false)}
                    className="cursor-pointer rounded-lg p-1 text-dark-muted transition-colors hover:bg-dark-input hover:text-dark-text"
                    aria-label="Fechar filtros"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>

                <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Período
                    <select
                      value={datePresetValue}
                      onChange={(event) => updateDatePreset(event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="custom">Personalizado</option>
                      {dateFilterPresets.map(preset => (
                        <option key={preset.value} value={preset.value}>{preset.label}</option>
                      ))}
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Ordenação
                    <select
                      value={sortBy}
                      onChange={(event) => {
                        setSortBy(event.target.value as ProductSortOption);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="sold_desc">Mais vendidos</option>
                      <option value="sold_asc">Menos vendidos</option>
                      <option value="revenue_desc">Maior receita</option>
                      <option value="revenue_asc">Menor receita</option>
                      <option value="stock_asc">Menor estoque</option>
                      <option value="stock_desc">Maior estoque</option>
                      <option value="coverage_asc">Menor cobertura</option>
                      <option value="coverage_desc">Maior cobertura</option>
                      <option value="name_asc">Nome A-Z</option>
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    De
                    <input
                      type="date"
                      value={formatDateParam(dateRange.start)}
                      onChange={(event) => updateDateStart(event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    />
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Até
                    <input
                      type="date"
                      value={formatDateParam(dateRange.end)}
                      onChange={(event) => updateDateEnd(event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    />
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Faixa de cobertura
                    <select
                      value={stockStatusFilter}
                      onChange={(event) => {
                        setStockStatusFilter(event.target.value as StockStatusFilter);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      {stockStatusOptions.map(option => (
                        <option key={option.value} value={option.value}>{option.label}</option>
                      ))}
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Estoque
                    <select
                      value={stockQuantityFilter}
                      onChange={(event) => {
                        setStockQuantityFilter(event.target.value as StockQuantityFilter);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="all">Todos</option>
                      <option value="zero">Zerado</option>
                      <option value="positive">Com estoque</option>
                      <option value="low">Baixo: 1 a 10 un.</option>
                      <option value="high">Alto: acima de 100 un.</option>
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Vendas
                    <select
                      value={salesFilter}
                      onChange={(event) => {
                        setSalesFilter(event.target.value as SalesFilter);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="all">Todos</option>
                      <option value="sold">Vendeu no período</option>
                      <option value="not_sold">Não vendeu no período</option>
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Cobertura estimada
                    <select
                      value={coverageFilter}
                      onChange={(event) => {
                        setCoverageFilter(event.target.value as CoverageFilter);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="all">Todos</option>
                      <option value="up_to_7">0-7 dias</option>
                      <option value="up_to_14">8-14 dias</option>
                      <option value="up_to_30">15-30 dias</option>
                      <option value="over_30">&gt;30 dias</option>
                      <option value="none">Sem venda</option>
                    </select>
                  </label>
                </div>

                <div className="mt-3 flex items-center justify-between border-t border-dark-border pt-3">
                  <button
                    type="button"
                    onClick={resetProductFilters}
                    disabled={!hasActiveFilters}
                    className="cursor-pointer text-sm font-bold text-dark-muted transition-colors hover:text-dark-text disabled:cursor-not-allowed disabled:opacity-40"
                  >
                    Limpar
                  </button>
                  <button
                    type="button"
                    onClick={() => setIsFilterMenuOpen(false)}
                    className="cursor-pointer rounded-xl bg-brand-primary px-4 py-2 text-sm font-bold text-brand-contrast transition-opacity hover:opacity-90"
                  >
                    Aplicar
                  </button>
                </div>
              </div>
            )}
          </div>

          <button
            onClick={() => {
              const exportData = productsData.map(product => ({
                'ID Produto': product.id,
                'Descrição': product.name,
                'Faixa de Cobertura': product.riskLabel,
                'Preço Atual (R$)': product.lastPrice.toFixed(2).replace('.', ','),
                'Total Vendido (un.)': product.quantitySold,
                'Estoque': product.stock,
                'Média Diária': product.dailySales.toFixed(2).replace('.', ','),
                'Cobertura': product.daysOfCover === null ? '' : product.daysOfCover.toFixed(1).replace('.', ','),
                'Receita Gerada (R$)': product.revenue.toFixed(2).replace('.', ',')
              }));
              exportToCSV(exportData, `produtos_${new Date().toISOString().split('T')[0]}.csv`);
            }}
            className="flex items-center justify-center gap-2 bg-dark-card border border-dark-border px-4 py-2.5 rounded-xl shadow-sm hover:border-brand-primary transition-colors text-sm font-medium text-dark-text cursor-pointer"
            title="Exportar para CSV"
          >
            <Download size={16} className="text-brand-primary" />
            <span className="hidden sm:inline">Exportar</span>
          </button>
        </div>
      </div>

      <RefreshStatus isRefreshing={isRefreshing} />

      {isLoading && productAnalytics.length === 0 ? (
        <ProductTableSkeleton />
      ) : (
        <div className={`bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}>
          <div className="overflow-x-auto">
            <table className="w-full min-w-[1320px] table-fixed text-left text-sm">
              <colgroup>
                <col className="w-[120px]" />
                <col className="w-[390px]" />
                <col className="w-[170px]" />
                <col className="w-[130px]" />
                <col className="w-[120px]" />
                <col className="w-[130px]" />
                <col className="w-[130px]" />
                <col className="w-[140px]" />
                <col className="w-[110px]" />
              </colgroup>
              <thead className="bg-zinc-50 dark:bg-dark-header border-b border-zinc-100 dark:border-dark-border text-zinc-500 dark:text-dark-muted">
                <tr>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">ID Produto</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Descrição</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Faixa de cobertura</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Total Vendido</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Estoque</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Média Diária</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Cobertura estimada</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Receita Gerada</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px] text-right">Ações</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
                {paginatedData.map((product) => {
                  const style = riskStyles[product.risk];

                  return (
                    <tr key={product.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors group">
                      <td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">#{product.id}</td>
                      <td className="max-w-0 px-6 py-2.5">
                        <div className="truncate font-semibold text-zinc-900 dark:text-dark-text" title={product.name}>{product.name}</div>
                        <div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">Preço Atual: {formatCurrency(product.lastPrice)}</div>
                      </td>
                      <td className="px-6 py-2.5">
                        <span className={`inline-flex items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-xs font-bold ${style.className}`}>
                          <span className={`h-2 w-2 rounded-full ${style.dotClass}`} />
                          {style.label}
                        </span>
                      </td>
                      <td className="px-6 py-2.5 whitespace-nowrap">
                        <div className="flex items-center gap-2">
                          <Package className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
                          <span className="font-bold text-zinc-900 dark:text-dark-text">{formatNumber(product.quantitySold)} un.</span>
                        </div>
                      </td>
                      <td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatNumber(product.stock)} un.</td>
                      <td className="px-6 py-2.5 text-zinc-500 dark:text-dark-muted whitespace-nowrap">{formatNumber(product.dailySales, 2)} un./dia</td>
                      <td className="px-6 py-2.5 whitespace-nowrap">
                        <span className="inline-flex items-center gap-1.5 font-bold text-zinc-900 dark:text-dark-text">
                          <TrendingDown className="h-3.5 w-3.5 text-zinc-400 dark:text-dark-muted" />
                          {formatDays(product.daysOfCover)}
                        </span>
                      </td>
                      <td className="px-6 py-2.5 text-brand-primary font-bold whitespace-nowrap">{formatCurrency(product.revenue)}</td>
                      <td className="px-6 py-2.5 text-right">
                        <Link
                          to={`/products/${product.id}`}
                          className="inline-flex items-center text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer"
                        >
                          <TrendingUp className="w-3.5 h-3.5 mr-1.5" />
                          Ver Gráfico
                        </Link>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {!productsData.length && (
            <div className="px-6 py-12 text-center">
              <PackageCheck className="mx-auto h-10 w-10 text-dark-muted" />
              <p className="mt-4 text-sm font-bold text-dark-text">Nenhum produto encontrado.</p>
              <p className="mt-1 text-sm text-dark-muted">Ajuste a busca ou o período selecionado.</p>
            </div>
          )}

          <PaginationControls
            totalItems={productsData.length}
            currentPage={safeCurrentPage}
            totalPages={totalPages}
            pageSize={itemsPerPage}
            pageSizeOptions={[10, 20, 50, 100]}
            itemLabel="produtos"
            pageSizeLabel="itens por página"
            startIndex={startIndex}
            endIndex={Math.min(startIndex + itemsPerPage, productsData.length)}
            onPageChange={setCurrentPage}
            onPageSizeChange={(pageSize) => {
              setItemsPerPage(pageSize);
              setCurrentPage(1);
            }}
          />
        </div>
      )}
    </div>
  );
};

export default Products;
