import * as React from "react";
import { cn } from "@/lib/utils";

export function Table({ className, ...props }: React.TableHTMLAttributes<HTMLTableElement>) {
  return (
    <div className="w-full overflow-x-auto bg-(--color-surface)">
      <table className={cn("min-w-max w-full border-collapse text-sm sm:min-w-full", className)} {...props} />
    </div>
  );
}

export function TableHead({ className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
  return <thead className={cn("border-b border-(--color-border) text-left", className)} {...props} />;
}

export function TableBody({ className, ...props }: React.HTMLAttributes<HTMLTableSectionElement>) {
  return <tbody className={cn("divide-y divide-(--color-border)", className)} {...props} />;
}

export function TableRow({ className, ...props }: React.HTMLAttributes<HTMLTableRowElement>) {
  return <tr className={cn("hover:bg-(--color-surface-2)/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--color-accent) focus-visible:ring-inset", className)} {...props} />;
}

export function TableHeaderCell({
  className,
  sortable,
  sorted,
  ...props
}: React.ThHTMLAttributes<HTMLTableCellElement> & { sortable?: boolean; sorted?: "asc" | "desc" | false }) {
  return (
    <th
      className={cn(
        "px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-(--color-ink-faint)",
        sortable && "cursor-pointer select-none hover:text-(--color-ink)",
        className
      )}
      {...props}
    >
      <span className="inline-flex items-center gap-1">
        {props.children}
        {sortable && <span className="text-[10px]">{sorted === "asc" ? "▲" : sorted === "desc" ? "▼" : "↕"}</span>}
      </span>
    </th>
  );
}

export function TableCell({ className, ...props }: React.TdHTMLAttributes<HTMLTableCellElement>) {
  return <td className={cn("whitespace-nowrap px-4 py-3 text-(--color-ink) sm:whitespace-normal", className)} {...props} />;
}

export function TableEmpty({ colSpan, message = "No records found.", action }: { colSpan: number; message?: string; action?: { label: string; onClick: () => void } }) {
  return (
    <tr>
      <td colSpan={colSpan} className="px-4 py-12 text-center">
        <div className="flex flex-col items-center justify-center gap-4">
          <svg className="h-12 w-12 text-(--color-ink-faint)" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <p className="text-sm text-(--color-ink-faint)">{message}</p>
          {action && (
            <button
              onClick={action.onClick}
              className="text-sm font-medium text-(--color-accent) hover:text-(--color-accent-hover) transition-colors"
            >
              {action.label}
            </button>
          )}
        </div>
      </td>
    </tr>
  );
}
