import React, { useState, useEffect, useRef } from "react";
import { motion } from "framer-motion";
import {
  MagnifyingGlassIcon,
  ListBulletIcon,
  FunnelIcon,
  XMarkIcon,
  ChevronUpIcon,
  ChevronDownIcon,
  DocumentArrowDownIcon,
  ArrowsPointingOutIcon,
  LockClosedIcon,
  LockOpenIcon,
} from "@heroicons/react/24/outline";
import { CalendarIcon } from "@heroicons/react/20/solid";
import { HtmlContent } from "../../types/htmlTypes";
import Checkbox from "../CheckBox/CheckBox";
import { gsap } from "gsap";
import { useLayoutEffect } from "react";
import DatePicker from "../date-picker/DatePicker";
import { getSizeStyles } from "../../data/getInputSizes";
import { Tooltip } from "../Tooltip/Tooltip";
import api from "../../utils/axios";
import { checkIsMobile } from "../../utils/checkIsMobile";
import ToggleButton from "../ToggleButton/ToggleButton";

type ExcelProps = {
  title?: string;
  link?: string;
};
interface TableProps {
  columns: string[];
  rows: HtmlContent[][];
  showPagination?: boolean;
  showDates?: boolean;
  title?: string;
  className?: string;
  isDashboard?: boolean;
  noPagination?: boolean;
  count?: number;
  isPaginated?: boolean;
  excelInfo?: ExcelProps;
  onChange?: (params: {
    page_size: number;
    page: number;
    search?: string;
  }) => void;
  noSearch?: boolean;
}

const Table: React.FC<TableProps> = ({
  columns,
  rows,
  showPagination = true,
  showDates = false,
  excelInfo,
  title,
  className,
  isDashboard,
  noPagination,
  count,
  isPaginated,
  onChange,
  noSearch,
}) => {
  const storageKey = `table-pagination-${title || "default"}`;
  const getStoredPagination = () => {
    if (!isPaginated || typeof window === "undefined") return null;
    try {
      const raw = localStorage.getItem(storageKey);
      return raw ? JSON.parse(raw) : null;
    } catch {
      return null;
    }
  };
  const [currentPage, setCurrentPage] = useState<number>(() => {
    const stored = getStoredPagination();
    const value = Number(stored?.page);
    return Number.isFinite(value) && value > 0 ? value : 1;
  });
  const [itemsPerPage, setItemsPerPage] = useState<number>(() => {
    const stored = getStoredPagination();
    const value = Number(stored?.pageSize);
    return Number.isFinite(value) && value > 0 ? value : 10;
  });
  const [isLocked, setIsLocked] = useState<boolean>(() =>
    Boolean(getStoredPagination()?.locked)
  );
  const [expandedRows, setExpandedRows] = useState<number[]>([]);
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [filteredRows, setFilteredRows] = useState<HtmlContent[][]>(rows);
  const [showColumnFilter, setShowColumnFilter] = useState<boolean>(false);
  const [stretchMode, setStretchMode] = useState<boolean>(
    localStorage.getItem(`stretch-mode${title}`) === "false" ? false : true
  );

  const [visibleColumns, setVisibleColumns] = useState<Record<string, boolean>>(
    columns.reduce((acc, column) => ({ ...acc, [column]: true }), {})
  );

  const [dateInfo, setDateInfo] = useState({
    active: false,
    date1: "",
    date2: "",
  });

  const [sortColumn, setSortColumn] = useState<number | null>(null);
  const [sortDirection, setSortDirection] = useState<"desc" | "asc" | null>(
    null
  );

  useEffect(() => {
    localStorage.setItem(
      `stretch-mode${title}`,
      stretchMode ? "true" : "false"
    );
  }, [stretchMode]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if (!isPaginated) {
      localStorage.removeItem(storageKey);
      return;
    }
    if (isLocked) {
      localStorage.setItem(
        storageKey,
        JSON.stringify({
          page: currentPage,
          pageSize: itemsPerPage,
          locked: true,
        })
      );
    } else {
      localStorage.removeItem(storageKey);
    }
  }, [isLocked, currentPage, itemsPerPage, isPaginated, storageKey]);

  const rowRefs = useRef<(HTMLTableRowElement | null)[]>([]);
  const previousRowsSignatureRef = useRef<string>("");
  const hasAnimatedRef = useRef<boolean>(false);

  const getRowsSignature = (
    rowsToSign: HtmlContent[][],
    isDashboardTable: boolean
  ): string => {
    try {
      return JSON.stringify(
        rowsToSign.map((row, rowIdx) =>
          row.map((cell, cellIdx) => {
            if (typeof cell === "string" || typeof cell === "number") {
              return cell;
            }
            if (cell && typeof cell === "object" && "props" in cell) {
              if (isDashboardTable) {
                return "element";
              } else {
                const p: any = (cell as any).props;
                return p?.key || `element-${rowIdx}-${cellIdx}`;
              }
            }
            return String(cell || "");
          })
        )
      );
    } catch {
      return `${rowsToSign.length}-${String(rowsToSign[0]?.[0])}-${String(
        rowsToSign[rowsToSign.length - 1]?.[0]
      )}`;
    }
  };

  const effectiveTotal =
    isPaginated && typeof count === "number" ? count : filteredRows?.length;

  useEffect(() => {
    if (!isPaginated) {
      if (searchTerm.trim() === "") {
        setFilteredRows(rows);
      } else {
        const filtered = rows.filter((row) =>
          row.some((cell) =>
            String(cell).toLowerCase().includes(searchTerm.toLowerCase())
          )
        );
        setFilteredRows(filtered);
      }
      setCurrentPage(1);
    }
  }, [rows, searchTerm, isPaginated]);

  useEffect(() => {
    if (onChange) {
      onChange({
        page_size: itemsPerPage,
        page: currentPage,
        ...(searchTerm ? { search: searchTerm } : {}),
        ...(dateInfo.active
          ? { start: dateInfo?.date1, end: dateInfo?.date2 }
          : {}),
      });
    }
  }, [currentPage, itemsPerPage]);

  useEffect(() => {
    if (onChange && !isPaginated) {
      onChange({
        page_size: itemsPerPage,
        page: currentPage,
        ...(searchTerm ? { search: searchTerm } : {}),
        ...(dateInfo.active
          ? { start: dateInfo?.date1, end: dateInfo?.date2 }
          : {}),
      });
    }
  }, [searchTerm]);

  const toggleColumnVisibility = (column: string) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };

  const resetColumnFilters = () => {
    setVisibleColumns(
      columns.reduce((acc, column) => ({ ...acc, [column]: true }), {})
    );
  };

  const totalPages = Math.ceil(effectiveTotal / itemsPerPage);

  const paginate = (page: number) => {
    if (page < 1) page = 1;
    if (page > totalPages) page = totalPages;
    setCurrentPage(page);
  };

  const toggleRow = (rowIndex: number) => {
    setExpandedRows((prev) =>
      prev.includes(rowIndex)
        ? prev.filter((i) => i !== rowIndex)
        : [...prev, rowIndex]
    );
  };

  const getNumericValue = (cell: any) => {
    if (typeof cell === "number") return cell;
    if (typeof cell === "string") {
      const n = Number(cell.replace(/[٬,\s]/g, ""));
      return Number.isNaN(n) ? NaN : n;
    }
    if (cell && typeof cell === "object" && "props" in cell) {
      const p: any = (cell as any).props;
      const candidate = p?.weight ?? p?.value ?? p?.amount ?? p?.total;
      if (candidate !== undefined) {
        const n = Number(String(candidate).replace(/[٬,\s]/g, ""));
        return Number.isNaN(n) ? NaN : n;
      }
    }
    return NaN;
  };

  const isNumericColumn = (
    columnIndex: number,
    rowsToCheck?: HtmlContent[][]
  ) => {
    try {
      const rowsToUse =
        rowsToCheck || (isPaginated ? rows : filteredRows) || [];
      let hasAtLeastOneNumber = false;
      for (const row of rowsToUse) {
        const cell = row?.[columnIndex] as unknown as any;
        const value = getNumericValue(cell);
        if (!Number.isNaN(value)) {
          hasAtLeastOneNumber = true;
        } else if (
          cell !== undefined &&
          cell !== null &&
          cell !== "" &&
          !(cell && typeof cell === "object" && "props" in cell)
        ) {
          return false;
        }
      }
      return hasAtLeastOneNumber;
    } catch {
      return false;
    }
  };

  const getColumnSum = (columnIndex: number) => {
    let sum = 0;
    for (const row of currentRows || []) {
      const cell = row?.[columnIndex] as unknown as any;
      const value = getNumericValue(cell);
      if (!Number.isNaN(value)) sum += value;
    }
    return sum;
  };

  const getCellValue = (cell: any): string | number => {
    if (typeof cell === "number") return cell;
    if (typeof cell === "string") return cell.toLowerCase();
    if (cell && typeof cell === "object" && "props" in cell) {
      const p: any = (cell as any).props;
      const candidate =
        p?.weight ?? p?.value ?? p?.amount ?? p?.total ?? p?.children;
      if (candidate !== undefined) {
        if (typeof candidate === "number") return candidate;
        if (typeof candidate === "string") return candidate.toLowerCase();
      }
    }
    return String(cell || "").toLowerCase();
  };

  const sortRows = (
    rowsToSort: HtmlContent[][],
    columnIndex: number,
    direction: "desc" | "asc"
  ): HtmlContent[][] => {
    const sorted = [...rowsToSort];
    const isNumeric = isNumericColumn(columnIndex, rowsToSort);

    sorted.sort((a, b) => {
      const cellA = a[columnIndex];
      const cellB = b[columnIndex];

      if (isNumeric) {
        const numA = getNumericValue(cellA);
        const numB = getNumericValue(cellB);

        if (Number.isNaN(numA) && Number.isNaN(numB)) return 0;
        if (Number.isNaN(numA)) return 1;
        if (Number.isNaN(numB)) return -1;

        return direction === "desc" ? numB - numA : numA - numB;
      } else {
        const strA = getCellValue(cellA);
        const strB = getCellValue(cellB);

        if (strA < strB) return direction === "desc" ? 1 : -1;
        if (strA > strB) return direction === "desc" ? -1 : 1;
        return 0;
      }
    });

    return sorted;
  };

  const handleColumnSort = (columnIndex: number) => {
    if (sortColumn === columnIndex && sortDirection) {
      setSortDirection(sortDirection === "desc" ? "asc" : "desc");
    } else {
      setSortColumn(columnIndex);
      setSortDirection("desc");
    }
    setCurrentPage(1);
  };

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;

  let rowsToDisplay = isPaginated ? rows : filteredRows;

  if (sortColumn !== null && sortDirection !== null) {
    rowsToDisplay = sortRows(rowsToDisplay, sortColumn, sortDirection);
  }

  const currentRows = isPaginated
    ? rowsToDisplay
    : showPagination
    ? rowsToDisplay.slice(indexOfFirstItem, indexOfLastItem)
    : rowsToDisplay;

  const visibleColumnIndices = columns
    .map((col, index) => (visibleColumns[col] ? index : -1))
    .filter((index) => index !== -1);

  const getVisiblePages = () => {
    const visiblePages = [];
    const maxVisible = 5;

    if (totalPages <= maxVisible) {
      for (let i = 1; i <= totalPages; i++) visiblePages.push(i);
    } else {
      let start = Math.max(currentPage - 2, 1);
      const end = Math.min(start + maxVisible - 1, totalPages);

      if (end - start + 1 < maxVisible) start = end - maxVisible + 1;

      if (start > 1) {
        visiblePages.push(1);
        if (start > 2) visiblePages.push("...");
      }

      for (let i = start; i <= end - 1; i++) visiblePages.push(i);

      if (end < totalPages) {
        if (end < totalPages - 1) visiblePages.push("...");
        visiblePages.push(totalPages);
      }
    }

    return visiblePages;
  };

  useLayoutEffect(() => {
    rowRefs.current = rowRefs.current.slice(0, currentRows.length);

    const validRefs = rowRefs.current.filter(
      (ref) => ref !== null && ref !== undefined
    );

    if (validRefs.length === 0) return;

    const currentSignature = getRowsSignature(
      currentRows,
      isDashboard || false
    );
    const hasContentChanged =
      currentSignature !== previousRowsSignatureRef.current;

    let shouldAnimate = false;

    if (isDashboard) {
      if (hasContentChanged && !hasAnimatedRef.current) {
        shouldAnimate = true;
      } else if (hasContentChanged && hasAnimatedRef.current) {
        shouldAnimate = true;
      } else {
        gsap.set(validRefs, {
          opacity: 1,
          y: 0,
        });
        previousRowsSignatureRef.current = currentSignature;
        return;
      }
    } else {
      shouldAnimate = hasContentChanged || !hasAnimatedRef.current;
    }

    previousRowsSignatureRef.current = currentSignature;

    if (currentRows.length > 20) {
      gsap.set(validRefs, {
        opacity: 1,
        y: 0,
      });
      hasAnimatedRef.current = true;
      return;
    }

    if (!shouldAnimate && hasAnimatedRef.current) {
      gsap.set(validRefs, {
        opacity: 1,
        y: 0,
      });
      return;
    }

    if (shouldAnimate) {
      gsap.set(validRefs, {
        opacity: 0,
        y: 20,
      });

      const animation = gsap.to(validRefs, {
        opacity: 1,
        y: 0,
        duration: 0.3,
        stagger: 0.1,
        ease: "power2.out",
      });

      hasAnimatedRef.current = true;

      return () => {
        if (animation) {
          animation.kill();
        }
      };
    }
  }, [currentRows, isDashboard]);

  useEffect(() => {
    if (showDates) {
      setCurrentPage(1);
      if (onChange) {
        onChange({
          page_size: itemsPerPage,
          page: 1,
          ...(searchTerm ? { search: searchTerm } : {}),
          ...(dateInfo.active
            ? { start: dateInfo?.date1, end: dateInfo?.date2 }
            : {}),
        });
      }
    }
  }, [showDates, dateInfo]);

  return (
    <motion.div
      variants={{
        visible: { x: 0, opacity: 1, filter: "blur(0px)" },
        hidden: { x: 75, opacity: 0, filter: "blur(8px)" },
      }}
      initial="hidden"
      animate="visible"
      transition={{ duration: 0.3, delay: 0.25 }}
      className={`${className} ${
        isDashboard && "rounded-2xl"
      }  xs:w-dvh lg:w-full`}
    >
      <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-2 w-full">
        <div className="flex items-center gap-2">
          <div
            className={`h-6 w-6 ${
              isDashboard
                ? "text-red-500 dark:text-red-300"
                : "text-gray-500 dark:text-gray-300"
            }`}
          >
            {isDashboard ? <CalendarIcon /> : <ListBulletIcon />}
          </div>
          {title && (
            <h2
              className={`text-md ${
                isDashboard
                  ? "text-red-500 dark:text-red-300"
                  : "text-gray-500 dark:text-gray-300"
              } font-semibold`}
            >
              {title}
            </h2>
          )}
          {excelInfo && (
            <div
              className="cursor-pointer md:md:border-b rounded-sm px-1 border-red-400 shadow-b-xl shadow-sky-50"
              onClick={() => {
                api
                  .get(excelInfo?.link || "", {
                    params: {
                      search: searchTerm,
                      ...(dateInfo.active
                        ? { start: dateInfo?.date1, end: dateInfo?.date2 }
                        : {}),
                    },
                    responseType: "blob",
                  })
                  .then((response) => {
                    const url = window.URL.createObjectURL(
                      new Blob([response.data])
                    );

                    const link = document.createElement("a");
                    link.href = url;

                    link.setAttribute("download", `${title}.xlsx`);

                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    window.URL.revokeObjectURL(url);
                  })
                  .catch((error) => {
                    console.error("Error downloading file:", error);
                  });
              }}
            >
              <Tooltip
                position="top"
                title={checkIsMobile() ? "" : excelInfo?.title || "خروجی اکسل"}
              >
                <DocumentArrowDownIcon className="text-primary-600 w-5 animate-pulse" />
              </Tooltip>
            </div>
          )}
        </div>

        <div
          className={`flex flex-col md:flex-row gap-2 w-full items-center md:w-auto ${
            !noSearch ? "md:min-w-60" : ""
          } mt-1 ${
            showDates &&
            "md:bg-linear-to-r from-primary-50 dark:from-dark-300/50 to-primary-50/10 dark:to-transparent rounded-lg p-1"
          } `}
        >
          {showDates && (
            <div className="flex items-center justify-center">
              <ToggleButton
                size="small"
                isActive={dateInfo.active}
                onClick={() => {
                  setDateInfo((prev: any) => ({
                    ...prev,
                    active: !prev.active,
                  }));
                }}
              />
              <DatePicker
                isTable
                disabled={!dateInfo.active}
                size="small"
                label=""
                onChange={(e) => {
                  setDateInfo((prev: any) => ({
                    ...prev,
                    date1: e,
                  }));
                }}
                placeholderColor="bg-gray-100 dark:bg-dark-600 border-dark-300"
              />
              <DatePicker
                isTable
                disabled={!dateInfo.active}
                className="mr-2"
                size="small"
                label="تا"
                onChange={(e) => {
                  setDateInfo((prev: any) => ({
                    ...prev,
                    date2: e,
                  }));
                }}
                placeholderColor="bg-gray-100 dark:bg-dark-600 border-dark-300"
              />
            </div>
          )}
          <div className="flex gap-2 items-center justify-start">
            <div className="relative grow">
              {!noSearch && (
                <div
                  className="absolute inset-y-0 left-0 pl-3 flex items-center cursor-pointer"
                  onClick={() => {
                    if (onChange) {
                      onChange({
                        page_size: itemsPerPage,
                        page: currentPage,
                        search: searchTerm,
                      });
                    }
                  }}
                >
                  <MagnifyingGlassIcon className="h-6 w-6 p-1 bg-primary-600 rounded-full text-white" />
                </div>
              )}
              {!noSearch && (
                <input
                  placeholder={isPaginated ? "جستجو + Enter" : "جستجو..."}
                  value={searchTerm}
                  onChange={(e) => {
                    setSearchTerm(e.target.value);
                    setCurrentPage(1);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && onChange) {
                      onChange({
                        page_size: itemsPerPage,
                        page: currentPage,
                        search: searchTerm,
                      });
                    }
                  }}
                  className={`block text-sm w-full pl-10 pr-3 ${
                    getSizeStyles("small").padding
                  } border border-dark-300 rounded-lg bg-gray-100 dark:bg-dark-600 text-dark-900 dark:text-dark-100 placeholder-dark-500 dark:placeholder-dark-100 focus:outline-none focus:ring-1 focus:ring-dark-400 focus:border-transparent`}
                />
              )}
            </div>
            <button
              onClick={() => setShowColumnFilter(!showColumnFilter)}
              className={`flex items-center gap-2 ${
                getSizeStyles("small").padding
              } rounded-lg border ${
                showColumnFilter
                  ? "bg-primary-600 text-white"
                  : "border-dark-300 rounded-lg bg-gray-100 dark:bg-dark-600 text-dark-500 dark:text-dark-100"
              }`}
            >
              <FunnelIcon className="h-4 w-4" />
              <span className="text-sm">فیلتر</span>
            </button>
            <button
              onClick={() => setStretchMode(!stretchMode)}
              className={` hidden md:flex  items-center gap-2 ${
                getSizeStyles("small").padding
              } rounded-lg border ${
                stretchMode
                  ? "border-dark-300 rounded-lg bg-gray-100 dark:bg-dark-600 text-dark-500 dark:text-dark-100"
                  : "bg-primary-600 text-white"
              }`}
            >
              <ArrowsPointingOutIcon className="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>

      <motion.div
        initial={{ opacity: 0, height: 0 }}
        animate={{
          opacity: showColumnFilter ? 1 : 0,
          height: showColumnFilter ? "auto" : 0,
        }}
        exit={{ opacity: 0, height: 0 }}
        transition={{ duration: 0.2, ease: "easeInOut" }}
        className="overflow-hidden"
      >
        <motion.div
          initial={{ y: -20 }}
          animate={{ y: showColumnFilter ? 0 : -20 }}
          transition={{ duration: 0.2 }}
          className="mb-4 p-4 bg-white dark:bg-dark-700 rounded-lg shadow-md border border-dark-200 dark:border-dark-600"
        >
          <div className="flex justify-end items-center mb-3">
            <div className="flex gap-2">
              <button
                onClick={resetColumnFilters}
                className="text-sm text-primary-600 dark:text-primary-400 hover:underline"
              >
                بازنشانی
              </button>
              <button
                onClick={() => setShowColumnFilter(false)}
                className="text-dark-500 dark:text-dark-300 hover:text-dark-700 dark:hover:text-dark-100"
              >
                <XMarkIcon className="h-5 w-5" />
              </button>
            </div>
          </div>
          <div className="grid grid-cols-3 md:grid-cols-3 lg:grid-cols-6 gap-3 items-center">
            {columns.map((column) => (
              <label
                key={column}
                className="flex items-center text-nowrap gap-2 text-[10px] sm:text-xs text-dark-700 dark:text-dark-200"
              >
                <Checkbox
                  checked={visibleColumns[column]}
                  onChange={() => toggleColumnVisibility(column)}
                />
                {column}
              </label>
            ))}
          </div>
        </motion.div>
      </motion.div>
      <div className={`w-full overflow-x-auto`}>
        <div className="w-full mb-2">
          <div className="hidden md:block w-full">
            <table className="min-w-full divide-y divide-dark-200 overflow-hidden">
              <thead className="bg-white">
                <tr className="">
                  {columns.map((column, index) =>
                    visibleColumns[column] ? (
                      <th
                        key={index}
                        onClick={() => handleColumnSort(index)}
                        className={`border-b border-black-300 dark:border-gray-300 ${
                          stretchMode
                            ? "px-3 py-2 text-[12px] font-bold"
                            : "px-6 py-3 text-sm font-bold"
                        }  text-center cursor-pointer select-none ${
                          stretchMode
                            ? "whitespace-normal"
                            : "whitespace-nowrap"
                        }  tracking-wider  ${
                          isDashboard
                            ? "bg-red-400 text-white"
                            : "bg-primary-50 text-dark-500 dark:text-dark-100 hover:bg-primary-100 dark:bg-dark-500 dark:hover:bg-dark-400"
                        }  ${index === 0 ? "rounded-tr-lg" : ""} ${
                          index === columns.length - 1 ? "rounded-tl-lg" : ""
                        }`}
                      >
                        <div className="flex items-center justify-center gap-1">
                          {isNumericColumn(index) &&
                          getColumnSum(index) <= 10000000000 &&
                          column !== "ردیف" ? (
                            <Tooltip
                              title={`مجموع: ${getColumnSum(
                                index
                              ).toLocaleString()}`}
                              position="top"
                            >
                              <span className="inline-block">{column}</span>
                            </Tooltip>
                          ) : (
                            <span>{column}</span>
                          )}
                          {sortColumn === index &&
                            sortDirection &&
                            (sortDirection === "desc" ? (
                              <ChevronDownIcon className="h-4 w-4" />
                            ) : (
                              <ChevronUpIcon className="h-4 w-4" />
                            ))}
                        </div>
                      </th>
                    ) : null
                  )}
                </tr>
              </thead>
              <tbody className="divide-y divide-dark-200 justify-center">
                {currentRows?.length > 0 ? (
                  currentRows?.map((row, rowIndex) => (
                    <tr
                      key={rowIndex}
                      ref={(el: HTMLTableRowElement | null) => {
                        if (el) {
                          rowRefs.current[rowIndex] = el;
                        } else {
                          rowRefs.current[rowIndex] = null;
                        }
                      }}
                      className={`${
                        rowIndex % 2 === 0
                          ? "bg-white dark:bg-dark-800"
                          : "bg-primary-50 dark:bg-dark-900"
                      } ${
                        !isDashboard &&
                        "hover:bg-primary-100 dark:hover:bg-dark-700 dark:hover:text-dark-100"
                      } ${
                        rowIndex === currentRows.length - 1
                          ? "[&>td:first-child]:rounded-br-lg [&>td:last-child]:rounded-bl-lg "
                          : "border-b border-black-50 dark:border-gray-600 "
                      }`}
                    >
                      {row.map((cell, cellIndex) =>
                        visibleColumns[columns[cellIndex]] ? (
                          <td
                            key={cellIndex}
                            className={`${
                              stretchMode ? "px-2 py-2" : "px-4 py-4"
                            } `}
                          >
                            <div
                              className={`text-center ${
                                stretchMode ? "text-xs" : "text-sm"
                              } flex justify-center ${
                                cellIndex === 0 && columns[0] === "ردیف"
                                  ? "text-gray2-900"
                                  : typeof cell === "string" &&
                                    cell.match(/^09\d{9}$/)
                                  ? "text-primary-600"
                                  : "text-gray2-700"
                              } dark:text-dark-100`}
                            >
                              {cell ? cell : cell === 0 ? 0 : "-"}
                            </div>
                          </td>
                        ) : null
                      )}
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td
                      colSpan={visibleColumnIndices.length || columns?.length}
                      className="px-6 py-4 text-center text-dark-500 dark:text-dark-300 rounded-b-lg"
                    >
                      نتیجه‌ای یافت نشد!
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {}
          <div className="block md:hidden mb-4">
            {currentRows?.length > 0 ? (
              <div className="space-y-4">
                {currentRows.map((row, idx) => (
                  <motion.div
                    key={`row-${idx}`}
                    layout
                    initial={{ scale: 1 }}
                    whileTap={{ scale: 0.96 }}
                    className="relative overflow-hidden rounded-3xl border border-gray-200 dark:border-dark-800 bg-white p-5 shadow-lg transition-transform duration-200 backdrop-blur-md  dark:bg-dark-600 "
                  >
                    <div className="mb-4 grid grid-cols-1 gap-4 ">
                      {row
                        .filter((_, i) => visibleColumns[columns[i]])
                        .slice(0, 6)
                        .map((cell, i) => (
                          <div
                            className="flex justify-between gap-4"
                            key={`cell-${idx}-${i}`}
                          >
                            <div className="text-right text-sm font-semibold text-nowrap sm:text-sm text-gray-700 dark:text-gray1-200">
                              {columns?.[i]}
                            </div>
                            <div className="truncate mr-2 text-wrap text-left text-sm font-semibold sm:text-sm text-gray-700 dark:text-gray1-200">
                              {cell || "-"}
                            </div>
                          </div>
                        ))}
                    </div>

                    {row.filter((_, i) => visibleColumns[columns[i]]).length >
                      6 && (
                      <div className="">
                        <motion.div
                          initial={{ opacity: 0, scale: 0.98, height: 0 }}
                          animate={
                            expandedRows.includes(idx)
                              ? { opacity: 1, scale: 1, height: "auto" }
                              : { opacity: 0, scale: 0.98, height: 0 }
                          }
                          transition={{ duration: 0.15, ease: "easeOut" }}
                          className="overflow-hidden"
                        >
                          <div className="mb-4 grid grid-cols-1 gap-4 mt-1 ">
                            {row
                              .filter((_, i) => visibleColumns[columns[i]])
                              .splice(6, row?.length)
                              .map((cell, i) => (
                                <div
                                  className="flex justify-between"
                                  key={`cell-${idx}-${i}`}
                                >
                                  <div className="text-right text-sm font-semibold text-nowrap sm:text-sm text-gray-700 dark:text-gray1-200">
                                    {columns?.[i + 6]}
                                  </div>
                                  <div className="truncate mr-2 text-wrap text-left text-sm font-semibold sm:text-sm text-gray-700 dark:text-gray1-200">
                                    {cell || "-"}
                                  </div>
                                </div>
                              ))}
                          </div>
                        </motion.div>

                        <button
                          onClick={() => toggleRow(idx)}
                          className="inline-flex w-full items-center justify-center gap-2 rounded-md bg-primary-500 px-3 py-1 text-sm font-semibold text-white transition duration-100 ease-in-out dark:bg-dark-400 dark:text-dark-100 dark:hover:bg-dark-500"
                        >
                          {expandedRows.includes(idx) ? (
                            <>
                              بستن
                              <ChevronUpIcon className="h-5 w-5" />
                            </>
                          ) : (
                            <>
                              نمایش همه
                              <ChevronDownIcon className="h-5 w-5" />
                            </>
                          )}
                        </button>
                      </div>
                    )}
                  </motion.div>
                ))}
              </div>
            ) : (
              <div className="relative rounded-3xl border border-primary-100 bg-linear-to-tr from-white to-primary-50 p-5 text-center text-sm text-dark-500 dark:text-dark-300 shadow-sm backdrop-blur-md dark:border-dark-700 dark:from-dark-700 dark:to-dark-800">
                <div className="absolute left-0 top-0 bottom-0 w-1 rounded-l-3xl" />
                نتیجه‌ای یافت نشد
              </div>
            )}
          </div>
        </div>
      </div>

      {showPagination &&
        !noPagination &&
        (isPaginated ? count || 1 : filteredRows?.length) > 10 && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.2 }}
            className="flex flex-col sm:flex-row items-center justify-between mt-4 gap-3 px-3 py-3 bg-linear-to-r from-gray-50 to-gray-100 dark:from-dark-700 dark:to-dark-800 rounded-lg border border-gray-200 dark:border-dark-600"
          >
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2">
                <label
                  htmlFor="page_size"
                  className="text-xs font-medium text-gray-700 dark:text-gray-300"
                >
                  نمایش:
                </label>
                <select
                  id="page_size"
                  value={itemsPerPage}
                  onChange={(e) => {
                    setItemsPerPage(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                  className="px-2 py-1 text-xs border border-gray-300 dark:border-dark-600 rounded-md bg-white dark:bg-dark-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                >
                  {[10, 20, 50, 100].map((size) => (
                    <option key={size} value={size}>
                      {size}
                    </option>
                  ))}
                </select>
              </div>
              {isPaginated && (
                <button
                  onClick={() => setIsLocked((prev) => !prev)}
                  className={`flex items-center gap-2 p-1 text-xs font-medium rounded-md border transition-colors ${
                    isLocked
                      ? "bg-primary-600 dark:bg-primary-700 text-white border-primary-600"
                      : "bg-gray-200/20 dark:bg-dark-600 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-dark-600 hover:bg-gray-100 dark:hover:bg-dark-600"
                  }`}
                >
                  {isLocked ? (
                    <LockClosedIcon className="h-4 w-4" />
                  ) : (
                    <LockOpenIcon className="h-4 w-4" />
                  )}
                </button>
              )}

              <div className="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400">
                <span>تعداد کل: </span>
                <span className="font-semibold text-primary-600 dark:text-primary-400">
                  {isPaginated
                    ? count?.toLocaleString()
                    : filteredRows?.length?.toLocaleString()}
                </span>
              </div>
            </div>

            {getVisiblePages()?.length > 1 && (
              <div className="flex items-center gap-0.5">
                <button
                  onClick={() => paginate(1)}
                  disabled={currentPage === 1}
                  className={`flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded-md transition-all duration-200 ${
                    currentPage === 1
                      ? "opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600"
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-600 hover:text-primary-600 dark:hover:text-primary-400"
                  }`}
                  aria-label="صفحه اول"
                >
                  <ChevronUpIcon className="w-3 h-3 rotate-90" />
                  <span className="hidden md:inline">اول</span>
                </button>

                <button
                  onClick={() => paginate(currentPage - 1)}
                  disabled={currentPage === 1}
                  className={`flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded-md transition-all duration-200 ${
                    currentPage === 1
                      ? "opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600"
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-600 hover:text-primary-600 dark:hover:text-primary-400"
                  }`}
                  aria-label="صفحه قبلی"
                >
                  <ChevronUpIcon className="w-3 h-3 rotate-90" />
                  <span className="hidden md:inline">قبلی</span>
                </button>

                <div className="flex items-center gap-0.5 mx-1">
                  {getVisiblePages().map((page, idx) =>
                    typeof page === "number" ? (
                      <button
                        key={idx}
                        onClick={() => paginate(page)}
                        className={`relative px-3 py-1.5 text-xs font-medium rounded-md transition-all duration-200 ${
                          page === currentPage
                            ? "bg-primary-600 text-white shadow-md shadow-primary-600/25"
                            : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-600 hover:text-primary-600 dark:hover:text-primary-400"
                        }`}
                        aria-current={page === currentPage ? "page" : undefined}
                      >
                        {page}
                        {page === currentPage && (
                          <motion.div
                            layoutId="activePage"
                            className="absolute inset-0 bg-primary-600 rounded-md -z-10"
                            initial={false}
                            transition={{
                              type: "spring",
                              stiffness: 500,
                              damping: 30,
                            }}
                          />
                        )}
                      </button>
                    ) : (
                      <span
                        key={idx}
                        className="px-1.5 py-1.5 text-xs text-gray-500 dark:text-gray-400"
                      >
                        {page}
                      </span>
                    )
                  )}
                </div>

                <button
                  onClick={() => paginate(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className={`flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded-md transition-all duration-200 ${
                    currentPage === totalPages
                      ? "opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600"
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-600 hover:text-primary-600 dark:hover:text-primary-400"
                  }`}
                  aria-label="صفحه بعدی"
                >
                  <span className="hidden md:inline">بعدی</span>
                  <ChevronDownIcon className="w-3 h-3 rotate-90" />
                </button>

                <button
                  onClick={() => paginate(totalPages)}
                  disabled={currentPage === totalPages}
                  className={`flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded-md transition-all duration-200 ${
                    currentPage === totalPages
                      ? "opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-600"
                      : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-600 hover:text-primary-600 dark:hover:text-primary-400"
                  }`}
                  aria-label="صفحه آخر"
                >
                  <span className="hidden md:inline">آخر</span>
                  <ChevronDownIcon className="w-3 h-3 rotate-90" />
                </button>
              </div>
            )}
          </motion.div>
        )}
    </motion.div>
  );
};

export default Table;
