import React, { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import Pagination from '@/components/tables/Pagination2';
import { useUiLoadingStore } from "@/lib/_AG";


interface CtTableDefineProps {
  title: string;
  key: string;
  renderCol?: (item: any, colIndex: number) => React.ReactNode;
  renderItem?: (item: any, rowIndex: number) => React.ReactNode;
}

interface CtTable1Props {
  columns: CtTableDefineProps[];
  bodyData: any[];
  offset: number;
  totalCount: number;
  countPerPage: number;
  pageNumCount: number;
  onClickRow?: (rowIndex: number) => void;
  onClickCell?: (rowIndex: number, colIndex: number, cellData?: any) => void;
  onClickPageChange?: (page: number) => void;
  hoverRowClassName?: string;
  hoverCellClassName?: string;
  useCheckbox?: boolean;
  selectedRows?: number[];
  onChangeSelectedRows?: (newSelectedRows: number[]) => void;
  getRowId?: (rowItem: any, rowIndex: number) => number;
  isLoading?: boolean;
}


// Props for TableRow
interface CtTableRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  children: React.ReactNode; // Cells (th or td)
  className?: string; // Optional className for styling
}

// TableRow Component
const CtTableRow: React.FC<CtTableRowProps> = ({ children, className, ...props }) => {
  return <tr className={className} {...props}>{children}</tr>;
};

// Props for TableCell
interface CtTableCellProps extends React.HTMLAttributes<HTMLTableCellElement> {
  children: React.ReactNode;
  className?: string;
}

// TableCell Component
const CtTableCell: React.FC<CtTableCellProps> = ({ children, className, ...props }) => {
  return <td className={className} {...props}>{children}</td>;
};

const CtTable1: React.FC<CtTable1Props> = ({
  columns,
  bodyData,
  offset,
  totalCount,
  countPerPage,
  pageNumCount,
  onClickRow,
  onClickCell,
  onClickPageChange,
  hoverRowClassName,
  hoverCellClassName,
  useCheckbox = false,
  selectedRows = [],
  onChangeSelectedRows,
  getRowId,
  isLoading,
}) => {
  const tableLoading = useUiLoadingStore((s) => s.isTableLoading);
  const loading = isLoading ?? tableLoading;
  //console.log("columns", columns);
  const [totalPages, setTotalPages] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(0);

  useEffect(() => {
    setTotalPages(Math.floor((totalCount - 1) / countPerPage) + 1);
    setCurrentPage(Math.floor(offset / countPerPage) + 1);
    //const startPage = currentPage - ((currentPage - 1) % pageNumCount);
    
    //console.log("totalPages: " + totalPages)
    //console.log("currentPage: " + currentPage)        
  }, [offset, totalCount, countPerPage]);


  // 전체 체크된 상태인지 확인
  const allChecked =
    bodyData.length > 0 &&
    selectedRows.length === bodyData.length &&
    bodyData.every((item, index) =>
      selectedRows.includes(getRowId ? getRowId(item, index) : index)
    );

  // 전체 선택 / 해제
  const onClickSelectAll = (checked: boolean) => {
    const newRows = checked
      ? bodyData.map((item, index) =>
        getRowId ? getRowId(item, index) : index
      )
      : [];

    onChangeSelectedRows?.(newRows);
  };

  // 개별 선택
  const onClickSelectRow = (rowIndex: number, checked: boolean) => {
    const rowItem = bodyData[rowIndex];
    const key = getRowId ? getRowId(rowItem, rowIndex) : rowIndex;

    const newRows = checked
      ? [...selectedRows, key]
      : selectedRows.filter((x) => x !== key);

    onChangeSelectedRows?.(newRows);
  };

  return (
    <div className="col-span-12">
      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-white/[0.05] dark:bg-white/[0.03]">
        <div className="max-w-full overflow-x-auto">
          <div className="min-w-[1280px]">
            <Table>
              <TableHeader className="border-b border-gray-100 dark:border-white/[0.05]">
                <TableRow>
                  {useCheckbox && (
                    <TableCell className="px-5 py-3 w-[40px]">
                      <input
                        type="checkbox"
                        checked={allChecked}
                        onChange={(e) => onClickSelectAll(e.target.checked)}
                      />
                    </TableCell>
                  )}
                  {columns.map((column, index) => (
                    <TableCell
                      key={index}
                      isHeader
                      className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400"
                    >
                      {column.title}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHeader>
              <TableBody className="divide-y divide-gray-100 dark:divide-white/[0.05]">
                {loading ? (
                  Array.from({ length: 4 }).map((_, rowIndex) => (
                    <CtTableRow key={`skeleton-${rowIndex}`}>
                      {useCheckbox && (
                        <CtTableCell className="px-4 w-[40px] text-center">
                          <div className="mx-auto h-3 w-3 animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
                        </CtTableCell>
                      )}
                      {columns.map((_, colIndex) => (
                        <CtTableCell
                          key={`skeleton-col-${colIndex}`}
                          className="px-4 py-3 text-start text-theme-sm text-gray-600 dark:text-gray-400"
                        >
                          <div className="h-3 w-2/3 max-w-[120px] animate-pulse rounded bg-gray-200 dark:bg-gray-700"></div>
                        </CtTableCell>
                      ))}
                    </CtTableRow>
                  ))
                ) : (
                  bodyData.map((item, rowIndex) => (
                    <CtTableRow
                      key={rowIndex}
                      onClick={() => onClickRow?.(rowIndex)}
                      className={`cursor-pointer transition-colors ${hoverRowClassName ? hoverRowClassName : "hover:bg-blue-50 dark:hover:bg-blue-900/20"}`}
                    >
                      {useCheckbox && (
                        <CtTableCell className="px-4 w-[40px] text-center">
                          <input
                            type="checkbox"
                            checked={selectedRows.includes(getRowId ? getRowId(item, rowIndex) : rowIndex)}
                            onChange={(e) =>
                              onClickSelectRow(rowIndex, e.target.checked)
                            }
                          />
                        </CtTableCell>
                      )}
                      {columns.map((column, colIndex) => (
                        <CtTableCell
                          key={colIndex}
                          className={`px-4 py-3 text-start text-theme-sm text-gray-600 dark:text-gray-400 transition-colors ${hoverCellClassName}`}
                          onClick={() => onClickCell?.(rowIndex, colIndex, item[column.key])}
                        >
                          {column.renderItem ? column.renderItem(item, rowIndex)
                              : item[column.key] ? item[column.key] : ""}
                        </CtTableCell>
                      ))}
                    </CtTableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>
      <div className="mt-5 flex justify-end">
        <Pagination currentPage={currentPage} totalPages={totalPages} pageNumCount={pageNumCount} onPageChange={onClickPageChange || (() => { })} />
      </div>
    </div>
  );
};

export default CtTable1;
