"use client";

import { ReactNode } from "react";
import { DataTableSkeletonRows } from "@/components/ui/Skeleton";
import type { SortDir } from "@/components/layout/TableSort";

export type DataTableColumn = {
  key: string;
  label: string;
  className?: string;
  sortable?: boolean;
};

export function DataTable({
  columns,
  children,
  emptyMessage = "اطلاعاتی وجود ندارد.",
  loading = false,
  loadingRows = 8,
  sortBy,
  sortDir,
  onSort,
}: {
  columns: DataTableColumn[];
  children: ReactNode;
  emptyMessage?: string;
  loading?: boolean;
  loadingRows?: number;
  sortBy?: string;
  sortDir?: SortDir;
  onSort?: (key: string) => void;
}) {
  return (
    <div
      className="rounded-2xl border border-[var(--border)] bg-white shadow-card"
      aria-busy={loading || undefined}
    >
      <div className="overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="bg-slate-50 text-xs text-[var(--muted)]">
            <tr>
              {columns.map((col) => {
                const active = Boolean(col.sortable && sortBy === col.key);
                return (
                  <th
                    key={col.key}
                    className={`whitespace-nowrap px-3 py-3 text-right font-semibold ${col.className ?? ""}`}
                    aria-sort={
                      col.sortable && active
                        ? sortDir === "desc"
                          ? "descending"
                          : "ascending"
                        : col.sortable
                          ? "none"
                          : undefined
                    }
                  >
                    {col.sortable && onSort ? (
                      <button
                        type="button"
                        className={`inline-flex items-center gap-1 rounded-md text-right font-semibold transition-colors hover:text-primary ${
                          active ? "text-primary" : "text-[var(--muted)]"
                        }`}
                        onClick={() => onSort(col.key)}
                        title={
                          active
                            ? sortDir === "asc"
                              ? "مرتب‌سازی نزولی"
                              : "مرتب‌سازی صعودی"
                            : `مرتب‌سازی بر اساس ${col.label}`
                        }
                      >
                        <span>{col.label}</span>
                        <span className="text-[10px] leading-none" aria-hidden>
                          {active ? (sortDir === "asc" ? "▲" : "▼") : "↕"}
                        </span>
                      </button>
                    ) : (
                      col.label
                    )}
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--border)]">
            {loading ? (
              <DataTableSkeletonRows columns={columns.length} rows={loadingRows} />
            ) : (
              children
            )}
          </tbody>
        </table>
      </div>
      {!loading && !children ? (
        <div className="px-4 py-8 text-center text-sm text-[var(--muted)]">{emptyMessage}</div>
      ) : null}
    </div>
  );
}

export function DataTableEmpty({
  colSpan,
  message,
  children,
}: {
  colSpan: number;
  message?: string;
  children?: ReactNode;
}) {
  return (
    <tr>
      <td colSpan={colSpan} className="px-4 py-8 text-center text-sm text-[var(--muted)]">
        {children ?? message ?? "اطلاعاتی وجود ندارد!"}
      </td>
    </tr>
  );
}
