import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Search, ChevronRight, Filter, ChevronLeft, Download } from 'lucide-react';
import type { OrderData, DateRange, RfmAnalytics, RfmClient } from '../types';
import { exportToCSV, fetchRfmAnalytics } from '../dataService';
import DateRangePicker from '../components/DateRangePicker';
import { buildClientsSummary, type ClientSortOption, type ClientSummary } from '../analytics/clients';

const clientTypeStyles: Record<string, string> = {
  '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 = [
  '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 Clients = () => {
  const { dateRange, setDateRange, ordersData } = useOutletContext<{ 
    dateRange: DateRange, 
    setDateRange: (range: DateRange) => void, 
    ordersData: OrderData[] 
  }>();
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<ClientSortOption>('recent');
  const [clientTypeFilter, setClientTypeFilter] = useState('all');
  const [rfmAnalytics, setRfmAnalytics] = useState<RfmAnalytics | null>(null);
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

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

    const loadRfm = async () => {
      const data = await fetchRfmAnalytics(dateRange);
      if (isMounted) setRfmAnalytics(data);
    };

    void loadRfm();

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

  const rfmClientsByIdentity = useMemo(() => {
    const map = new Map<string, RfmClient>();

    (rfmAnalytics?.clients || []).forEach(client => {
      if (client.phone) map.set(`phone:${client.phone}`, client);
      map.set(`name:${client.name.toLowerCase()}`, client);
    });

    return map;
  }, [rfmAnalytics]);

  const allClientsData = useMemo(() => {
    const localClients = buildClientsSummary(ordersData, dateRange, searchTerm, sortBy);
    const enrichedClients = localClients.map(client => {
      const rfmClient = (client.phone && rfmClientsByIdentity.get(`phone:${client.phone}`)) ||
        rfmClientsByIdentity.get(`name:${client.name.toLowerCase()}`);

      if (!rfmClient) return client;

      return {
        ...client,
        clientType: backendSegmentToClientType[rfmClient.segmentKey] || client.clientType,
        rfmScore: rfmClient.rfmScore,
        rfmPriority: getRfmPriority(rfmClient)
      };
    });

    return sortClients(enrichedClients, sortBy);
  }, [searchTerm, sortBy, ordersData, dateRange, rfmClientsByIdentity]);

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

  return (
    <div className="space-y-6">
      <div className="flex flex-col xl:flex-row xl:items-center justify-between gap-4">
        <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">Métricas de engajamento e histórico de consumo dos seus clientes.</p>
        </div>
        
        <div className="flex flex-col sm:flex-row flex-wrap gap-3 items-center justify-start xl:justify-end">
          <DateRangePicker 
            dateRange={dateRange} 
            onChange={(range) => {
              setDateRange(range);
              setCurrentPage(1);
            }}
          />
          
          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 text-zinc-400 dark:text-dark-muted w-4 h-4" />
            <select 
              value={sortBy}
              onChange={(e) => {
                setSortBy(e.target.value as ClientSortOption);
                setCurrentPage(1);
              }}
              className="appearance-none bg-dark-card border border-dark-border text-dark-text text-sm rounded-xl pl-9 pr-8 py-2.5 focus:outline-none focus:border-brand-primary transition-colors shadow-sm cursor-pointer"
            >
              <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 RFM</option>
              <option value="items_desc">Mais Produtos</option>
              <option value="items_asc">Menos Produtos</option>
            </select>
          </div>

          <div className="relative w-full sm:w-auto">
            <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 sm:w-64 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>
          
          <button
            onClick={() => {
              const exportData = clientsData.map(client => ({
                'Nome do Cliente': client.name,
                'Telefone/WhatsApp': client.phone || 'N/A',
                'Tipo de Cliente': client.clientType,
                'RFM': client.rfmScore,
                'Total Gasto (R$)': client.totalSpent.toFixed(2).replace('.', ','),
                'Ticket Médio (R$)': client.averageTicket.toFixed(2).replace('.', ','),
                'Produtos Comprados': client.totalItems,
                'Total de Pedidos': client.orderCount,
                'Última Compra': new Date(client.lastPurchase).toLocaleDateString('pt-BR')
              }));
              exportToCSV(exportData, `clientes_${new Date().toISOString().split('T')[0]}.csv`);
            }}
            className="flex items-center justify-center gap-2 bg-dark-card border border-dark-border px-4 py-2.5 rounded-xl shadow-sm hover:border-brand-primary transition-colors text-sm font-medium text-dark-text cursor-pointer"
            title="Exportar para CSV"
          >
            <Download size={16} className="text-brand-primary" />
            <span className="hidden sm:inline">Exportar</span>
          </button>
        </div>
      </div>

      <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-4 shadow-sm">
        <div className="mb-4">
          <div>
            <h2 className="text-sm font-bold text-zinc-900 dark:text-dark-text">Tipos de Clientes</h2>
            <p className="text-xs font-semibold text-zinc-500 dark:text-dark-muted">
              Classificação RFM sincronizada com a página RFM quando disponível.
            </p>
          </div>
        </div>

        <div className="flex flex-wrap gap-2">
          {clientTypes.map(type => (
            <button
              key={type}
              onClick={() => selectClientType(type)}
              title={clientTypeFilter === type ? 'Clique para limpar o filtro' : `Filtrar por ${type}`}
              className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-bold transition-all cursor-pointer hover:-translate-y-0.5 ${
                clientTypeFilter === type
                  ? `${clientTypeStyles[type]} ring-1 ring-current shadow-sm`
                  : clientTypeStyles[type]
              }`}
            >
              <span>{type}</span>
              <span className="rounded-full bg-black/20 px-2 py-0.5 text-[10px]">{clientTypeCounts[type] || 0}</span>
            </button>
          ))}
        </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]">RFM</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.name} 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">
                    {client.totalItems} un. ({client.orderCount} {client.orderCount === 1 ? 'pedido' : 'pedidos'})
                  </td>
                  <td className="px-6 py-2.5 text-right">
                    <Link 
                      to={`/clients/${encodeURIComponent(client.name)}`}
                      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;
