import DefaultTableSkeleton from "@/components/DefaultTableSkeleton";
import Td from "@/components/Td";
import type { ColumnType, RowDataType, TableProps } from "@/components/types/TableTypes";
import { type ReactElement } from "react";

const Table = <T extends RowDataType>({
  columns,
  data,
  isLoading = false,
  onRowClick,
  className = "",
  rowClassName = "",
  noDataMessage = "هیچ داده‌ای یافت نشد",
  headerClassName = "bg-gray-50",
  emptyRowsCount = 5,
  showHeader = true,
  actions = null,
  actionsPosition = "top",
}: TableProps<T>): ReactElement => {
  const getRowClassName = (item: T, index: number): string => {
    if (typeof rowClassName === "function") {
      return rowClassName(item, index);
    }
    return rowClassName;
  };

  const getCellClassName = (column: ColumnType<T>): string => {
    const alignClass = column.align ? `text-${column.align}` : "";
    return `px-3 md:px-6 py-3 md:py-4 whitespace-nowrap text-xs ${alignClass} ${column.className || ""}`.trim();
  };

  const handleRowClick = (item: T) => {
    if (onRowClick) {
      onRowClick(item.id, item);
    }
  };

  const renderTableBody = () => {
    if (isLoading) {
      return <DefaultTableSkeleton tdCount={columns.length} trCount={emptyRowsCount} />;
    }

    if (!data || data.length === 0) {
      return (
        <tr>
          <td colSpan={columns.length} className="px-3 md:px-6 py-6 md:py-8 text-center text-gray-500">
            {noDataMessage}
          </td>
        </tr>
      );
    }

    return data.map((item, rowIndex) => (
      <tr
        key={item.id}
        className={`w-full h-[64px] md:h-[74px] bg-white border-t border-[#EAEDF5] hover:bg-[#F4F5F9] ${onRowClick ? "cursor-pointer" : ""} ${getRowClassName(item, rowIndex)}`}
        onClick={() => handleRowClick(item)}
      >
        {columns.map((col) => (
          <td key={`${item.id}-${col.key}`} className={getCellClassName(col)} style={{ width: col.width }}>
            {col.render ? col.render(item) : (item[col.key] as React.ReactNode)}
          </td>
        ))}
      </tr>
    ));
  };

  const renderHeader = () => {
    if (!showHeader || actionsPosition === "header-replace") return null;

    return (
      <thead className={`h-[60px] md:h-[69px] bg-white text-sm text-[#8C90A3] ${headerClassName}`}>
        <tr>
          {columns.map((col) => (
            <Td key={col.key} text={col.title} />
          ))}
        </tr>
      </thead>
    );
  };

  const renderActions = () => {
    if (!actions) return null;

    return (
      <div className="h-[64px] rounded-t-2xl md:rounded-t-3xl md:h-[74px] bg-white flex items-center px-3 md:px-6">
        <div className="flex items-center gap-2 md:gap-4">{actions}</div>
      </div>
    );
  };

  return (
    <div className={`relative w-full ${className}`}>
      {(actionsPosition === "top" || actionsPosition === "above-header") && renderActions()}

      <div
        className={`overflow-x-auto overflow-hidden ${showHeader && actionsPosition !== "header-replace" ? "rounded-2xl md:rounded-3xl" : "rounded-b-2xl md:rounded-b-3xl"} bg-white`}
      >
        <table className="w-full text-sm border-collapse min-w-[600px]">
          {renderHeader()}
          <tbody>{renderTableBody()}</tbody>
        </table>
      </div>
    </div>
  );
};

export default Table;
