import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Search, ChevronRight, Filter, ChevronLeft, X } from 'lucide-react';
import type { ClientAnalyticsItem, ClientFilterOptions, ClientMetadataFilters, DateRange, RfmAnalytics, RfmClient } from '../types';
import { fetchClientAnalytics, fetchClientFilterOptions, fetchRfmAnalytics, getCachedClientAnalytics, getCachedClientFilterOptions, getCachedRfmAnalytics } from '../dataService';
import { endOfLocalDay, formatDateParam, parseLocalDateInput, rangeForDay, rangeForLastDays, rangeForPreviousDay, startOfLocalDay } from '../dateRanges';
import type { ClientSortOption, ClientSummary } from '../analytics/clients';

const clientTypeStyles: Record<string, string> = {
  'Sem análise': 'border-zinc-600/30 bg-zinc-600/15 text-zinc-300',
  'Campeão': 'border-emerald-500/30 bg-emerald-500/15 text-emerald-300',
  'Potencial Leal': 'border-sky-500/30 bg-sky-500/15 text-sky-300',
  'Novo Cliente': 'border-cyan-500/30 bg-cyan-500/15 text-cyan-300',
  'Cliente Leal': 'border-blue-500/30 bg-blue-500/15 text-blue-300',
  'Precisa de Atenção': 'border-amber-500/30 bg-amber-500/15 text-amber-300',
  'Quase Dormindo': 'border-orange-500/30 bg-orange-500/15 text-orange-300',
  'Em Risco': 'border-rose-500/30 bg-rose-500/15 text-rose-300',
  'Hibernando': 'border-fuchsia-500/30 bg-fuchsia-500/15 text-fuchsia-300',
  'Perdido': 'border-zinc-500/30 bg-zinc-500/15 text-zinc-300'
};

const clientTypes = [
  'Sem análise',
  'Campeão',
  'Potencial Leal',
  'Novo Cliente',
  'Cliente Leal',
  'Precisa de Atenção',
  'Quase Dormindo',
  'Em Risco',
  'Hibernando',
  'Perdido'
];

const backendSegmentToClientType: Record<string, string> = {
  champions: 'Campeão',
  potential_loyalists: 'Potencial Leal',
  new_customers: 'Novo Cliente',
  loyal_customers: 'Cliente Leal',
  need_attention: 'Precisa de Atenção',
  about_to_sleep: 'Quase Dormindo',
  at_risk: 'Em Risco',
  hibernating: 'Hibernando',
  lost: 'Perdido'
};

const getRfmPriority = (client: Pick<RfmClient, 'recencyScore' | 'valueScore' | 'monetaryScore'>) => {
  return (client.recencyScore * 100) + (client.valueScore * 10) + client.monetaryScore;
};

const sortClients = (clients: ClientSummary[], sortBy: ClientSortOption) => {
  return [...clients].sort((a, b) => {
    switch (sortBy) {
      case 'recent': return b.lastPurchase - a.lastPurchase;
      case 'spent_desc': return b.totalSpent - a.totalSpent;
      case 'spent_asc': return a.totalSpent - b.totalSpent;
      case 'ticket_desc': return b.averageTicket - a.averageTicket;
      case 'ticket_asc': return a.averageTicket - b.averageTicket;
      case 'rfm_priority': return b.rfmPriority - a.rfmPriority;
      case 'items_desc': return b.totalItems - a.totalItems;
      case 'items_asc': return a.totalItems - b.totalItems;
      default: return 0;
    }
  });
};

const emptyClientFilters: ClientMetadataFilters = {
  marketplace: '',
  canal_venda: '',
  seller: ''
};

const emptyClientFilterOptions: ClientFilterOptions = {
  marketplaces: [],
  salesChannels: [],
  sellers: []
};

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 Clients = () => {
  const { dateRange, setDateRange } = useOutletContext<{ 
    dateRange: DateRange, 
    setDateRange: (range: DateRange) => void
  }>();
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<ClientSortOption>('recent');
  const [clientTypeFilter, setClientTypeFilter] = useState('all');
  const [metadataFilters, setMetadataFilters] = useState<ClientMetadataFilters>(emptyClientFilters);
  const initialFilterOptions = getCachedClientFilterOptions(dateRange);
  const initialClientAnalytics = getCachedClientAnalytics(dateRange, emptyClientFilters);
  const initialRfmAnalytics = getCachedRfmAnalytics(dateRange, emptyClientFilters);
  const [filterOptions, setFilterOptions] = useState<ClientFilterOptions>(initialFilterOptions || emptyClientFilterOptions);
  const [isFilterMenuOpen, setIsFilterMenuOpen] = useState(false);
  const filterMenuRef = useRef<HTMLDivElement>(null);
  const [rfmAnalytics, setRfmAnalytics] = useState<RfmAnalytics | null>(initialRfmAnalytics || null);
  const [clientAnalytics, setClientAnalytics] = useState<ClientAnalyticsItem[]>(initialClientAnalytics || []);
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

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

    const loadClients = async () => {
      const cachedOptions = getCachedClientFilterOptions(dateRange);
      const cachedClients = getCachedClientAnalytics(dateRange, metadataFilters);
      const cachedRfm = getCachedRfmAnalytics(dateRange, metadataFilters);

      if (isMounted) {
        if (cachedOptions) setFilterOptions(cachedOptions);
        if (cachedClients) setClientAnalytics(cachedClients);
        setRfmAnalytics(cachedRfm || null);
      }

      const filterOptionsPromise = fetchClientFilterOptions(dateRange, { force: true });
      const clientsPromise = fetchClientAnalytics(dateRange, metadataFilters);
      const rfmPromise = fetchRfmAnalytics(dateRange, metadataFilters);
      const [options, clientsData] = await Promise.all([filterOptionsPromise, clientsPromise]);

      if (isMounted) {
        setFilterOptions(options);
        setClientAnalytics(clientsData);
      }

      const rfmData = await rfmPromise;
      if (isMounted) {
        setRfmAnalytics(rfmData);
      }
    };

    void loadClients();

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

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

    const handlePointerDown = (event: PointerEvent) => {
      if (!filterMenuRef.current?.contains(event.target as Node)) {
        setIsFilterMenuOpen(false);
      }
    };
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsFilterMenuOpen(false);
      }
    };

    document.addEventListener('pointerdown', handlePointerDown);
    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('pointerdown', handlePointerDown);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isFilterMenuOpen]);

  const allClientsData = useMemo(() => {
    const normalizedSearch = searchTerm.trim().toLowerCase();
    const rfmByCustomerKey = new Map((rfmAnalytics?.clients || []).map(client => [client.customerKey, client]));
    const clients = clientAnalytics.map((client): ClientSummary => {
      const rawClient = client as ClientAnalyticsItem & {
        client_token?: string;
        customer_key?: string;
        last_purchase_date?: string;
        order_count?: number;
        quantity_purchased?: number;
        total_spent?: number;
      };
      const rfmClient = rfmByCustomerKey.get(client.customerKey);
      const orderCount = Number(client.orderCount ?? rawClient.order_count ?? 0);
      const totalSpent = Number(client.totalSpent ?? rawClient.total_spent ?? 0);
      const totalItems = Number(client.quantityPurchased ?? rawClient.quantity_purchased ?? 0);
      const lastPurchaseDate = client.lastPurchaseDate ?? rawClient.last_purchase_date;

      return {
        customerKey: client.customerKey ?? rawClient.customer_key ?? '',
        clientToken: client.clientToken ?? rawClient.client_token ?? '',
        name: client.name,
        phone: client.phone,
        totalSpent,
        averageTicket: orderCount ? totalSpent / orderCount : 0,
        totalItems,
        orderCount,
        lastPurchase: lastPurchaseDate ? new Date(lastPurchaseDate).getTime() : 0,
        clientType: rfmClient ? (backendSegmentToClientType[rfmClient.segmentKey] || rfmClient.segmentLabel) : 'Sem análise',
        rfmScore: rfmClient?.rfmScore || '000',
        rfmPriority: rfmClient ? getRfmPriority(rfmClient) : 0
      };
    });

    const filteredClients = normalizedSearch
      ? clients.filter(client =>
        client.name.toLowerCase().includes(normalizedSearch) ||
        client.phone.toLowerCase().includes(normalizedSearch)
      )
      : clients;

    return sortClients(filteredClients, sortBy);
  }, [clientAnalytics, searchTerm, sortBy, rfmAnalytics]);

  const clientsData = useMemo(() => {
    if (clientTypeFilter === 'all') return allClientsData;
    return allClientsData.filter(client => client.clientType === clientTypeFilter);
  }, [allClientsData, clientTypeFilter]);

  const clientTypeCounts = useMemo(() => {
    return clientTypes.reduce<Record<string, number>>((counts, type) => {
      counts[type] = allClientsData.filter(client => client.clientType === type).length;
      return counts;
    }, {});
  }, [allClientsData]);

  // Pagination logic
  const totalPages = Math.ceil(clientsData.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedData = clientsData.slice(startIndex, startIndex + itemsPerPage);

  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 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 selectClientType = (type: string) => {
    setClientTypeFilter(current => current === type ? 'all' : type);
    setCurrentPage(1);
  };

  const updateMetadataFilter = (key: keyof ClientMetadataFilters, value: string) => {
    setMetadataFilters(current => ({
      ...current,
      [key]: value
    }));
    setCurrentPage(1);
  };

  const resetMetadataFilters = () => {
    setMetadataFilters(emptyClientFilters);
    setClientTypeFilter('all');
    setSortBy('recent');
    setCurrentPage(1);
  };

  const getSellerOptionLabel = (seller: ClientFilterOptions['sellers'][number]) => {
    if (seller.id && seller.name && seller.id !== seller.name) return `${seller.name} (${seller.id})`;
    return seller.name || seller.id;
  };

  const marketplaceOptions = useMemo(() => {
    if (!metadataFilters.marketplace || filterOptions.marketplaces.includes(metadataFilters.marketplace)) {
      return filterOptions.marketplaces;
    }

    return [metadataFilters.marketplace, ...filterOptions.marketplaces];
  }, [filterOptions.marketplaces, metadataFilters.marketplace]);

  const salesChannelOptions = useMemo(() => {
    if (!metadataFilters.canal_venda || filterOptions.salesChannels.includes(metadataFilters.canal_venda)) {
      return filterOptions.salesChannels;
    }

    return [metadataFilters.canal_venda, ...filterOptions.salesChannels];
  }, [filterOptions.salesChannels, metadataFilters.canal_venda]);

  const sellerOptions = useMemo(() => {
    if (!metadataFilters.seller || filterOptions.sellers.some(seller => seller.value === metadataFilters.seller)) {
      return filterOptions.sellers;
    }

    const fallbackSeller = metadataFilters.seller.startsWith('id:')
      ? { value: metadataFilters.seller, id: metadataFilters.seller.slice(3), name: metadataFilters.seller.slice(3) }
      : { value: metadataFilters.seller, id: '', name: metadataFilters.seller.replace(/^name:/, '') };

    return [fallbackSeller, ...filterOptions.sellers];
  }, [filterOptions.sellers, metadataFilters.seller]);

  const activeMetadataFilters = useMemo(() => {
    const filters = [];
    const selectedSeller = sellerOptions.find(seller => seller.value === metadataFilters.seller);

    if (metadataFilters.marketplace) {
      filters.push({ key: 'marketplace' as const, label: `Marketplace: ${metadataFilters.marketplace}` });
    }

    if (metadataFilters.canal_venda) {
      filters.push({ key: 'canal_venda' as const, label: `Canal: ${metadataFilters.canal_venda}` });
    }

    if (metadataFilters.seller) {
      filters.push({ key: 'seller' as const, label: `Vendedor: ${selectedSeller ? getSellerOptionLabel(selectedSeller) : metadataFilters.seller}` });
    }

    return filters;
  }, [metadataFilters, sellerOptions]);
  const activeFilterCount = activeMetadataFilters.length +
    (clientTypeFilter === 'all' ? 0 : 1) +
    (sortBy === 'recent' ? 0 : 1);
  const hasActiveFilters = activeFilterCount > 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>
          <h1 className="text-2xl font-bold mb-2 text-zinc-900 dark:text-dark-text">Clientes</h1>
          <p className="text-zinc-500 dark:text-dark-muted font-medium lg:whitespace-nowrap">Métricas de engajamento e histórico de consumo dos seus clientes.</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 cliente..." 
              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-black">
                  {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={(e) => {
                        setSortBy(e.target.value as ClientSortOption);
                        setCurrentPage(1);
                      }}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="recent">Mais Recentes</option>
                      <option value="spent_desc">Maior Gasto</option>
                      <option value="spent_asc">Menor Gasto</option>
                      <option value="ticket_desc">Maior Ticket Médio</option>
                      <option value="ticket_asc">Menor Ticket Médio</option>
                      <option value="rfm_priority">Prioridade RFV</option>
                      <option value="items_desc">Mais Produtos</option>
                      <option value="items_asc">Menos Produtos</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">
                    Marketplace
                    <select
                      value={metadataFilters.marketplace}
                      onChange={(event) => updateMetadataFilter('marketplace', event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="">Todos</option>
                      {marketplaceOptions.map(marketplace => (
                        <option key={marketplace} value={marketplace}>{marketplace}</option>
                      ))}
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Canal de venda
                    <select
                      value={metadataFilters.canal_venda}
                      onChange={(event) => updateMetadataFilter('canal_venda', event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="">Todos</option>
                      {salesChannelOptions.map(channel => (
                        <option key={channel} value={channel}>{channel}</option>
                      ))}
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Vendedor
                    <select
                      value={metadataFilters.seller}
                      onChange={(event) => updateMetadataFilter('seller', event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="">Todos</option>
                      {!sellerOptions.length && (
                        <option value="" disabled>Nenhum vendedor encontrado</option>
                      )}
                      {sellerOptions.map(seller => (
                        <option key={seller.value} value={seller.value}>{getSellerOptionLabel(seller)}</option>
                      ))}
                    </select>
                  </label>

                  <label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
                    Tipo de cliente
                    <select
                      value={clientTypeFilter}
                      onChange={(event) => selectClientType(event.target.value)}
                      className={`${filterSelectClassName} mt-1`}
                    >
                      <option value="all">Todos</option>
                      {clientTypes.map(type => (
                        <option key={type} value={type}>
                          {type} ({clientTypeCounts[type] || 0})
                        </option>
                      ))}
                    </select>
                  </label>
                </div>

                <div className="mt-3 flex items-center justify-between border-t border-dark-border pt-3">
                  <button
                    type="button"
                    onClick={resetMetadataFilters}
                    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-black transition-opacity hover:opacity-90"
                  >
                    Aplicar
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <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]">Posição</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Nome do Cliente</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Tipo</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">RFV</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Total Gasto</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Ticket Médio</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Produtos Comprados</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((client, index) => (
                <tr key={client.customerKey} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors group">
                  <td className="px-6 py-2.5">
                    <span className="inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold bg-zinc-100 dark:bg-dark-border text-zinc-500 dark:text-dark-muted">
                      {startIndex + index + 1}
                    </span>
                  </td>
                  <td className="px-6 py-2.5 font-semibold text-zinc-900 dark:text-dark-text">{client.name}</td>
                  <td className="px-6 py-2.5">
                    <span className={`inline-flex rounded-full border px-3 py-1 text-xs font-bold ${clientTypeStyles[client.clientType] || clientTypeStyles.Perdido}`}>
                      {client.clientType}
                    </span>
                  </td>
                  <td className="px-6 py-2.5">
                    <div className="flex items-center gap-1">
                      {client.rfmScore.split('').map((score, scoreIndex) => (
                        <span
                          key={`${client.name}-${scoreIndex}`}
                          className="inline-flex h-6 w-6 items-center justify-center rounded-md border border-dark-border bg-dark-input text-[11px] font-bold text-dark-text"
                        >
                          {score}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td className="px-6 py-2.5 text-brand-primary font-bold">{formatCurrency(client.totalSpent)}</td>
                  <td className="px-6 py-2.5 text-zinc-700 dark:text-dark-text font-semibold">{formatCurrency(client.averageTicket)}</td>
                  <td className="px-6 py-2.5 text-zinc-500 dark:text-dark-muted text-xs font-medium">
                    {formatNumber(client.totalItems)} un. ({formatNumber(client.orderCount)} {client.orderCount === 1 ? 'pedido' : 'pedidos'})
                  </td>
                  <td className="px-6 py-2.5 text-right">
                    <Link 
                      to={`/clients/${encodeURIComponent(client.clientToken)}`}
                      className="inline-flex items-center text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity cursor-pointer"
                    >
                      Ver detalhes
                      <ChevronRight className="w-3.5 h-3.5 ml-1" />
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        {/* Pagination Controls */}
        <div className="px-6 py-4 border-t border-zinc-100 dark:border-dark-border flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-2 text-sm text-zinc-500 dark:text-dark-muted">
            <span>Mostrar</span>
            <select
              value={itemsPerPage}
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value));
                setCurrentPage(1);
              }}
              className="bg-dark-card border border-dark-border rounded-lg px-2 py-1 focus:outline-none focus:border-brand-primary cursor-pointer text-dark-text"
            >
              <option value={10}>10</option>
              <option value={20}>20</option>
              <option value={50}>50</option>
              <option value={100}>100</option>
            </select>
            <span>itens por página</span>
          </div>
          
          <div className="flex items-center gap-4 text-sm">
            <span className="text-zinc-500 dark:text-dark-muted">
              Mostrando {clientsData.length > 0 ? startIndex + 1 : 0} a {Math.min(startIndex + itemsPerPage, clientsData.length)} de {clientsData.length} clientes
            </span>
            <div className="flex gap-1">
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages || totalPages === 0}
                className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Clients;
