'use client';

import { useState } from 'react';
import { ChevronUp, ChevronDown, ChevronsUpDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import EmptyState from '@/components/EmptyState';

type SortDirection = 'asc' | 'desc' | null;

export interface SortableColumn {
  key: string;
  label: string;
  sortable?: boolean;
  align?: 'left' | 'right' | 'center';
  render?: (value: any, row: any) => React.ReactNode;
}

interface SortableTableProps {
  title?: string;
  data: any[];
  columns: SortableColumn[];
  onRowClick?: (row: any) => void;
  activeRowClassName?: string;
  loading?: boolean;
  emptyMessage?: string;
  emptyDescription?: string;
  rowClassName?: (row: any) => string;
  sortBy?: string | null;
  sortOrder?: 'asc' | 'desc' | null;
  onSortChange?: (key: string, order: 'asc' | 'desc' | null) => void;
}

export function SortableTable({
  title,
  data,
  columns,
  onRowClick,
  activeRowClassName = 'bg-blue-500/10',
  loading,
  emptyMessage = 'No records found',
  emptyDescription = 'There are no records to display.',
  rowClassName,
  sortBy,
  sortOrder,
  onSortChange,
}: SortableTableProps) {
  const isControlled = onSortChange !== undefined;
  const [internalSortKey, setInternalSortKey] = useState<string | null>(null);
  const [internalSortDir, setInternalSortDir] = useState<SortDirection>(null);
  const [activeRowId, setActiveRowId] = useState<string | number | null>(null);

  const activeSortKey = isControlled ? sortBy : internalSortKey;
  const activeSortDir = isControlled ? sortOrder : internalSortDir;

  const handleSort = (key: string) => {
    if (isControlled) {
      let newDir: SortDirection;
      if (activeSortKey === key) {
        if (activeSortDir === 'asc') newDir = 'desc';
        else if (activeSortDir === 'desc') newDir = null;
        else newDir = 'asc';
      } else {
        newDir = 'asc';
      }
      onSortChange(key, newDir);
    } else {
      if (internalSortKey === key) {
        if (internalSortDir === 'asc') setInternalSortDir('desc');
        else if (internalSortDir === 'desc') { setInternalSortKey(null); setInternalSortDir(null); }
        else setInternalSortDir('asc');
      } else {
        setInternalSortKey(key);
        setInternalSortDir('asc');
      }
    }
  };

  const sortedData = [...(data ?? [])].sort((a, b) => {
    if (!activeSortKey || !activeSortDir) return 0;
    const aVal = a?.[activeSortKey];
    const bVal = b?.[activeSortKey];
    if (aVal == null && bVal == null) return 0;
    if (aVal == null) return activeSortDir === 'asc' ? -1 : 1;
    if (bVal == null) return activeSortDir === 'asc' ? 1 : -1;
    if (typeof aVal === 'number' && typeof bVal === 'number') {
      return activeSortDir === 'asc' ? aVal - bVal : bVal - aVal;
    }
    const aStr = String(aVal).toLowerCase();
    const bStr = String(bVal).toLowerCase();
    if (aStr < bStr) return activeSortDir === 'asc' ? -1 : 1;
    if (aStr > bStr) return activeSortDir === 'asc' ? 1 : -1;
    return 0;
  });

  const SortIcon = ({ columnKey }: { columnKey: string }) => {
    if (activeSortKey !== columnKey) return <ChevronsUpDown className="ml-1 h-3.5 w-3.5 text-slate-500" />;
    if (activeSortDir === 'asc') return <ChevronUp className="ml-1 h-3.5 w-3.5 text-blue-400" />;
    if (activeSortDir === 'desc') return <ChevronDown className="ml-1 h-3.5 w-3.5 text-blue-400" />;
    return <ChevronsUpDown className="ml-1 h-3.5 w-3.5 text-slate-500" />;
  };

  const handleRowClick = (row: any) => {
    if (!onRowClick) return;
    setActiveRowId(row?.id ?? row?.userId ?? null);
    onRowClick(row);
  };

  const alignClass: Record<string, string> = {
    left: 'text-left',
    right: 'text-right',
    center: 'text-center',
  };

  const SkeletonRow = () => (
    <tr>
      {columns.map((col) => (
        <td key={col.key} className="px-4 py-3">
          <div className="skeleton h-4 w-full max-w-[120px]" />
        </td>
      ))}
    </tr>
  );

  return (
    <div className="overflow-x-auto rounded-xl border border-white/10 bg-slate-900/50">
      {title && (
        <div className="border-b border-white/10 px-4 py-3">
          <h3 className="text-sm font-semibold text-white">{title}</h3>
        </div>
      )}
      <table className="w-full text-sm">
        <thead className="border-b border-white/10 bg-white/5">
          <tr>
            {columns.map((col) => (
              <th
                key={col.key}
                className={cn(
                  'px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-300',
                  alignClass[col.align || 'left'],
                  col.sortable !== false && 'cursor-pointer select-none hover:text-white',
                )}
                onClick={() => col.sortable !== false && handleSort(col.key)}
              >
                <span
                  className={cn(
                    'flex items-center',
                    col.align === 'center' ? 'justify-center' : col.align === 'right' ? 'justify-end' : '',
                  )}
                >
                  {col.label}
                  {col.sortable !== false && <SortIcon columnKey={col.key} />}
                </span>
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-white/5">
          {loading ? (
            Array.from({ length: 5 }).map((_, i) => <SkeletonRow key={i} />)
          ) : sortedData.length === 0 ? (
            <tr>
              <td colSpan={columns.length} className="px-4 py-8">
                <EmptyState message={emptyMessage} description={emptyDescription} />
              </td>
            </tr>
          ) : (
            sortedData.map((row, idx) => {
              const rowId = row?.id ?? row?.userId ?? idx;
              const isActive = activeRowId === rowId;
              return (
                <tr
                  key={rowId}
                  className={cn(
                    'transition-colors',
                    onRowClick && 'cursor-pointer',
                    isActive ? activeRowClassName : 'hover:bg-white/5',
                    rowClassName?.(row),
                  )}
                  onClick={() => handleRowClick(row)}
                >
                  {columns.map((col) => (
                    <td
                      key={col.key}
                      className={cn('px-4 py-3 text-slate-300', alignClass[col.align || 'left'])}
                    >
                      {col.render
                        ? col.render(row?.[col.key], row)
                        : row?.[col.key] == null
                          ? '-'
                          : String(row[col.key])}
                    </td>
                  ))}
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </div>
  );
}
