'use client';

import { useState } from 'react';
import { ArrowUpDown, DollarSign, Clock, CheckCircle, XCircle, Search } from 'lucide-react';

interface IncomeItem {
  id: string;
  userId: string;
  referralId: string | null;
  amount: number;
  commissionRate: number;
  currency: string;
  status: string;
  paidAt: string | null;
  createdAt: string;
  referral: {
    referred: { id: string; email: string; firstName: string | null; lastName: string | null };
  } | null;
  transactions: Array<{
    id: string;
    amount: number;
    status: string;
    description: string | null;
    createdAt: string;
  }>;
}

interface IncomeTableProps {
  income: IncomeItem[];
  isLoading?: boolean;
  total?: number;
  onPageChange?: (page: number) => void;
  currentPage?: number;
}

const STATUS_COLORS: Record<string, string> = {
  PAID: 'text-emerald-400 bg-emerald-500/10',
  PENDING: 'text-amber-400 bg-amber-500/10',
  FAILED: 'text-red-400 bg-red-500/10',
};

const STATUS_ICONS: Record<string, any> = {
  PAID: CheckCircle,
  PENDING: Clock,
  FAILED: XCircle,
};

export function IncomeTable({ income, isLoading, total, onPageChange, currentPage = 1 }: IncomeTableProps) {
  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 = [...income].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, 5].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-20 rounded bg-white/10" />
              <div className="h-4 w-16 rounded bg-white/10" />
              <div className="h-4 w-24 rounded bg-white/10" />
              <div className="h-4 w-20 rounded bg-white/10" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  if (income.length === 0) {
    return (
      <div className="rounded-lg border border-white/10 bg-white/5 p-8 text-center">
        <DollarSign className="mx-auto h-12 w-12 text-slate-600" />
        <p className="mt-3 text-sm text-slate-500">No referral income yet.</p>
        <p className="text-xs text-slate-600">Earn commissions when your referrals complete trades.</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">
              <button onClick={() => handleSort('amount')} className="flex items-center gap-1 hover:text-slate-300" type="button">
                Amount <ArrowUpDown className="h-3 w-3" />
              </button>
            </th>
            <th className="pb-3 pr-4 font-medium">Commission Rate</th>
            <th className="pb-3 pr-4 font-medium">
              <button onClick={() => handleSort('status')} className="flex items-center gap-1 hover:text-slate-300" type="button">
                Status <ArrowUpDown className="h-3 w-3" />
              </button>
            </th>
            <th className="pb-3 font-medium">Paid At</th>
          </tr>
        </thead>
        <tbody>
          {sorted.map((item) => {
            const StatusIcon = STATUS_ICONS[item.status] ?? Search;
            return (
              <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 text-slate-200">
                  {item.referral?.referred
                    ? `${item.referral.referred.firstName ?? ''} ${item.referral.referred.lastName ?? ''}`.trim() ||
                      item.referral.referred.email
                    : 'Unknown'}
                </td>
                <td className="py-3 pr-4 font-medium text-emerald-400">
                  ${item.amount.toFixed(2)}
                </td>
                <td className="py-3 pr-4 text-slate-400">
                  {(item.commissionRate * 100).toFixed(2)}%
                </td>
                <td className="py-3 pr-4">
                  <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[item.status] ?? 'text-slate-400 bg-slate-500/10'}`}>
                    <StatusIcon className="h-3 w-3" />
                    {item.status}
                  </span>
                </td>
                <td className="py-3 text-slate-400">
                  {item.paidAt
                    ? new Date(item.paidAt).toLocaleDateString('en-US', {
                        month: 'short',
                        day: 'numeric',
                        year: 'numeric',
                      })
                    : '-'}
                </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>
  );
}
