import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext, useSearchParams } from 'react-router-dom';
import { AlertTriangle, ArrowLeft, CheckCircle2, Download, Eye, Package, Pencil, Search, TrendingUp } from 'lucide-react';
import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus';
import { buildSkuEditPath } from '../catalogLinks';
import { buildOpenProductionByProductId } from '../analytics/cutting';
import type { DateRange, ProductAnalyticsItem, ProductionOrderItem } from '../types';
import { exportToCSV, fetchProductAnalytics, fetchProductionOrders } from '../dataService';
import { encodeProductGroupKey, parseProductName, sortProductSizes } from '../productParsing';
import { formatColorLabel } from '../displayFormatters';
import { getPlanningStock } from '../planningStock';

type ReplenishmentStatus = 'need' | 'covered' | 'no_sales' | 'no_stock';
type ReplenishmentFilter = 'all' | ReplenishmentStatus;
type ReplenishmentSort = 'need_desc' | 'need_asc' | 'demand_desc' | 'stock_asc' | 'coverage_asc' | 'sold_desc' | 'name_asc';
type ReplenishmentView = 'sku' | 'group';

type ReplenishmentRow = ProductAnalyticsItem & {
  dailySales: number;
  projectedDemand: number;
  suggestedQuantity: number;
  openProductionQuantity: number;
  availableQuantity: number;
  daysOfCover: number | null;
  status: ReplenishmentStatus;
  statusLabel: string;
  baseName: string;
  color: string;
  size: string;
  productIds: string[];
  productCount: number;
  sizes: string[];
};

const statusStyles: Record<ReplenishmentStatus, { label: string; className: string; dotClass: string }> = {
  need: {
    label: 'Repor',
    className: 'border-red-400/35 bg-red-400/10 text-red-300',
    dotClass: 'bg-red-400'
  },
  no_stock: {
    label: 'Sem estoque',
    className: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-300',
    dotClass: 'bg-zinc-400'
  },
  covered: {
    label: 'Coberto',
    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 filterOptions: Array<{ value: ReplenishmentFilter; label: string }> = [
  { value: 'need', label: 'Com necessidade' },
  { value: 'all', label: 'Todos' },
  { value: 'no_stock', label: 'Sem estoque' },
  { value: 'covered', label: 'Cobertos' },
  { value: 'no_sales', label: 'Sem venda' }
];

const coverageTargetOptions = [7, 15, 30, 60];

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 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 allProductionOrdersRange = {
  start: new Date(2000, 0, 1),
  end: new Date(2100, 11, 31)
};

const ReplenishmentSkeleton = () => (
  <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 necessidade de reposicao">
    <div className="border-b border-zinc-100 p-4 dark:border-dark-border">
      <div className="grid grid-cols-[120px_1.5fr_120px_130px_120px_130px_130px_110px] gap-6">
        {[0, 1, 2, 3, 4, 5, 6, 7].map(item => (
          <div key={`replenishment-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={`replenishment-row-skeleton-${row}`} className="grid grid-cols-[120px_1.5fr_120px_130px_120px_130px_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-7 rounded-lg" />
        </div>
      ))}
    </div>
  </div>
);

const Replenishment = () => {
  const { dateRange, setDateRange } = useOutletContext<{
    dateRange: DateRange,
    setDateRange: (range: DateRange) => void
  }>();
  const [searchParams] = useSearchParams();
  const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
  const [productionOrders, setProductionOrders] = useState<ProductionOrderItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<ReplenishmentFilter>(() => {
    const filter = searchParams.get('status') as ReplenishmentFilter | null;
    return filter && filterOptions.some(option => option.value === filter) ? filter : 'need';
  });
  const [sortBy, setSortBy] = useState<ReplenishmentSort>('need_desc');
  const [viewMode, setViewMode] = useState<ReplenishmentView>(() => searchParams.get('view') === 'group' ? 'group' : 'sku');
  const [targetCoverageDays, setTargetCoverageDays] = useState(30);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

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

    const loadProducts = async () => {
      setIsLoading(true);
      const [productData, productionOrderData] = await Promise.all([
        fetchProductAnalytics(dateRange),
        fetchProductionOrders(allProductionOrdersRange)
      ]);

      if (isMounted) {
        setProducts(productData);
        setProductionOrders(productionOrderData.orders);
        setIsLoading(false);
      }
    };

    void loadProducts();

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

  const openProductionByProductId = useMemo(
    () => buildOpenProductionByProductId(products, productionOrders),
    [products, productionOrders]
  );

  const allRows = useMemo<ReplenishmentRow[]>(() => {
    const rangeDays = getRangeDays(dateRange);

    return products.map(product => {
      const dailySales = product.quantitySold / rangeDays;
      const projectedDemand = dailySales * targetCoverageDays;
      const openProductionQuantity = openProductionByProductId[product.id] || 0;
      const availableQuantity = getPlanningStock(product.stock) + openProductionQuantity;
      const rawNeed = projectedDemand - availableQuantity;
      const suggestedQuantity = Math.max(0, Math.ceil(rawNeed));
      const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null;
      const status: ReplenishmentStatus = availableQuantity <= 0
          ? 'no_stock'
          : dailySales <= 0
            ? 'no_sales'
            : suggestedQuantity > 0
              ? 'need'
              : 'covered';

      const metadata = parseProductName(product.name);

      return {
        ...product,
        dailySales,
        projectedDemand,
        suggestedQuantity,
        openProductionQuantity,
        availableQuantity,
        daysOfCover,
        status,
        statusLabel: statusStyles[status].label,
        baseName: metadata.baseName,
        color: metadata.color,
        size: metadata.size,
        productIds: [product.id],
        productCount: 1,
        sizes: metadata.size ? [metadata.size] : []
      };
    });
  }, [dateRange, openProductionByProductId, products, targetCoverageDays]);

  const groupedRows = useMemo<ReplenishmentRow[]>(() => {
    const groups = new Map<string, ReplenishmentRow[]>();

    allRows.forEach(row => {
      const key = `${row.baseName.toLowerCase()}::${row.color.toLowerCase()}`;
      const group = groups.get(key) || [];
      group.push(row);
      groups.set(key, group);
    });

    return Array.from(groups.values()).map(group => {
      const first = group[0];
      const quantitySold = group.reduce((total, row) => total + row.quantitySold, 0);
      const revenue = group.reduce((total, row) => total + row.revenue, 0);
      const stock = group.reduce((total, row) => total + row.stock, 0);
      const openProductionQuantity = group.reduce((total, row) => total + row.openProductionQuantity, 0);
      const availableQuantity = group.reduce((total, row) => total + row.availableQuantity, 0);
      const dailySales = group.reduce((total, row) => total + row.dailySales, 0);
      const projectedDemand = group.reduce((total, row) => total + row.projectedDemand, 0);
      const suggestedQuantity = group.reduce((total, row) => total + row.suggestedQuantity, 0);
      const orderLineCount = group.reduce((total, row) => total + row.orderLineCount, 0);
      const daysOfCover = dailySales > 0 ? availableQuantity / dailySales : null;
      const status: ReplenishmentStatus = availableQuantity <= 0
        ? 'no_stock'
        : dailySales <= 0
          ? 'no_sales'
          : suggestedQuantity > 0
            ? 'need'
            : 'covered';
      const sizes = sortProductSizes(Array.from(new Set(group.flatMap(row => row.sizes))));
      const productIds = group.map(row => row.id);
      const name = first.color ? `${first.baseName} · ${formatColorLabel(first.color)}` : first.baseName;

      return {
        ...first,
        id: productIds[0],
        name,
        quantitySold,
        revenue,
        stock,
        openProductionQuantity,
        availableQuantity,
        orderLineCount,
        dailySales,
        projectedDemand,
        suggestedQuantity,
        daysOfCover,
        status,
        statusLabel: statusStyles[status].label,
        productIds,
        productCount: group.length,
        sizes,
        lastPrice: group.length ? revenue / Math.max(1, quantitySold) : first.lastPrice
      };
    });
  }, [allRows]);

  const activeRows = viewMode === 'group' ? groupedRows : allRows;

  const filteredRows = useMemo(() => {
    const normalizedSearch = searchTerm.trim().toLowerCase();
    const searchedRows = normalizedSearch
      ? activeRows.filter(row =>
        row.name.toLowerCase().includes(normalizedSearch) ||
        row.id.toLowerCase().includes(normalizedSearch) ||
        row.productIds.some(id => id.toLowerCase().includes(normalizedSearch))
      )
      : activeRows;

    const statusRows = statusFilter === 'all'
      ? searchedRows
      : searchedRows.filter(row => (
        statusFilter === 'need'
          ? row.suggestedQuantity > 0
          : row.status === statusFilter
      ));

    return [...statusRows].sort((a, b) => {
      switch (sortBy) {
        case 'need_asc': return a.suggestedQuantity - b.suggestedQuantity;
        case 'demand_desc': return b.projectedDemand - a.projectedDemand;
        case 'stock_asc': return a.stock - b.stock;
        case 'coverage_asc': return (a.daysOfCover ?? Number.POSITIVE_INFINITY) - (b.daysOfCover ?? Number.POSITIVE_INFINITY);
        case 'sold_desc': return b.quantitySold - a.quantitySold;
        case 'name_asc': return a.name.localeCompare(b.name, 'pt-BR');
        case 'need_desc':
        default:
          return b.suggestedQuantity - a.suggestedQuantity;
      }
    });
  }, [activeRows, searchTerm, sortBy, statusFilter]);

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

  const needRows = activeRows.filter(row => row.suggestedQuantity > 0);
  const totalSuggestedQuantity = needRows.reduce((total, row) => total + row.suggestedQuantity, 0);
  const projectedDemand = activeRows.reduce((total, row) => total + row.projectedDemand, 0);
  const totalStock = activeRows.reduce((total, row) => total + row.stock, 0);

  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>
          <Link to="/supplies" className="mb-3 inline-flex items-center gap-2 text-sm font-bold text-zinc-500 transition-colors hover:text-zinc-900 dark:text-dark-muted dark:hover:text-dark-text">
            <ArrowLeft className="h-4 w-4" />
            Suprimentos
          </Link>
          <h1 className="text-2xl font-bold mb-2 text-zinc-900 dark:text-dark-text">Necessidade de Reposição</h1>
          <p className="text-zinc-500 dark:text-dark-muted font-medium">
            O período selecionado define a base de vendas; a cobertura define quantos dias de estoque sugerir.
          </p>
        </div>

        <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
          <DateRangePicker
            dateRange={dateRange}
            onChange={(range) => {
              setDateRange(range);
              setCurrentPage(1);
            }}
          />

          <button
            onClick={() => {
              const exportData = filteredRows.map(row => ({
                'Tipo': viewMode === 'group' ? 'Grupo' : 'SKU',
                'ID Produto': viewMode === 'group' ? row.productIds.join(' | ') : row.id,
                'Descricao': row.name,
                'Cor': row.color,
                'Tamanhos': row.sizes.join(' | '),
                'SKUs': row.productCount,
                'Status': row.statusLabel,
                'Cobertura alvo (dias)': targetCoverageDays,
                'Vendido no Periodo': row.quantitySold,
                'Media Diaria': row.dailySales.toFixed(2).replace('.', ','),
                'Demanda Projetada': row.projectedDemand.toFixed(2).replace('.', ','),
                'Estoque Atual': row.stock,
                'OP Aberta': row.openProductionQuantity,
                'Disponivel': row.availableQuantity,
                'Cobertura Atual': row.daysOfCover === null ? '' : row.daysOfCover.toFixed(1).replace('.', ','),
                'Sugestao Reposicao': row.suggestedQuantity
              }));
              exportToCSV(exportData, `necessidade_reposicao_${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} />

      <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
        <div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Produtos a repor</p>
              <p className="mt-2 text-3xl font-bold text-red-300">{formatNumber(needRows.length)}</p>
              <p className="mt-1 text-xs font-semibold text-dark-muted">
                {viewMode === 'group' ? 'Grupos' : 'SKUs'} abaixo da demanda projetada
              </p>
            </div>
            <div className="rounded-xl border border-red-400/25 bg-red-400/10 p-3 text-red-300">
              <AlertTriangle className="h-5 w-5" />
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Sugestão total</p>
              <p className="mt-2 text-3xl font-bold text-dark-text">{formatNumber(totalSuggestedQuantity)}</p>
              <p className="mt-1 text-xs font-semibold text-dark-muted">Unidades para cobrir {targetCoverageDays} dias</p>
            </div>
            <div className="rounded-xl border border-brand-primary/25 bg-brand-primary/10 p-3 text-brand-primary">
              <Package className="h-5 w-5" />
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">Demanda projetada</p>
              <p className="mt-2 text-3xl font-bold text-sky-300">{formatNumber(projectedDemand)}</p>
              <p className="mt-1 text-xs font-semibold text-dark-muted">Pelo ritmo do período selecionado</p>
            </div>
            <div className="rounded-xl border border-sky-400/25 bg-sky-400/10 p-3 text-sky-300">
              <TrendingUp className="h-5 w-5" />
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-dark-border bg-dark-card p-5 shadow-sm">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-xs font-bold uppercase tracking-widest text-dark-muted">{viewMode === 'group' ? 'Grupos cobertos' : 'Produtos cobertos'}</p>
              <p className="mt-2 text-3xl font-bold text-emerald-300">{formatNumber(activeRows.filter(row => row.status === 'covered').length)}</p>
              <p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(totalStock)} unidades em estoque</p>
            </div>
            <div className="rounded-xl border border-emerald-400/25 bg-emerald-400/10 p-3 text-emerald-300">
              <CheckCircle2 className="h-5 w-5" />
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-3 rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm xl:grid-cols-[auto_1fr_150px_180px_190px]">
        <div className="inline-flex rounded-xl border border-dark-border bg-dark-input p-1">
          {[
            { key: 'sku' as const, label: 'SKU' },
            { key: 'group' as const, label: 'Grupo' }
          ].map(view => (
            <button
              key={view.key}
              type="button"
              onClick={() => {
                setViewMode(view.key);
                setCurrentPage(1);
              }}
              className={`rounded-lg px-4 py-2 text-sm font-bold transition-colors cursor-pointer ${
                viewMode === view.key
                  ? 'bg-brand-primary text-brand-contrast'
                  : 'text-dark-muted hover:bg-dark-card hover:text-dark-text'
              }`}
            >
              {view.label}
            </button>
          ))}
        </div>

        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-zinc-400 dark:text-dark-muted" />
          <input
            type="text"
            placeholder="Buscar por nome ou ID..."
            value={searchTerm}
            onChange={(event) => {
              setSearchTerm(event.target.value);
              setCurrentPage(1);
            }}
            className="w-full bg-dark-input 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"
          />
        </div>

        <select
          value={targetCoverageDays}
          onChange={(event) => {
            setTargetCoverageDays(Number(event.target.value));
            setCurrentPage(1);
          }}
          className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
          aria-label="Dias de cobertura alvo"
        >
          {coverageTargetOptions.map(days => (
            <option key={days} value={days}>Cobrir {days} dias</option>
          ))}
        </select>

        <select
          value={statusFilter}
          onChange={(event) => {
            setStatusFilter(event.target.value as ReplenishmentFilter);
            setCurrentPage(1);
          }}
          className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
        >
          {filterOptions.map(option => (
            <option key={option.value} value={option.value}>{option.label}</option>
          ))}
        </select>

        <select
          value={sortBy}
          onChange={(event) => {
            setSortBy(event.target.value as ReplenishmentSort);
            setCurrentPage(1);
          }}
          className="h-11 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-semibold text-dark-text focus:outline-none focus:border-brand-primary cursor-pointer"
        >
          <option value="need_desc">Maior necessidade</option>
          <option value="need_asc">Menor necessidade</option>
          <option value="demand_desc">Maior demanda projetada</option>
          <option value="stock_asc">Menor estoque</option>
          <option value="coverage_asc">Menor cobertura</option>
          <option value="sold_desc">Mais vendidos</option>
          <option value="name_asc">Nome A-Z</option>
        </select>
      </div>

      {isLoading && products.length === 0 ? (
        <ReplenishmentSkeleton />
      ) : (
        <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-[120px]" />
                <col className="w-[130px]" />
                <col className="w-[140px]" />
                <col className="w-[120px]" />
                <col className="w-[150px]" />
                <col className="w-[130px]" />
                <col className="w-[140px]" />
              </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]">{viewMode === 'group' ? 'SKUs' : 'ID Produto'}</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">{viewMode === 'group' ? 'Grupo / cor' : 'Descrição'}</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Status</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Demanda proj.</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]">Disponível</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Sugestão reposição</th>
                  <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Cobertura</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">
                {paginatedRows.map(row => {
                  const style = statusStyles[row.status];

                  return (
                    <tr key={row.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors">
                      <td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">
                        {viewMode === 'group' ? `${row.productCount} SKUs` : `#${row.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={row.name}>{row.name}</div>
                        <div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">
                          {viewMode === 'group' && row.sizes.length ? `Tamanhos: ${row.sizes.join(', ')} · ` : ''}
                          Média: {formatNumber(row.dailySales, 2)} un./dia · Vendido: {formatNumber(row.quantitySold)} un.
                        </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 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatNumber(row.projectedDemand, 1)} un.</td>
                      <td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatNumber(row.stock)} un.</td>
                      <td className="px-6 py-2.5 whitespace-nowrap">
                        <span className="font-bold text-zinc-900 dark:text-dark-text">{formatNumber(row.availableQuantity)} un.</span>
                        {!!row.openProductionQuantity && (
                          <span className="ml-1 text-xs font-semibold text-dark-muted">OP {formatNumber(row.openProductionQuantity)}</span>
                        )}
                      </td>
                      <td className="px-6 py-2.5 whitespace-nowrap">
                        <span className={row.suggestedQuantity > 0 ? 'font-bold text-red-300' : 'font-bold text-emerald-300'}>
                          {formatNumber(row.suggestedQuantity)} un.
                        </span>
                      </td>
                      <td className="px-6 py-2.5 font-bold text-zinc-900 dark:text-dark-text whitespace-nowrap">{formatDays(row.daysOfCover)}</td>
                      <td className="px-4 py-2.5 text-right">
                        <div className="flex justify-end gap-2">
                          {viewMode === 'sku' && (
                            <Link
                              to={buildSkuEditPath({ sku: row.id, name: row.name, color: row.color, size: row.size })}
                              className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-dark-input text-dark-text transition-colors hover:bg-dark-border cursor-pointer"
                              title={`Editar SKU ${row.id}`}
                              aria-label={`Editar SKU ${row.id}`}
                            >
                              <Pencil className="h-3.5 w-3.5" />
                            </Link>
                          )}
                          <Link
                            to={viewMode === 'group' ? `/products/groups/${encodeProductGroupKey(row.baseName)}` : `/products/${row.id}`}
                            className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-brand-primary/10 text-brand-primary transition-opacity hover:opacity-80 cursor-pointer"
                            title={viewMode === 'group' ? `Ver grupo ${row.baseName}` : `Ver SKU ${row.id}`}
                            aria-label={viewMode === 'group' ? `Ver grupo ${row.baseName}` : `Ver SKU ${row.id}`}
                          >
                            <Eye className="h-3.5 w-3.5" />
                          </Link>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {!filteredRows.length && (
            <div className="px-6 py-12 text-center">
              <Package 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 os filtros, a busca ou o período selecionado.</p>
            </div>
          )}

          <PaginationControls
            totalItems={filteredRows.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, filteredRows.length)}
            onPageChange={setCurrentPage}
            onPageSizeChange={(pageSize) => {
              setItemsPerPage(pageSize);
              setCurrentPage(1);
            }}
          />
        </div>
      )}
    </div>
  );
};

export default Replenishment;
