﻿import React from "react";

export interface ColumnType<T> {
  title: string;
  dataIndex?: keyof T;
  render?: (value: any, record: T, index: number) => React.ReactNode;
  width?: string | number;
  className?: string;
}

interface TableProps<T> {
  columns: ColumnType<T>[];
  data: T[];
  loading?: boolean;
  rowKey?: keyof T;
  pageSize?: number;
}

export function Table<T extends Record<string, any>>({
  columns,
  data,
  loading = false,
  rowKey = "id" as keyof T,
  pageSize = 5,
}: TableProps<T>) {
  const [currentPage, setCurrentPage] = React.useState(1);

  const paginatedData = React.useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return data.slice(start, start + pageSize);
  }, [data, currentPage, pageSize]);

  const totalPages = Math.ceil(data.length / pageSize);

  const getRowKey = (record: T, index: number): React.Key => {
    const key = record[rowKey];
    if (typeof key === "string" || typeof key === "number") return key;
    return index; // fallback
  };

  return (
    <div className="overflow-x-auto bg-white rounded-lg shadow-sm border border-gray-200">
      <table className="w-full text-sm text-left text-gray-500">
        <thead className="text-xs uppercase bg-gray-50">
          <tr>
            {columns.map((col, i) => (
              <th
                key={i}
                className={`px-6 py-3 font-medium text-gray-700 ${
                  col.className || ""
                }`}
                style={{ width: col.width }}
              >
                {col.title}
              </th>
            ))}
          </tr>
        </thead>

        <tbody>
          {loading ? (
            <tr>
              <td colSpan={columns.length} className="text-center p-6">
                Loading...
              </td>
            </tr>
          ) : paginatedData.length === 0 ? (
            <tr>
              <td
                colSpan={columns.length}
                className="text-center p-6 text-gray-400"
              >
                No data found
              </td>
            </tr>
          ) : (
            paginatedData.map((record, rowIndex) => (
              <tr
                key={getRowKey(record, rowIndex)}
                className="bg-white border-b hover:bg-gray-50 transition"
              >
                {columns.map((col, colIndex) => (
                  <td key={colIndex} className="px-6 py-4 whitespace-nowrap">
                    {col.render
                      ? col.render(record[col.dataIndex!], record, rowIndex)
                      : (record[col.dataIndex!] as React.ReactNode)}
                  </td>
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex justify-end items-center p-4 space-x-2">
          <button
            disabled={currentPage === 1}
            onClick={() => setCurrentPage((p) => p - 1)}
            className="px-3 py-1 text-sm bg-gray-100 rounded disabled:opacity-50"
          >
            Prev
          </button>
          <span className="text-sm text-gray-600">
            Page {currentPage} of {totalPages}
          </span>
          <button
            disabled={currentPage === totalPages}
            onClick={() => setCurrentPage((p) => p + 1)}
            className="px-3 py-1 text-sm bg-gray-100 rounded disabled:opacity-50"
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
}

