'use client';
import React, { useState, useMemo } from 'react';
import { Icon } from '@iconify/react';

export interface Column<T> {
  key: keyof T | string;
  header: string;
  render?: (row: T) => React.ReactNode;
  className?: string;
}

interface TableProps<T> {
  columns: Column<T>[];
  data: T[];
  keyField: keyof T;
  isLoading?: boolean;
  emptyMessage?: string;
  onRowClick?: (row: T) => void;
}

function Skeleton() {
  return (
    <div className="animate-pulse h-4 bg-[var(--border-default)] rounded w-3/4" />
  );
}

export function Table<T extends object>({
  columns,
  data,
  keyField,
  isLoading = false,
  emptyMessage = 'No records found.',
  onRowClick,
}: TableProps<T>) {
  const [sortKey, setSortKey] = useState<keyof T | string | null>(null);
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');

  const handleSort = (key: keyof T | string) => {
    if (sortKey === key) {
      if (sortDirection === 'asc') setSortDirection('desc');
      else setSortKey(null);
    } else {
      setSortKey(key);
      setSortDirection('asc');
    }
  };

  const sortedData = useMemo(() => {
    if (!sortKey) return data;
    return [...data].sort((a, b) => {
      const aVal = (a as any)[sortKey];
      const bVal = (b as any)[sortKey];

      if (aVal === bVal) return 0;
      if (aVal === null || aVal === undefined) return 1;
      if (bVal === null || bVal === undefined) return -1;

      if (typeof aVal === 'string' && typeof bVal === 'string') {
        return sortDirection === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
      }
      return sortDirection === 'asc' ? (aVal < bVal ? -1 : 1) : (aVal > bVal ? -1 : 1);
    });
  }, [data, sortKey, sortDirection]);

  return (
    <div className="overflow-x-auto rounded-xl border border-[var(--border-default)] shadow-sm">
      <table className="min-w-full divide-y divide-[var(--border-default)] text-sm">
        <thead className="bg-[var(--bg-default)]">
          <tr>
            {columns.map((col) => (
              <th
                key={String(col.key)}
                onClick={() => handleSort(col.key)}
                className={[
                  'px-4 py-3 text-left text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider select-none cursor-pointer group hover:bg-[var(--bg-paper)] transition-colors',
                  col.className ?? '',
                ].join(' ')}
              >
                <div className="flex items-center gap-1.5">
                  {col.header}
                  <span className="inline-flex">
                    {sortKey === col.key ? (
                      <Icon 
                        icon={sortDirection === 'asc' ? 'solar:sort-from-bottom-to-top-bold' : 'solar:sort-from-top-to-bottom-bold'} 
                        className="w-3.5 h-3.5 text-primary" 
                      />
                    ) : (
                      <Icon icon="solar:sort-vertical-linear" className="w-3.5 h-3.5 opacity-0 group-hover:opacity-50 transition-opacity" />
                    )}
                  </span>
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="bg-[var(--bg-paper)] divide-y divide-[var(--border-default)]">
          {isLoading
            ? Array.from({ length: 5 }).map((_, i) => (
                <tr key={i}>
                  {columns.map((col) => (
                    <td key={String(col.key)} className="px-4 py-3">
                      <Skeleton />
                    </td>
                  ))}
                </tr>
              ))
            : data.length === 0
            ? (
              <tr>
                <td
                  colSpan={columns.length}
                  className="px-4 py-12 text-center text-[var(--text-secondary)]"
                >
                  {emptyMessage}
                </td>
              </tr>
            )
            : sortedData.map((row) => (
              <tr
                key={String(row[keyField])}
                onClick={() => onRowClick?.(row)}
                className={[
                  'transition-colors duration-100',
                  onRowClick ? 'cursor-pointer hover:bg-primary/5' : '',
                ].join(' ')}
              >
                {columns.map((col) => (
                  <td
                    key={String(col.key)}
                    className={['px-4 py-3 text-[var(--text-primary)]', col.className ?? ''].join(' ')}
                  >
                    {col.render
                      ? col.render(row)
                      : String((row as Record<string, unknown>)[String(col.key)] ?? '—')}
                  </td>
                ))}
              </tr>
            ))}
        </tbody>
      </table>
    </div>
  );
}
