import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { ChevronDown, ChevronUp, ChevronsUpDown } from 'lucide-react';
import { User } from '../types';

interface SellerStat {
  user: User;
  total: number;
  avgScore: string;
  conversionRate: string;
  responseTime: string;
}

interface SellersTableProps {
  data: SellerStat[];
}

export const SellersTable: React.FC<SellersTableProps> = ({ data }) => {
  const navigate = useNavigate();
  const [sortKey, setSortKey] = useState<keyof SellerStat>('total');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');

  const handleSort = (key: keyof SellerStat) => {
    if (sortKey === key) {
      setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
    } else {
      setSortKey(key);
      setSortDirection('desc');
    }
  };

  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => {
      const aVal = a[sortKey];
      const bVal = b[sortKey];
      
      if (typeof aVal === 'string' && typeof bVal === 'string') {
        return sortDirection === 'asc' 
          ? aVal.localeCompare(bVal) 
          : bVal.localeCompare(aVal);
      }
      
      if (typeof aVal === 'number' && typeof bVal === 'number') {
        return sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
      }

      // Handle user object (sort by name)
      if (sortKey === 'user') {
        return sortDirection === 'asc' 
          ? a.user.name.localeCompare(b.user.name) 
          : b.user.name.localeCompare(a.user.name);
      }

      return 0;
    });
  }, [data, sortKey, sortDirection]);

  const SortIcon = ({ column }: { column: string }) => {
    if (sortKey !== column) return <ChevronsUpDown size={14} className="text-zinc-300 dark:text-dark-muted" />;
    return sortDirection === 'asc' ? <ChevronUp size={14} className="text-brand-yellow" /> : <ChevronDown size={14} className="text-brand-yellow" />;
  };

  return (
    <div className="bg-white dark:bg-dark-card rounded-2xl shadow-sm border border-zinc-100 dark:border-dark-border overflow-hidden transition-colors">
      <div className="px-6 py-5 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center">
        <h3 className="font-bold text-zinc-800 dark:text-dark-text">Ranking de Vendedores</h3>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-zinc-50/50 dark:bg-dark-bg/50 text-zinc-500 dark:text-dark-muted text-xs uppercase tracking-wider">
              <th 
                className="px-6 py-4 font-semibold cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
                onClick={() => handleSort('user')}
              >
                <div className="flex items-center gap-2">Usuário <SortIcon column="user" /></div>
              </th>
              <th 
                className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
                onClick={() => handleSort('total')}
              >
                <div className="flex items-center justify-center gap-2">Atendimentos <SortIcon column="total" /></div>
              </th>
              <th 
                className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
                onClick={() => handleSort('avgScore')}
              >
                <div className="flex items-center justify-center gap-2">Nota Média <SortIcon column="avgScore" /></div>
              </th>
               <th 
                className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
                onClick={() => handleSort('responseTime')}
              >
                <div className="flex items-center justify-center gap-2">Tempo Resp. <SortIcon column="responseTime" /></div>
              </th>
              <th 
                className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-zinc-50 dark:hover:bg-dark-border select-none"
                onClick={() => handleSort('conversionRate')}
              >
                <div className="flex items-center justify-center gap-2">Conversão <SortIcon column="conversionRate" /></div>
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
            {sortedData.map((item, idx) => (
              <tr 
                key={item.user.id} 
                className="hover:bg-yellow-50/10 dark:hover:bg-yellow-400/5 transition-colors cursor-pointer group"
                onClick={() => navigate(`/users/${item.user.slug || item.user.id}`)}
              >
                <td className="px-6 py-4">
                  <div className="flex items-center gap-3">
                    <span className="text-xs text-zinc-400 dark:text-dark-muted font-mono w-4">#{idx + 1}</span>
                    <img 
                      src={item.user.avatar_url 
                        ? (item.user.avatar_url.startsWith('http') ? item.user.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${item.user.avatar_url}`)
                        : `https://ui-avatars.com/api/?name=${encodeURIComponent(item.user.name)}&background=random`} 
                      alt="" 
                      className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-dark-border" 
                    />
                    <div>
                      <div className="font-semibold text-zinc-900 dark:text-dark-text group-hover:text-yellow-600 dark:group-hover:text-brand-yellow transition-colors">{item.user.name}</div>
                      <div className="text-xs text-zinc-500 dark:text-dark-muted">{item.user.email}</div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text font-medium">
                  {item.total}
                </td>
                <td className="px-6 py-4 text-center">
                  <span className={`inline-flex px-2 py-1 rounded-full text-xs font-bold ${parseFloat(item.avgScore) >= 80 ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'}`}>
                    {item.avgScore}
                  </span>
                </td>
                 <td className="px-6 py-4 text-center text-zinc-600 dark:text-dark-text text-sm">
                  {item.responseTime} min
                </td>
                <td className="px-6 py-4 text-center">
                  <div className="flex items-center justify-center gap-2">
                    <div className="w-16 bg-zinc-100 dark:bg-dark-bg rounded-full h-1.5 overflow-hidden border dark:border-dark-border">
                      <div className="bg-brand-yellow h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
                    </div>
                    <span className="text-xs font-semibold text-zinc-700 dark:text-dark-text">{item.conversionRate}%</span>
                  </div>
                </td>
              </tr>
            ))}
            {sortedData.length === 0 && (
              <tr>
                <td colSpan={5} className="px-6 py-8 text-center text-zinc-400 dark:text-dark-muted italic">Nenhum dado disponível para o período selecionado.</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};