'use client';

import { useState } from 'react';
import { ArrowUpDown, UserPlus, Users, Search } from 'lucide-react';

interface HistoryItem {
  id: string;
  createdAt: string;
  referrerUserId: string;
  referredUserId: string;
  status: string;
  depth: number;
  referred: {
    id: string;
    email: string;
    firstName: string | null;
    lastName: string | null;
    createdAt: string;
  };
}

interface ReferralHistoryTableProps {
  history: HistoryItem[];
  isLoading?: boolean;
  total?: number;
  onPageChange?: (page: number) => void;
  currentPage?: number;
}

export function ReferralHistoryTable({ history, isLoading, total, onPageChange, currentPage = 1 }: ReferralHistoryTableProps) {
  const [sortField, setSortField] = useState<string>('createdAt');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDir('desc');
    }
  };

  const sorted = [...history].sort((a, b) => {
    const aVal = a[sortField as keyof typeof a] ?? '';
    const bVal = b[sortField as keyof typeof b] ?? '';
    const cmp = typeof aVal === 'number' ? (aVal as number) - (bVal as number) : String(aVal).localeCompare(String(bVal));
    return sortDir === 'asc' ? cmp : -cmp;
  });

  if (isLoading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="animate-pulse rounded-lg border border-white/10 bg-white/5 p-4">
            <div className="flex items-center gap-4">
              <div className="h-4 w-24 rounded bg-white/10" />
              <div className="h-4 w-32 rounded bg-white/10" />
              <div className="h-4 w-20 rounded bg-white/10" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  if (history.length === 0) {
    return (
      <div className="rounded-lg border border-white/10 bg-white/5 p-8 text-center">
        <UserPlus className="mx-auto h-12 w-12 text-slate-600" />
        <p className="mt-3 text-sm text-slate-500">No referral history yet.</p>
        <p className="text-xs text-slate-600">Your referral history will appear here when people sign up using your link.</p>
      </div>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-left text-sm">
        <thead>
          <tr className="border-b border-white/10 text-xs uppercase tracking-wider text-slate-500">
            <th className="pb-3 pr-4 font-medium">
              <button onClick={() => handleSort('createdAt')} className="flex items-center gap-1 hover:text-slate-300" type="button">
                Date <ArrowUpDown className="h-3 w-3" />
              </button>
            </th>
            <th className="pb-3 pr-4 font-medium">Referred User</th>
            <th className="pb-3 pr-4 font-medium">Email</th>
            <th className="pb-3 pr-4 font-medium">Status</th>
            <th className="pb-3 font-medium">Level</th>
          </tr>
        </thead>
        <tbody>
          {sorted.map((item) => (
            <tr key={item.id} className="border-b border-white/5 transition-colors hover:bg-white/5">
              <td className="py-3 pr-4 text-slate-400">
                {new Date(item.createdAt).toLocaleDateString('en-US', {
                  month: 'short',
                  day: 'numeric',
                  year: 'numeric',
                })}
              </td>
              <td className="py-3 pr-4">
                <div className="flex items-center gap-2">
                  <div className="flex h-7 w-7 items-center justify-center rounded-full bg-blue-500/20 text-blue-400">
                    <Users className="h-3.5 w-3.5" />
                  </div>
                  <span className="text-slate-200">
                    {item.referred.firstName || item.referred.lastName
                      ? `${item.referred.firstName ?? ''} ${item.referred.lastName ?? ''}`.trim()
                      : 'Anonymous'}
                  </span>
                </div>
              </td>
              <td className="py-3 pr-4 text-slate-400">{item.referred.email}</td>
              <td className="py-3 pr-4">
                <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
                  item.status === 'ACTIVE' ? 'bg-emerald-500/10 text-emerald-400' :
                  item.status === 'PENDING' ? 'bg-amber-500/10 text-amber-400' :
                  'bg-slate-500/10 text-slate-400'
                }`}>
                  {item.status}
                </span>
              </td>
              <td className="py-3 text-slate-400">Level {item.depth}</td>
            </tr>
          ))}
        </tbody>
      </table>

      {total && total > 20 && onPageChange && (
        <div className="mt-4 flex items-center justify-between">
          <p className="text-xs text-slate-500">
            Showing {(currentPage - 1) * 20 + 1}-{Math.min(currentPage * 20, total)} of {total}
          </p>
          <div className="flex gap-2">
            <button
              onClick={() => onPageChange(currentPage - 1)}
              disabled={currentPage <= 1}
              className="rounded-lg border border-white/10 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/5 disabled:opacity-50"
              type="button"
            >
              Previous
            </button>
            <button
              onClick={() => onPageChange(currentPage + 1)}
              disabled={currentPage * 20 >= total}
              className="rounded-lg border border-white/10 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/5 disabled:opacity-50"
              type="button"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
