import { useEffect, useState } from 'react';
import { useParams, Link, useOutletContext } from 'react-router-dom';
import { User, Tag, Package, DollarSign, Clock, Phone, ChevronDown, ShoppingBag, ReceiptText } from 'lucide-react';
import { AreaChart, Area, BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import BackButton from '../components/BackButton';
import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls';
import RefreshStatus from '../components/RefreshStatus';
import type { ClientDetailsAnalytics, DateRange, OrderData } from '../types';
import { fetchClientDetailsAnalytics } from '../dataService';
import { formatDisplayName, removeTrailingSellerId } from '../displayFormatters';

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 WEEKDAY_BAR_COLOR = '#25C2FF';
const HOUR_BAR_COLOR = '#52DFA0';

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 }>;
  label?: string;
};

type PatternPoint = {
  label: string;
  value: number;
};

const getTopPatternPoint = (points: PatternPoint[]) => (
  points.reduce<PatternPoint | null>((topPoint, point) => {
    if (!topPoint || point.value > topPoint.value) return point;
    return topPoint;
  }, null)
);

const getPatternShare = (value: number, total: number) => (
  total > 0 ? Math.round((value / total) * 100) : 0
);

const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
  if (active && payload && payload.length) {
    return (
      <div className="rounded-xl bg-dark-card p-3 shadow-lg">
        <p className="mb-1 font-bold text-brand-primary">{label}</p>
        <p className="m-0 text-dark-text">
          Gasto: {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(payload[0].value)}
        </p>
      </div>
    );
  }
  return null;
};

const PatternTooltip = ({ active, payload, label }: CustomTooltipProps) => {
  if (active && payload && payload.length) {
    const value = payload[0].value;
    return (
      <div className="rounded-xl bg-dark-card p-3 shadow-lg">
        <p className="mb-1 font-bold text-brand-primary">{label}</p>
        <p className="m-0 text-dark-text">
          {value} {value === 1 ? 'pedido' : 'pedidos'}
        </p>
      </div>
    );
  }
  return null;
};

const getOrderMetadata = (order: OrderData) => {
  const sellerName = formatDisplayName(removeTrailingSellerId(order.nome_vendedor || ''));

  return [
    order.cliente_nome_fantasia ? `Fantasia: ${formatDisplayName(order.cliente_nome_fantasia)}` : '',
    sellerName ? `Vendedor: ${sellerName}` : '',
    order.marketplace ? `Marketplace: ${order.marketplace}` : '',
    order.canal_venda ? `Canal: ${order.canal_venda}` : '',
    order.numero_ecommerce ? `E-commerce: ${order.numero_ecommerce}` : ''
  ].filter(Boolean);
};

const ClientDetailsSkeleton = () => (
  <div className="space-y-6" aria-label="Carregando cliente">
    <div className="flex flex-col gap-4">
      <div className="skeleton h-4 w-20" />
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="flex items-center gap-4">
          <div className="skeleton h-16 w-16 rounded-2xl" />
          <div>
            <div className="skeleton h-7 w-56" />
            <div className="skeleton mt-3 h-4 w-72" />
          </div>
        </div>
        <div className="skeleton h-10 w-64" />
      </div>
    </div>

    <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
      {[0, 1, 2, 3].map(item => (
        <div key={`client-details-kpi-skeleton-${item}`} className="bg-dark-card p-5 rounded-2xl border border-dark-border shadow-sm">
          <div className="flex justify-between gap-5">
            <div className="w-full">
              <div className="skeleton h-3 w-32" />
              <div className="skeleton mt-3 h-7 w-28" />
            </div>
            <div className="skeleton h-11 w-11 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-36" />
      <div className="mt-8 skeleton h-[320px] w-full" />
    </div>

    <section className="space-y-4">
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="skeleton h-5 w-44" />
          <div className="skeleton mt-2 h-4 w-64" />
        </div>
        <div className="skeleton h-7 w-28 rounded-full" />
      </div>
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {[0, 1].map(item => (
          <div key={`client-pattern-skeleton-${item}`} 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-4 w-40" />
            <div className="mt-5 flex h-56 items-end gap-3">
              {[0, 1, 2, 3, 4, 5, 6].map(bar => (
                <div key={`client-pattern-bar-skeleton-${item}-${bar}`} className="skeleton flex-1" style={{ height: `${20 + ((bar * 17) % 65)}%` }} />
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>

    <div className="flex flex-col gap-4">
      {[0, 1, 2, 3].map(item => (
        <div key={`client-order-skeleton-${item}`} className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-4 shadow-sm">
          <div className="flex items-center justify-between gap-4">
            <div className="flex min-w-0 items-center gap-3">
              <div className="skeleton h-8 w-8 rounded-lg" />
              <div>
                <div className="skeleton h-4 w-48" />
                <div className="skeleton mt-2 h-3 w-32" />
              </div>
            </div>
            <div className="skeleton h-8 w-28" />
          </div>
        </div>
      ))}
    </div>
  </div>
);

const ClientDetails = () => {
  const { clientToken } = useParams<{ clientToken: string }>();
  const decodedClientToken = clientToken ? decodeURIComponent(clientToken) : '';
  const { dateRange, setDateRange } = useOutletContext<{
    dateRange: DateRange,
    setDateRange: (range: DateRange) => void
  }>();
  const [details, setDetails] = useState<ClientDetailsAnalytics | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [ordersPerPage, setOrdersPerPage] = useState(5);
  const [expandedOrderIds, setExpandedOrderIds] = useState<Set<string>>(() => new Set());

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

    const loadClientDetails = async () => {
      if (!decodedClientToken) {
        if (isMounted) {
          setDetails(null);
          setIsLoading(false);
        }
        return;
      }

      setIsLoading(true);
      const nextDetails = await fetchClientDetailsAnalytics(decodedClientToken, dateRange);

      if (isMounted) {
        setDetails(nextDetails);
        setIsLoading(false);
      }
    };

    void loadClientDetails();

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

  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 handleDateRangeChange = (range: DateRange) => {
    setCurrentPage(1);
    setExpandedOrderIds(new Set());
    setDateRange(range);
  };

  const toggleOrder = (orderId: string) => {
    setExpandedOrderIds(current => {
      const next = new Set(current);
      if (next.has(orderId)) {
        next.delete(orderId);
      } else {
        next.add(orderId);
      }
      return next;
    });
  };

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

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

  const {
    chartData,
    groupedOrders,
    purchaseHours = [],
    purchaseHourRangeLabel = 'Últimos 60 dias',
    purchaseWeekdayRangeLabel = 'Todo período',
    purchaseWeekdays = [],
    allTimeOrderCount,
    clientName,
    clientPhone,
    periodAverageTicket,
    periodItems,
    periodOrderCount,
    periodSpent
  } = details;
  const displayName = clientName || 'Cliente';
  const totalPages = Math.ceil(groupedOrders.length / ordersPerPage);
  const safeCurrentPage = Math.min(currentPage, totalPages || 1);
  const startIndex = (safeCurrentPage - 1) * ordersPerPage;
  const paginatedOrders = groupedOrders.slice(startIndex, startIndex + ordersPerPage);
  const hasWeekdayPattern = purchaseWeekdays.some(day => day.value > 0);
  const hasHourPattern = purchaseHours.some(hour => hour.value > 0);
  const weekdayPatternTotal = purchaseWeekdays.reduce((total, day) => total + day.value, 0);
  const hourPatternTotal = purchaseHours.reduce((total, hour) => total + hour.value, 0);
  const topWeekday = getTopPatternPoint(purchaseWeekdays);
  const topHour = getTopPatternPoint(purchaseHours);
  const isRefreshing = isLoading && Boolean(details);
  const isSingleDayRange = formatDateKey(dateRange.start) === formatDateKey(dateRange.end);

  return (
    <div className="space-y-6">
      {/* Header Area */}
      <div className="flex flex-col gap-4">
        <BackButton fallbackTo="/clients" />
        
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
          <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">
              <User className="w-8 h-8 text-brand-primary" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text">{displayName}</h1>
              <div className="flex items-center gap-3 mt-1">
                <p className="text-zinc-500 dark:text-dark-muted font-medium">
                  {formatNumber(allTimeOrderCount)} pedidos no histórico completo
                </p>
                {clientPhone && (
                  <>
                    <span className="text-zinc-300 dark:text-dark-border">•</span>
                    <span className="flex items-center gap-1.5 text-brand-primary font-bold text-sm bg-brand-primary/10 px-2 py-1 rounded-md">
                      <Phone className="w-3.5 h-3.5" />
                      {clientPhone}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
          
          <DateRangePicker
            dateRange={dateRange}
            onChange={handleDateRangeChange}
          />
        </div>
      </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-5 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">Gasto no Período</p>
            <p className="text-2xl font-bold text-brand-primary">{formatCurrency(periodSpent)}</p>
          </div>
          <div className="p-3 bg-brand-primary/10 rounded-xl text-brand-primary">
            <DollarSign size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 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 no Período</p>
            <p className="text-2xl font-bold text-dark-text">{formatCurrency(periodAverageTicket)}</p>
          </div>
          <div className="p-3 bg-emerald-500/10 rounded-xl text-emerald-400">
            <ReceiptText size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 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">Total Pedidos</p>
            <p className="text-2xl font-bold text-dark-text">{formatNumber(periodOrderCount)}</p>
          </div>
          <div className="p-3 bg-blue-500/10 rounded-xl text-blue-300">
            <ShoppingBag size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 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">Itens no Período</p>
            <p className="text-2xl font-bold text-dark-text">{formatNumber(periodItems)}</p>
          </div>
          <div className="p-3 bg-purple-500/10 rounded-xl text-purple-300">
            <Package size={22} />
          </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">
        <h3 className="text-lg font-bold mb-8 text-zinc-900 dark:text-dark-text">
          Gasto por {isSingleDayRange ? 'Horário' : 'Data'}
        </h3>
        {chartData.length === 0 ? (
          <div className="flex h-[320px] items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Nenhum gasto no período selecionado.
          </div>
        ) : (
          <div className="h-[320px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: isSingleDayRange ? 24 : 80 }}>
                <defs>
                  <linearGradient id="clientSpendGradient" 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}
                  interval={isSingleDayRange ? 2 : 0}
                  angle={isSingleDayRange ? 0 : -45}
                  textAnchor={isSingleDayRange ? 'middle' : 'end'}
                  height={isSingleDayRange ? 24 : 80}
                />
                <YAxis stroke={CHART_AXIS_COLOR} fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => formatCurrency(Number(value))} />
                <Tooltip content={<CustomTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
                <Area
                  type="monotone"
                  dataKey="value"
                  stroke={CHART_DETAIL_BAR_COLOR}
                  strokeWidth={2.25}
                  fill="url(#clientSpendGradient)"
                  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)' }}
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>

      <section className="space-y-4">
        <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Padrão de Compra</h3>
            <p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">Quando este cliente costuma comprar, separando histórico de data e horário confiável.</p>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <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-4 flex items-start justify-between gap-4">
              <div>
                <h4 className="text-sm font-bold uppercase tracking-widest text-zinc-500 dark:text-dark-muted">Compras por Dia</h4>
                {hasWeekdayPattern && topWeekday && (
                  <p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs font-semibold text-zinc-600 dark:text-dark-muted">
                    <span className="h-2 w-2 rounded-full" style={{ backgroundColor: WEEKDAY_BAR_COLOR }} />
                    <span>Dia mais forte: <span className="text-zinc-900 dark:text-dark-text">{topWeekday.label}</span></span>
                    <span className="text-zinc-400 dark:text-dark-border">·</span>
                    <span>{topWeekday.value} {topWeekday.value === 1 ? 'pedido' : 'pedidos'}</span>
                    <span className="text-zinc-400 dark:text-dark-border">·</span>
                    <span>{getPatternShare(topWeekday.value, weekdayPatternTotal)}%</span>
                  </p>
                )}
              </div>
              <span className="shrink-0 rounded-full border border-zinc-200 bg-zinc-100 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide text-zinc-600 dark:border-dark-border dark:bg-white/5 dark:text-dark-muted">
                {purchaseWeekdayRangeLabel}
              </span>
            </div>
            {hasWeekdayPattern ? (
              <div className="h-52">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={purchaseWeekdays} margin={{ top: 8, right: 10, left: -18, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
                    <XAxis dataKey="label" stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
                    <YAxis allowDecimals={false} stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
                    <Tooltip content={<PatternTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
                    <Bar dataKey="value" radius={[4, 4, 0, 0]}>
                      {purchaseWeekdays.map(day => (
                        <Cell key={`weekday-${day.label}`} fill={WEEKDAY_BAR_COLOR} fillOpacity={0.62} stroke={WEEKDAY_BAR_COLOR} strokeOpacity={0.9} strokeWidth={1.25} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <div className="flex h-56 items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
                Sem compras no período.
              </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-4 flex items-start justify-between gap-4">
              <div>
                <h4 className="text-sm font-bold uppercase tracking-widest text-zinc-500 dark:text-dark-muted">Compras por Horário</h4>
                {hasHourPattern && topHour && (
                  <p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs font-semibold text-zinc-600 dark:text-dark-muted">
                    <span className="h-2 w-2 rounded-full" style={{ backgroundColor: HOUR_BAR_COLOR }} />
                    <span>Horário mais forte: <span className="text-zinc-900 dark:text-dark-text">{topHour.label}</span></span>
                    <span className="text-zinc-400 dark:text-dark-border">·</span>
                    <span>{topHour.value} {topHour.value === 1 ? 'pedido' : 'pedidos'}</span>
                    <span className="text-zinc-400 dark:text-dark-border">·</span>
                    <span>{getPatternShare(topHour.value, hourPatternTotal)}%</span>
                  </p>
                )}
              </div>
              <span className="shrink-0 rounded-full border border-zinc-200 bg-zinc-100 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide text-zinc-600 dark:border-dark-border dark:bg-white/5 dark:text-dark-muted">
                {purchaseHourRangeLabel}
              </span>
            </div>
            {hasHourPattern ? (
              <div className="h-52">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={purchaseHours} margin={{ top: 8, right: 10, left: -18, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
                    <XAxis
                      dataKey="label"
                      stroke={CHART_AXIS_COLOR}
                      fontSize={10}
                      tickLine={false}
                      axisLine={false}
                      interval={0}
                      tickFormatter={(value) => Number(String(value).replace('h', '')) % 3 === 0 ? String(value) : ''}
                    />
                    <YAxis allowDecimals={false} stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
                    <Tooltip content={<PatternTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
                    <Bar dataKey="value" radius={[4, 4, 0, 0]}>
                      {purchaseHours.map(hour => (
                        <Cell key={`hour-${hour.label}`} fill={HOUR_BAR_COLOR} fillOpacity={0.56} stroke={HOUR_BAR_COLOR} strokeOpacity={0.86} strokeWidth={1.1} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <div className="flex h-56 items-center justify-center px-6 text-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
                Sem horário de compra disponível para os últimos 60 dias.
              </div>
            )}
          </div>
        </div>
      </section>
{/* Orders List */}
<div className="flex flex-col gap-6">
  {paginatedOrders.length === 0 ? (
    <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-8 text-center shadow-sm">
      <p className="text-sm font-bold text-zinc-900 dark:text-dark-text">Nenhum pedido no período selecionado.</p>
      <p className="mt-1 text-sm text-zinc-500 dark:text-dark-muted">Altere o filtro de data para ver outros pedidos deste cliente.</p>
    </div>
  ) : paginatedOrders.map((group) => {
    const isExpanded = expandedOrderIds.has(group.orderId);

    return (
      <div key={group.orderId} className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm">
        <button
          type="button"
          onClick={() => toggleOrder(group.orderId)}
          aria-expanded={isExpanded}
          className="flex w-full cursor-pointer items-center justify-between gap-4 bg-zinc-50/50 px-4 py-3 text-left transition-colors hover:bg-zinc-100/80 dark:bg-dark-header dark:hover:bg-dark-input/60"
        >
          <div className="flex min-w-0 items-center gap-3">
            <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-zinc-200 bg-white text-brand-primary dark:border-dark-border dark:bg-dark-card">
              <Tag className="h-4 w-4" />
            </span>
            <div className="min-w-0">
              <h2 className="truncate text-sm font-bold uppercase tracking-wider text-zinc-700 dark:text-dark-text">
                Pedido ID: {group.orderId}
              </h2>
              <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs font-bold text-zinc-400 dark:text-dark-muted">
                <span>{group.items.length} {group.items.length === 1 ? 'item' : 'itens'}</span>
                {group.date && (
                  <span className="inline-flex items-center gap-1">
                    <Clock className="h-3 w-3" />
                    {group.date}
                  </span>
                )}
              </div>
            </div>
          </div>

          <div className="flex shrink-0 items-center gap-3">
            <div className="text-right">
              <p className="text-[10px] font-bold uppercase tracking-widest text-zinc-400 dark:text-dark-muted">Total</p>
              <p className="text-sm font-bold text-brand-primary">{formatCurrency(group.orderTotal)}</p>
            </div>
            <span className="flex h-8 w-8 items-center justify-center rounded-lg border border-zinc-200 bg-white text-zinc-500 transition-colors dark:border-dark-border dark:bg-dark-card dark:text-dark-muted">
              <ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
            </span>
          </div>
        </button>

        {isExpanded && (
          <div className="divide-y divide-zinc-100 dark:divide-dark-border">
            {group.items.map((order, index) => {
              const metadata = getOrderMetadata(order);

              return (
                <div key={`${order.ID_Produto}-${index}`} className="px-4 py-2 flex flex-col md:flex-row md:items-center justify-between gap-3 hover:bg-zinc-50/50 dark:hover:bg-dark-input/30 transition-colors">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <div className="flex items-center gap-1">
                        <Tag className="w-3 h-3 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted">ID: {order.ID_Produto}</span>
                      </div>
                      {order.Data_Pedido && (
                        <div className="flex items-center gap-1 ml-2">
                          <Clock className="w-3 h-3 text-zinc-400 dark:text-dark-muted" />
                          <span className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted">
                            Comprado: {order.Data_Pedido}
                          </span>
                        </div>
                      )}
                    </div>
                    <h3 className="text-sm font-bold text-zinc-900 dark:text-dark-text truncate mb-1">{order.Descricao_Produto}</h3>
                    
                    <div className="flex gap-4">
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <Package className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-zinc-500 dark:text-dark-muted font-medium">Qtd: <span className="text-zinc-900 dark:text-dark-text font-bold">{order.Quantidade}</span></span>
                      </div>
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <DollarSign className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-zinc-500 dark:text-dark-muted font-medium">Preço: <span className="text-zinc-900 dark:text-dark-text font-bold">{formatCurrency(order.Valor_Unitario)}</span></span>
                      </div>
                    </div>
                    {metadata.length > 0 && (
                      <div className="mt-2 flex flex-wrap gap-1.5">
                        {metadata.map(value => (
                          <span key={value} className="max-w-full break-all rounded-md border border-zinc-200 dark:border-dark-border px-2 py-0.5 text-[10px] font-bold text-zinc-500 dark:text-dark-muted">
                            {value}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  
                  <div className="text-right shrink-0">
                    <p className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest mb-0.5">Subtotal</p>
                    <p className="text-base font-bold text-zinc-900 dark:text-dark-text">{formatCurrency(order.Quantidade * order.Valor_Unitario)}</p>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  })}
      </div>

      <PaginationControls
        totalItems={groupedOrders.length}
        currentPage={safeCurrentPage}
        totalPages={totalPages}
        pageSize={ordersPerPage}
        pageSizeOptions={[5, 10, 20, 50]}
        itemLabel="pedidos"
        pageSizeLabel="pedidos por página"
        startIndex={startIndex}
        endIndex={Math.min(startIndex + ordersPerPage, groupedOrders.length)}
        onPageChange={setCurrentPage}
        onPageSizeChange={(pageSize) => {
          setOrdersPerPage(pageSize);
          setCurrentPage(1);
        }}
        className="px-6 py-4 border border-zinc-200 dark:border-dark-border rounded-2xl bg-white dark:bg-dark-card"
      />
      </div>
    </div>
  );
};

export default ClientDetails;
