"use client";

import Image from "next/image";
import { ReactNode, useMemo, useState } from "react";

export type TableColumn<T> = {
  key: keyof T | string;
  title: string;
  render?: (row: T) => ReactNode;
  className?: string;
};

interface DynamicTableProps<T> {
  columns: TableColumn<T>[];
  data: T[];
  pageSize?: number;
  emptyTitle?: string;
  emptyDescription?: string;
  emptyImage?: string;
}

export default function DynamicTable<T>({
  columns,
  data,
  pageSize = 5,
  emptyTitle = "No transactions yet",
  emptyDescription = "Once you purchase a credit package, your invoices and transaction history will appear here.",
  emptyImage = "/images/no-transaction.svg",
}: DynamicTableProps<T>) {
  const [currentPage, setCurrentPage] = useState(1);

  const totalPages = Math.ceil(data.length / pageSize);

  const paginatedData = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return data.slice(start, start + pageSize);
  }, [data, currentPage, pageSize]);

  if (!data.length) {
    return (
      <div className="glass-card-v2 rounded-2xl p-10 text-center md:p-16">
        

        <div className="relative z-10 mx-auto max-w-152.5">
          <Image
            src={emptyImage}
            alt="Empty"
            width={150}
            height={120}
            className="mx-auto mb-6"
          />

          <h3 className="font-body text-xl font-bold text-heading">
            {emptyTitle}
          </h3>

          <p className="mt-3 font-body text-base text-text md:text-lg">
            {emptyDescription}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="hidden md:block">
        <table className="w-full rounded-xl overflow-hidden ">
          <thead className="glass-card-v2 rounded-xl">
            <tr>
              {columns.map((col) => (
                <th
                  key={String(col.key)}
                  className={`px-6 py-4 text-left font-body text-base font-medium text-heading ${
                    col.className || ""
                  }`}
                >
                  {col.title}
                </th>
              ))}
            </tr>

          </thead>
              
          <tbody className="glass-card-v2 rounded-xl overflow-hidden">
            {paginatedData.map((row, index) => (
              <tr key={index} 
                className={
                        index !== paginatedData.length - 1
                        ? "[&>td]:border-b [&>td]:border-white"
                        : ""
                    }>
                {columns.map((col) => (
                  <td
                    key={String(col.key)}
                    className={`px-6 py-4 font-body font-medium text-base text-heading ${
                      col.className || ""
                    }`}
                  >
                    {col.render ? col.render(row) : getCellValue(row, col.key)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="space-y-4 md:hidden">
        {paginatedData.map((row, index) => (
          <div key={index} className="glass-card-v2 rounded-2xl p-4">
            

            <div className="relative z-10 space-y-3">
              {columns.map((col) => (
                <div
                  key={String(col.key)}
                  className="flex items-start justify-between gap-4 border-b border-white/60 pb-2 last:border-b-0 last:pb-0"
                >
                  <span className="font-body text-sm font-semibold text-heading">
                    {col.title}
                  </span>

                  <span className="text-right font-body text-sm text-text">
                    {col.render ? col.render(row) : getCellValue(row, col.key)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      )}
    </div>
  );
}

function Pagination({
  currentPage,
  totalPages,
  onPageChange,
}: {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}) {
  const pages = Array.from({ length: totalPages }, (_, i) => i + 1);

  return (
    <div className="mt-8 flex flex-wrap items-center justify-center gap-1">
      <button
        type="button"
        disabled={currentPage === 1}
        onClick={() => onPageChange(currentPage - 1)}
        className="rounded-lg bg-white px-3 py-2 font-body text-base text-link-1 disabled:text-link-1/30"
      >
        Back
      </button>

      {pages.map((page) => (
        <button
          type="button"
          key={page}
          onClick={() => onPageChange(page)}
          className={`rounded-lg px-4 py-2 font-body text-base ${
            currentPage === page
              ? "bg-link-1 text-white"
              : "bg-white text-heading"
          }`}
        >
          {page}
        </button>
      ))}

      <button
        type="button"
        disabled={currentPage === totalPages}
        onClick={() => onPageChange(currentPage + 1)}
        className="rounded-lg bg-white px-3 py-2 font-body text-base text-link-1 disabled:text-link-1/30"
      >
        Next
      </button>
    </div>
  );
}

function getCellValue<T>(row: T, key: keyof T | string) {
  return String(row[key as keyof T] ?? "");
}