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[];
}

type SortKey = keyof SellerStat | 'name'; // 'name' is inside user object

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

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

  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => {
      let aValue: any = a[sortKey as keyof SellerStat];
      let bValue: any = b[sortKey as keyof SellerStat];

      if (sortKey === 'name') {
        aValue = a.user.name;
        bValue = b.user.name;
      } else {
        // Convert strings like "85.5" to numbers for sorting
        aValue = parseFloat(aValue as string);
        bValue = parseFloat(bValue as string);
      }

      if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
      if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });
  }, [data, sortKey, sortDirection]);

  const SortIcon = ({ column }: { column: SortKey }) => {
    if (sortKey !== column) return <ChevronsUpDown size={14} className="text-slate-300" />;
    return sortDirection === 'asc' ? <ChevronUp size={14} className="text-blue-500" /> : <ChevronDown size={14} className="text-blue-500" />;
  };

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
      <div className="px-6 py-5 border-b border-slate-100 flex justify-between items-center">
        <h3 className="font-bold text-slate-800">Ranking de Vendedores</h3>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-slate-50/50 text-slate-500 text-xs uppercase tracking-wider">
              <th 
                className="px-6 py-4 font-semibold cursor-pointer hover:bg-slate-50 select-none"
                onClick={() => handleSort('name')}
              >
                <div className="flex items-center gap-2">Usuário <SortIcon column="name" /></div>
              </th>
              <th 
                className="px-6 py-4 font-semibold text-center cursor-pointer hover:bg-slate-50 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-slate-50 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-slate-50 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-slate-50 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-slate-100">
            {sortedData.map((item, idx) => (
              <tr 
                key={item.user.id} 
                className="hover:bg-blue-50/30 transition-colors cursor-pointer group"
                onClick={() => navigate(`/users/${item.user.id}`)}
              >
                <td className="px-6 py-4">
                  <div className="flex items-center gap-3">
                    <span className="text-xs text-slate-400 font-mono w-4">#{idx + 1}</span>
                    <img src={item.user.avatar_url} alt="" className="w-9 h-9 rounded-full object-cover border border-slate-200" />
                    <div>
                      <div className="font-semibold text-slate-900 group-hover:text-blue-600 transition-colors">{item.user.name}</div>
                      <div className="text-xs text-slate-500">{item.user.email}</div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 text-center text-slate-600 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' : parseFloat(item.avgScore) >= 60 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'}`}>
                    {item.avgScore}
                  </span>
                </td>
                 <td className="px-6 py-4 text-center text-slate-600 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-slate-100 rounded-full h-1.5 overflow-hidden">
                      <div className="bg-blue-500 h-1.5 rounded-full" style={{ width: `${item.conversionRate}%` }}></div>
                    </div>
                    <span className="text-xs font-semibold text-slate-700">{item.conversionRate}%</span>
                  </div>
                </td>
              </tr>
            ))}
            {sortedData.length === 0 && (
              <tr>
                <td colSpan={5} className="px-6 py-8 text-center text-slate-400 italic">Nenhum dado disponível para o período selecionado.</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};