import { useEffect, useState } from 'react';
import { useParams, Link, useOutletContext } from 'react-router-dom';
import { Package, DollarSign, Pencil, ReceiptText, Warehouse } from 'lucide-react';
import { AreaChart, Area, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import BackButton from '../components/BackButton';
import DateRangePicker from '../components/DateRangePicker';
import SkuPlanningModal from '../components/SkuPlanningModal';
import ProductTypeBadge from '../components/ProductTypeBadge';
import RefreshStatus from '../components/RefreshStatus';
import type { CutProductOverride, CuttingSettings, DateRange, ProductComposition, ProductDetailsAnalytics } from '../types';
import { fetchCuttingSettings, fetchProductComposition, fetchProductDetailsAnalytics, saveCuttingSettings } from '../dataService';
import { parseProductName } from '../productParsing';
import { formatColorLabel } from '../displayFormatters';
import { averageRecentValues, formatDateBucketLabel, formatDateBucketLongLabel, getAutoDateBucket, getMovingAverageWindow, getRangeDayCount, getDateBucketKey, type DateBucket } from '../chartUtils';
import { getProductTypeConfig, resolveProductType } from '../productClassification';
import { getPlanningStock } from '../planningStock';

const CHART_GRID_COLOR = 'var(--chart-grid)';
const CHART_AXIS_COLOR = 'var(--chart-axis)';
const CHART_CURSOR_COLOR = 'var(--chart-cursor)';
const CHART_DETAIL_BAR_COLOR = 'var(--chart-detail-bar)';
const VARIANT_BAR_COLOR = '#52DFA0';

type ProductChartMetric = 'quantity' | 'revenue' | 'ticket';

type ProductMetricChartPoint = ProductDetailsAnalytics['chartData'][number] & {
  selectedValue: number;
  movingAverage?: number;
};

const formatDateKey = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

type CustomTooltipProps = {
  active?: boolean;
  payload?: Array<{
    value: number;
    dataKey?: string;
    payload?: ProductMetricChartPoint;
  }>;
  label?: string;
  metric: ProductChartMetric;
  formatCurrency: (value: number) => string;
  formatNumber: (value: number) => string;
  isHourly: boolean;
  dateBucket: DateBucket;
};

const CustomTooltip = ({ active, payload, label, metric, formatCurrency, formatNumber, isHourly, dateBucket }: CustomTooltipProps) => {
  if (active && payload && payload.length) {
    const primaryPayload = payload.find(item => item.dataKey === 'selectedValue') || payload[0];
    const point = primaryPayload.payload;
    const value = primaryPayload.value;
    const displayValue = metric === 'quantity' ? `${formatNumber(value)} un.` : formatCurrency(value);
    const displayLabel = isHourly ? String(label || '') : formatDateBucketLongLabel(String(label || ''), dateBucket);

    return (
      <div
        className="rounded-xl border p-3 shadow-lg"
        style={{ backgroundColor: 'var(--chart-tooltip-bg)', borderColor: 'var(--chart-tooltip-border)' }}
      >
        <p className="font-bold mb-1" style={{ color: CHART_DETAIL_BAR_COLOR }}>{displayLabel}</p>
        <p className="m-0 font-semibold" style={{ color: 'var(--chart-tooltip-text)' }}>{displayValue}</p>
        {point && (
          <div className="mt-2 space-y-1 text-xs" style={{ color: 'var(--chart-axis)' }}>
            <p className="m-0">Unidades: {formatNumber(point.quantitySold ?? point.value ?? 0)}</p>
            <p className="m-0">Receita: {formatCurrency(point.revenue ?? 0)}</p>
            <p className="m-0">Pedidos: {formatNumber(point.orderCount ?? 0)}</p>
          </div>
        )}
      </div>
    );
  }
  return null;
};

const ProductDetailsSkeleton = () => (
  <div className="space-y-6" aria-label="Carregando produto">
    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
      <div className="flex flex-col gap-4">
        <div className="skeleton h-4 w-20" />
        <div className="flex items-center gap-4">
          <div className="skeleton h-16 w-16 rounded-2xl" />
          <div>
            <div className="skeleton h-3 w-24" />
            <div className="skeleton mt-3 h-7 w-80 max-w-[70vw]" />
          </div>
        </div>
      </div>
      <div className="skeleton h-10 w-64" />
    </div>

    <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
      {[0, 1, 2, 3].map(item => (
        <div key={`product-details-kpi-skeleton-${item}`} className="bg-dark-card p-6 rounded-2xl border border-dark-border shadow-sm">
          <div className="flex justify-between gap-6">
            <div className="w-full">
              <div className="skeleton h-3 w-36" />
              <div className="skeleton mt-3 h-8 w-32" />
            </div>
            <div className="skeleton h-12 w-12 shrink-0 rounded-xl" />
          </div>
        </div>
      ))}
    </div>

    <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
      <div className="skeleton h-5 w-56" />
      <div className="mt-8 skeleton h-[400px] w-full" />
    </div>

    <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
      <div className="skeleton h-5 w-44" />
      <div className="mt-5 space-y-3">
        {[0, 1, 2, 3].map(item => (
          <div key={`product-variant-skeleton-${item}`} className="skeleton h-12 w-full" />
        ))}
      </div>
    </div>
  </div>
);

const ProductDetails = () => {
  const { id } = useParams<{ id: string }>();
  const { dateRange, setDateRange } = useOutletContext<{ 
    dateRange: DateRange, 
    setDateRange: (range: DateRange) => void
  }>();
  const [details, setDetails] = useState<ProductDetailsAnalytics | null>(null);
  const [composition, setComposition] = useState<ProductComposition | null>(null);
  const [isCompositionLoading, setIsCompositionLoading] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [chartMetric, setChartMetric] = useState<ProductChartMetric>('quantity');
  const [selectedProductBucket, setSelectedProductBucket] = useState<string | null>(null);
  const [planningSettings, setPlanningSettings] = useState<CuttingSettings>({ familyYields: {}, productOverrides: {} });
  const [isPlanningModalOpen, setIsPlanningModalOpen] = useState(false);
  const [isSavingPlanning, setIsSavingPlanning] = useState(false);

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

    const loadPlanningSettings = async () => {
      const settings = await fetchCuttingSettings();
      if (isMounted) setPlanningSettings(settings);
    };

    void loadPlanningSettings();

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

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

    const loadProductDetails = async () => {
      if (!id) {
        if (isMounted) {
          setDetails(null);
          setComposition(null);
          setIsLoading(false);
          setIsCompositionLoading(false);
        }
        return;
      }

      setIsLoading(true);
      setIsCompositionLoading(true);
      const [productDetails, productComposition] = await Promise.all([
        fetchProductDetailsAnalytics(id, dateRange),
        fetchProductComposition(id)
      ]);

      if (isMounted) {
        setDetails(productDetails);
        setComposition(productComposition);
        setIsLoading(false);
        setIsCompositionLoading(false);
      }
    };

    void loadProductDetails();

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

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

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

  const saveProductOverride = async (productId: string, override: CutProductOverride | null) => {
    const productOverrides = { ...planningSettings.productOverrides };
    if (override) {
      productOverrides[productId] = override;
    } else {
      delete productOverrides[productId];
    }

    const nextSettings = { ...planningSettings, productOverrides };
    setIsSavingPlanning(true);
    try {
      const savedSettings = await saveCuttingSettings(nextSettings);
      setPlanningSettings(savedSettings);
      setIsPlanningModalOpen(false);
    } finally {
      setIsSavingPlanning(false);
    }
  };

  if (isLoading && !details) {
    return <ProductDetailsSkeleton />;
  }

  if (!details?.productInfo) {
    return (
      <div className="text-center py-12">
        <p className="text-zinc-500 dark:text-dark-muted font-medium">Produto não encontrado.</p>
        <Link to="/products" className="text-brand-primary hover:underline mt-4 inline-block font-bold">Voltar para produtos</Link>
      </div>
    );
  }

  const { productInfo, chartData, totalSold, totalRevenue, totalOrders = 0, averageTicket = 0, variantBreakdown = [] } = details;
  const productType = resolveProductType(productInfo.name, planningSettings.productOverrides[productInfo.id]);
  const productTypeConfig = getProductTypeConfig(productType);
  const isRefreshing = isLoading && Boolean(details);
  const isSingleDayRange = formatDateKey(dateRange.start) === formatDateKey(dateRange.end);
  const isHourlyChart = isSingleDayRange && chartData.some(point => /h$|:/.test(point.date));
  const dateBucket = isHourlyChart ? 'day' : getAutoDateBucket(dateRange);
  const periodDays = getRangeDayCount(dateRange);
  const dailyAverageSold = totalSold / periodDays;
  const projectedStockDays = dailyAverageSold > 0 ? getPlanningStock(productInfo.stock) / dailyAverageSold : null;
  const stockActionLabel = projectedStockDays === null
    ? 'Sem venda no período'
    : projectedStockDays <= 7
      ? 'Reposição crítica'
      : projectedStockDays <= 21
        ? 'Planejar reposição'
        : 'Estoque confortável';
  const metricConfig = {
    quantity: {
      label: 'Unidades',
      title: `Volume por ${isHourlyChart ? 'Horário' : 'Data'}`,
      subtitle: 'Quantidade vendida no período selecionado.',
      tickFormatter: (value: number) => formatNumber(value)
    },
    revenue: {
      label: 'Receita',
      title: `Receita por ${isHourlyChart ? 'Horário' : 'Data'}`,
      subtitle: 'Faturamento do produto no período selecionado.',
      tickFormatter: (value: number) => value >= 1000 ? `${formatNumber(value / 1000)}k` : formatCurrency(value)
    },
    ticket: {
      label: 'Ticket médio',
      title: `Ticket médio por ${isHourlyChart ? 'Horário' : 'Data'}`,
      subtitle: 'Receita média por pedido neste produto.',
      tickFormatter: (value: number) => value >= 1000 ? `${formatNumber(value / 1000)}k` : formatCurrency(value)
    }
  } satisfies Record<ProductChartMetric, {
    label: string;
    title: string;
    subtitle: string;
    tickFormatter: (value: number) => string;
  }>;
  const selectedMetric = metricConfig[chartMetric];
  const metricChartData = (() => {
    const bucketMap = new Map<string, ProductMetricChartPoint>();

    chartData.forEach(point => {
      const sourceKey = isHourlyChart ? point.date : getDateBucketKey(point.date, dateBucket);
      const current = bucketMap.get(sourceKey) || {
        date: sourceKey,
        value: 0,
        quantitySold: 0,
        revenue: 0,
        orderCount: 0,
        averageTicket: 0,
        selectedValue: 0
      };
      const quantity = point.quantitySold ?? point.value ?? 0;
      const revenue = point.revenue ?? 0;
      const orderCount = point.orderCount ?? 0;

      current.value = (current.value || 0) + quantity;
      current.quantitySold = (current.quantitySold || 0) + quantity;
      current.revenue = (current.revenue || 0) + revenue;
      current.orderCount = (current.orderCount || 0) + orderCount;
      current.averageTicket = current.orderCount ? current.revenue / current.orderCount : 0;
      bucketMap.set(sourceKey, current);
    });

    const rows = [...bucketMap.values()]
      .filter(point => (point.quantitySold || point.value || point.revenue || point.orderCount))
      .sort((a, b) => a.date.localeCompare(b.date))
      .map(point => ({
        ...point,
        selectedValue: chartMetric === 'quantity'
          ? (point.quantitySold ?? point.value)
          : chartMetric === 'revenue'
            ? (point.revenue ?? 0)
            : (point.averageTicket ?? 0)
      }));

    const movingAverageWindow = isHourlyChart ? 0 : getMovingAverageWindow(dateBucket);
    if (movingAverageWindow > 1) {
      const values = rows.map(point => point.selectedValue);
      rows.forEach((point, index) => {
        point.movingAverage = averageRecentValues(values, index, movingAverageWindow);
      });
    }

    return rows;
  })();
  const selectedProductPoint = selectedProductBucket
    ? metricChartData.find(point => point.date === selectedProductBucket)
    : null;
  const selectedProductBucketLabel = selectedProductPoint
    ? isHourlyChart
      ? selectedProductPoint.date
      : formatDateBucketLongLabel(selectedProductPoint.date, dateBucket)
    : '';
  const maxVariantQuantity = Math.max(...variantBreakdown.map(variant => variant.quantitySold), 0);

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex flex-col gap-4">
          <BackButton fallbackTo="/products" />
          
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-2xl bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border flex items-center justify-center shadow-sm text-brand-primary">
              <Package className="w-8 h-8" />
            </div>
            <div>
              <div className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest">ID: #{productInfo.id}</div>
              <h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text">{productInfo.name}</h1>
              <div className="mt-2 flex flex-wrap items-center gap-2">
                <ProductTypeBadge type={productType} />
                <span className="text-xs font-semibold text-dark-muted">{productTypeConfig.description}</span>
                <button
                  type="button"
                  onClick={() => setIsPlanningModalOpen(true)}
                  className="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-dark-border bg-dark-input text-dark-muted transition-colors hover:border-brand-primary hover:text-brand-primary cursor-pointer"
                  title={`Editar planejamento do SKU ${productInfo.id}`}
                  aria-label={`Editar planejamento do SKU ${productInfo.id}`}
                >
                  <Pencil className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          </div>
        </div>

        <DateRangePicker 
          dateRange={dateRange} 
          onChange={setDateRange} 
        />      </div>

      <RefreshStatus isRefreshing={isRefreshing} />

      <div className={isRefreshing ? 'refreshing-content space-y-6' : 'space-y-6'} aria-busy={isRefreshing}>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
        <div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Unidades Vendidas</p>
            <p className="text-3xl font-bold text-dark-text">{formatNumber(totalSold)}</p>
            <p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(dailyAverageSold)} un./dia</p>
          </div>
          <div className="p-3 bg-brand-primary/10 rounded-xl text-brand-primary">
            <Package size={24} />
          </div>
        </div>
        <div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Receita Total</p>
            <p className="text-3xl font-bold text-brand-primary">{formatCurrency(totalRevenue)}</p>
          </div>
          <div className="p-3 bg-emerald-500/10 rounded-xl text-emerald-500">
            <DollarSign size={24} />
          </div>
        </div>
        <div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Ticket Médio</p>
            <p className="text-3xl font-bold text-dark-text">{formatCurrency(averageTicket)}</p>
          </div>
          <div className="p-3 bg-sky-500/10 rounded-xl text-sky-500">
            <ReceiptText size={24} />
          </div>
        </div>
        <div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Estoque</p>
            <p className="text-3xl font-bold text-dark-text">{formatNumber(productInfo.stock)}</p>
            <p className="mt-1 text-xs font-semibold text-dark-muted">
              {projectedStockDays === null ? stockActionLabel : `${formatNumber(projectedStockDays)} dias · ${stockActionLabel}`}
            </p>
          </div>
          <div className="p-3 bg-purple-500/10 rounded-xl text-purple-400">
            <Warehouse size={24} />
          </div>
        </div>
      </div>

      <section className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
        <div className="mb-5">
          <h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Composição</h3>
          {composition && (
            <p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">
              Para produzir 1 UN de {composition.finishedProductSku || productInfo.id}
            </p>
          )}
        </div>
        {isCompositionLoading ? (
          <div className="flex h-24 items-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">Carregando composição…</div>
        ) : !composition ? (
          <div className="flex h-24 items-center justify-center rounded-xl border border-dashed border-dark-border bg-dark-input/30 text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Nenhuma composição sincronizada para este produto.
          </div>
        ) : composition.components.length === 0 ? (
          <div className="flex h-24 items-center justify-center rounded-xl border border-dashed border-dark-border bg-dark-input/30 text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Esta composição não possui insumos.
          </div>
        ) : (
          <div className="overflow-x-auto rounded-xl border border-dark-border">
            <table className="w-full min-w-[640px] text-left text-sm">
              <thead className="bg-dark-input/60 text-[10px] font-bold uppercase tracking-widest text-dark-muted">
                <tr>
                  <th className="px-4 py-3">Produto / insumo</th>
                  <th className="px-4 py-3">SKU</th>
                  <th className="px-4 py-3 text-right">Quantidade por unidade</th>
                  <th className="px-4 py-3">Unidade</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-dark-border">
                {composition.components.map(component => (
                  <tr key={component.id} className="text-dark-text">
                    <td className="px-4 py-3 font-semibold">
                      {component.productId ? (
                        <Link to={`/products/${component.productId}`} className="text-brand-primary hover:underline">
                          {component.componentName}
                        </Link>
                      ) : component.componentName}
                    </td>
                    <td className="px-4 py-3 font-mono text-xs text-dark-muted">{component.componentSku || '—'}</td>
                    <td className="px-4 py-3 text-right font-semibold">{formatNumber(component.quantityPerUnit)}</td>
                    <td className="px-4 py-3 text-dark-muted">{component.unit || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
        <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
          <div>
            <h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">{selectedMetric.title}</h3>
            <p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">
              {isHourlyChart
                ? selectedMetric.subtitle
                : dateBucket === 'day'
                  ? `${selectedMetric.subtitle} Média móvel de 7 dias.`
                  : dateBucket === 'week'
                    ? 'Valores agrupados por semana com média móvel de 4 semanas.'
                    : 'Valores agrupados por mês com média móvel de 3 meses.'}
            </p>
          </div>
          <div className="flex w-fit rounded-xl border border-dark-border bg-dark-input p-1">
            {(Object.keys(metricConfig) as ProductChartMetric[]).map(metric => (
              <button
                key={metric}
                type="button"
                onClick={() => setChartMetric(metric)}
                className={`cursor-pointer rounded-lg px-3 py-1.5 text-xs font-bold transition-colors ${
                  chartMetric === metric
                    ? 'bg-dark-card text-dark-text shadow-sm'
                    : 'text-dark-muted hover:text-dark-text'
                }`}
              >
                {metricConfig[metric].label}
              </button>
            ))}
          </div>
        </div>
        {metricChartData.length === 0 ? (
          <div className="flex h-[360px] items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Nenhuma venda no período selecionado.
          </div>
        ) : (
        <div className="h-[400px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart
              data={metricChartData}
              margin={{ top: 5, right: 30, left: 20, bottom: 28 }}
              onClick={(event) => {
                if (event?.activeLabel) setSelectedProductBucket(String(event.activeLabel));
              }}
            >
              <defs>
                <linearGradient id="productVolumeGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={CHART_DETAIL_BAR_COLOR} stopOpacity={0.38} />
                  <stop offset="95%" stopColor={CHART_DETAIL_BAR_COLOR} stopOpacity={0.04} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
              <XAxis 
                dataKey="date" stroke={CHART_AXIS_COLOR} fontSize={10} tickLine={false} axisLine={false}
                minTickGap={18}
                tickFormatter={(value) => (
                  isHourlyChart ? String(value) : formatDateBucketLabel(String(value), dateBucket)
                )}
              />
              <YAxis stroke={CHART_AXIS_COLOR} fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => selectedMetric.tickFormatter(Number(value))} />
              <Tooltip content={<CustomTooltip metric={chartMetric} formatCurrency={formatCurrency} formatNumber={formatNumber} isHourly={isHourlyChart} dateBucket={dateBucket} />} cursor={{ fill: CHART_CURSOR_COLOR }} />
              <Area
                type="monotone"
                dataKey="selectedValue"
                stroke={CHART_DETAIL_BAR_COLOR}
                strokeWidth={2.25}
                fill="url(#productVolumeGradient)"
                dot={{ r: 3, strokeWidth: 2, fill: 'var(--color-dark-card)', stroke: CHART_DETAIL_BAR_COLOR }}
                activeDot={{ r: 5, strokeWidth: 2, fill: CHART_DETAIL_BAR_COLOR, stroke: 'var(--color-dark-card)' }}
              />
              {!isHourlyChart && metricChartData.some(point => point.movingAverage !== undefined) && (
                <Line
                  type="monotone"
                  dataKey="movingAverage"
                  name="Média móvel"
                  stroke="var(--chart-label)"
                  strokeWidth={2.5}
                  strokeDasharray="6 5"
                  dot={false}
                  activeDot={false}
                />
              )}
            </AreaChart>
          </ResponsiveContainer>
        </div>
        )}
        {selectedProductPoint && (
          <div className="mt-4 rounded-xl border border-dark-border bg-dark-input/45 p-4">
            <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
              <div>
                <h4 className="text-sm font-bold text-dark-text">{selectedProductBucketLabel}</h4>
                <p className="mt-1 text-xs font-semibold text-dark-muted">Detalhe do ponto selecionado.</p>
              </div>
              <button
                type="button"
                onClick={() => setSelectedProductBucket(null)}
                className="h-8 rounded-lg border border-dark-border bg-dark-card px-3 text-xs font-bold text-dark-muted transition-colors hover:text-dark-text"
              >
                Limpar
              </button>
            </div>
            <div className="mt-4 grid gap-3 md:grid-cols-5">
              <div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Unidades</div>
                <div className="mt-1 text-sm font-bold text-dark-text">{formatNumber(selectedProductPoint.quantitySold ?? selectedProductPoint.value ?? 0)}</div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Receita</div>
                <div className="mt-1 text-sm font-bold text-dark-text">{formatCurrency(selectedProductPoint.revenue ?? 0)}</div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Pedidos</div>
                <div className="mt-1 text-sm font-bold text-dark-text">{formatNumber(selectedProductPoint.orderCount ?? 0)}</div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Ticket</div>
                <div className="mt-1 text-sm font-bold text-dark-text">{formatCurrency(selectedProductPoint.averageTicket ?? 0)}</div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Cobertura</div>
                <div className="mt-1 text-sm font-bold text-dark-text">{projectedStockDays === null ? '-' : `${formatNumber(projectedStockDays)} dias`}</div>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
        <div className="mb-5 flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
          <div>
            <h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Variações do Produto</h3>
            <p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">Tamanhos, cores ou SKUs parecidos no mesmo período.</p>
          </div>
          <span className="text-xs font-bold uppercase tracking-widest text-zinc-400 dark:text-dark-muted">
            {formatNumber(totalOrders)} {totalOrders === 1 ? 'pedido' : 'pedidos'}
          </span>
        </div>
        {variantBreakdown.length === 0 ? (
          <div className="flex h-32 items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Nenhuma variação encontrada para este produto.
          </div>
        ) : (
          <div className="space-y-3">
            {variantBreakdown.map(variant => {
              const width = maxVariantQuantity ? Math.max(4, (variant.quantitySold / maxVariantQuantity) * 100) : 0;
              const metadata = parseProductName(variant.name);

              return (
                <div key={variant.id} className="rounded-xl border border-dark-border bg-dark-input/45 p-4">
                  <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
                    <div className="min-w-0">
                      <div className="truncate text-sm font-bold text-dark-text">{variant.name}</div>
                      <div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] font-medium text-dark-muted">
                        <span>#{variant.id}</span>
                        {metadata.color && (
                          <span className="rounded-full border border-sky-400/25 bg-sky-400/10 px-2 py-0.5 font-bold text-sky-300">
                            {formatColorLabel(metadata.color)}
                          </span>
                        )}
                        {metadata.size && (
                          <span className="rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 font-bold text-emerald-300">
                            Tam. {metadata.size}
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex shrink-0 gap-5 text-right text-xs">
                      <div>
                        <div className="font-bold text-dark-text">{formatNumber(variant.quantitySold)} un.</div>
                        <div className="text-dark-muted">vendidas</div>
                      </div>
                      <div>
                        <div className="font-bold text-brand-primary">{formatCurrency(variant.revenue)}</div>
                        <div className="text-dark-muted">receita</div>
                      </div>
                    </div>
                  </div>
                  <div className="mt-3 h-2 overflow-hidden rounded-full bg-dark-border">
                    <div
                      className="h-full rounded-full"
                      style={{
                        width: `${width}%`,
                        backgroundColor: VARIANT_BAR_COLOR,
                        opacity: 0.72
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
      </div>

      {isPlanningModalOpen && (
        <SkuPlanningModal
          product={productInfo}
          override={planningSettings.productOverrides[productInfo.id]}
          isSaving={isSavingPlanning}
          onClose={() => setIsPlanningModalOpen(false)}
          onSave={(override) => saveProductOverride(productInfo.id, override)}
        />
      )}
    </div>
  );
};

export default ProductDetails;
