'use client';

import * as React from 'react';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@/lib/utils';

export type DataTableAlign = 'left' | 'right' | 'center';

export interface DataTableColumn<T> {
  /** Key duy nhất. */
  id: string;
  /** Header hiển thị. */
  header: React.ReactNode;
  /** Render cell. */
  cell: (row: T, index: number) => React.ReactNode;
  /** Căn lề. */
  align?: DataTableAlign;
  /** Có cho phép sort không. */
  sortable?: boolean;
  /** Function lấy giá trị sort (trả về number | string). */
  sortValue?: (row: T) => number | string;
  /** Rộng cột. */
  width?: string;
  /** Hiển thị dạng mono (tabular-nums). */
  numeric?: boolean;
}

export interface DataTableProps<T> {
  columns: DataTableColumn<T>[];
  data: T[];
  /** Hàm trả về key row duy nhất. */
  getRowId?: (row: T, index: number) => string | number;
  /** Click row. */
  onRowClick?: (row: T) => void;
  /** Hover row — fires with null on mouse leave. */
  onRowHover?: (row: T | null) => void;
  /** Hiện sticky header. */
  stickyHeader?: boolean;
  /** Trạng thái loading. */
  loading?: boolean;
  /** Text hiển thị khi rỗng. */
  emptyText?: React.ReactNode;
  className?: string;
  /** Compact row height. */
  dense?: boolean;
  /** Col sort mặc định. */
  defaultSortId?: string;
  defaultSortDir?: 'asc' | 'desc';
}

/**
 * DataTable ticker-style:
 * - Row cao 36px (dense mặc định), alternating bg, sticky header.
 * - Sort client-side qua `sortable` + `sortValue`.
 * - Số hiển thị font-mono với `column.numeric = true`.
 *
 * Giữ nguyên data contract: không tự fetch, component chỉ render.
 */
export function DataTable<T>({
  columns,
  data,
  getRowId,
  onRowClick,
  onRowHover,
  stickyHeader = true,
  loading = false,
  emptyText = 'Không có dữ liệu',
  className,
  dense = true,
  defaultSortId,
  defaultSortDir = 'desc',
}: DataTableProps<T>) {
  const [sortId, setSortId] = React.useState<string | undefined>(defaultSortId);
  const [sortDir, setSortDir] = React.useState<'asc' | 'desc'>(defaultSortDir);

  const sortedData = React.useMemo(() => {
    if (!sortId) return data;
    const col = columns.find((c) => c.id === sortId);
    if (!col || !col.sortValue) return data;
    const getValue = col.sortValue;
    const sorted = [...data].sort((a, b) => {
      const va = getValue(a);
      const vb = getValue(b);
      if (va === vb) return 0;
      if (typeof va === 'number' && typeof vb === 'number') {
        return sortDir === 'asc' ? va - vb : vb - va;
      }
      return sortDir === 'asc'
        ? String(va).localeCompare(String(vb), 'vi')
        : String(vb).localeCompare(String(va), 'vi');
    });
    return sorted;
  }, [data, columns, sortId, sortDir]);

  function toggleSort(colId: string) {
    if (sortId !== colId) {
      setSortId(colId);
      setSortDir('desc');
    } else {
      setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    }
  }

  return (
    <div
      className={cn(
        'relative w-full overflow-auto rounded-md border border-border bg-background-elevated',
        className,
      )}
    >
      <table className="w-full caption-bottom border-collapse text-data-sm">
        <thead
          className={cn(
            'bg-background-surface text-[11px] uppercase tracking-wide text-foreground-muted',
            stickyHeader && 'sticky top-0 z-10',
          )}
        >
          <tr className="border-b border-border">
            {columns.map((col) => {
              const active = col.sortable && sortId === col.id;
              return (
                <th
                  key={col.id}
                  scope="col"
                  style={col.width ? { width: col.width } : undefined}
                  className={cn(
                    'h-8 select-none px-3 font-medium',
                    col.align === 'right' && 'text-right',
                    col.align === 'center' && 'text-center',
                    !col.align && 'text-left',
                    col.sortable && 'cursor-pointer hover:text-foreground',
                  )}
                  onClick={col.sortable ? () => toggleSort(col.id) : undefined}
                >
                  <span
                    className={cn(
                      'inline-flex items-center gap-1',
                      col.align === 'right' && 'justify-end',
                    )}
                  >
                    {col.header}
                    {col.sortable ? (
                      <span className="inline-flex h-3 w-3 items-center justify-center text-foreground-dim">
                        {active ? (
                          sortDir === 'asc' ? (
                            <ChevronUp className="h-3 w-3 text-foreground" />
                          ) : (
                            <ChevronDown className="h-3 w-3 text-foreground" />
                          )
                        ) : (
                          <ChevronDown className="h-3 w-3" />
                        )}
                      </span>
                    ) : null}
                  </span>
                </th>
              );
            })}
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr>
              <td
                colSpan={columns.length}
                className="px-3 py-8 text-center text-foreground-muted"
              >
                Đang tải...
              </td>
            </tr>
          ) : sortedData.length === 0 ? (
            <tr>
              <td
                colSpan={columns.length}
                className="px-3 py-8 text-center text-foreground-muted"
              >
                {emptyText}
              </td>
            </tr>
          ) : (
            sortedData.map((row, index) => {
              const key = getRowId ? getRowId(row, index) : index;
              return (
                <tr
                  key={key}
                  onClick={onRowClick ? () => onRowClick(row) : undefined}
                  onMouseEnter={onRowHover ? () => onRowHover(row) : undefined}
                  onMouseLeave={onRowHover ? () => onRowHover(null) : undefined}
                  className={cn(
                    'border-b border-border/60 transition-colors duration-100',
                    dense ? 'h-row' : 'h-10',
                    index % 2 === 1 && 'bg-background-surface/40',
                    onRowClick && [
                      'cursor-pointer',
                      'hover:bg-background-surface',
                      'active:bg-accent/10',
                      'focus-within:bg-background-surface',
                    ],
                  )}
                >
                  {columns.map((col) => (
                    <td
                      key={col.id}
                      className={cn(
                        'px-3 align-middle',
                        col.align === 'right' && 'text-right',
                        col.align === 'center' && 'text-center',
                        col.numeric && 'font-mono tabular-nums',
                      )}
                      data-numeric={col.numeric || undefined}
                    >
                      {col.cell(row, index)}
                    </td>
                  ))}
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </div>
  );
}
