"use client";
import { Table } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/AreaSelectionLog.module.scss";
import useFetchData from "@/components/App/useFetchData";
import { SuspenseLoader } from "@/components/App/Loader";
import PaginationComp from "@/Layout/Component/Pagination/pagination";
import { useEffect, useState } from "react";
interface AreaSelectionLogData {
  id: number;
  date: string;
  time: string;
  area_selected: string;
  area_deselected: string;
  current_selection: string;
  area_total: string;
  performed_by: number | null;
  member_id: number | null;
  member: {
    id?: number; // Optional to handle null cases
    company_name?: string; // Optional to handle null cases
    [key: string]: unknown; // Allow additional dynamic fields
  } | null;
  admin: {
    id?: number; // Optional to handle null cases
    name?: string; // Optional to handle null cases
    [key: string]: unknown; // Allow additional dynamic fields
  } | null;
}

const AreaSelectionLog = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPagesVal, setTotalPagesVal] = useState(10);
  const { data, isLoading } = useFetchData<{
    data: AreaSelectionLogData[];
    total: number;
    per_page: number;
  }>("SELECTED_AREA_LOGS", { page: currentPage }, [currentPage]);

  // <-------------------TEMP SAMPLE PAGINATION---------------------->
  // const postsPerPage = 5;
  // const allPosts = [
  //   'Post 1', 'Post 2', 'Post 3', 'Post 4', 'Post 5',
  //   'Post 6', 'Post 7', 'Post 8', 'Post 9', 'Post 10',
  //   'Post 11', 'Post 12', 'Post 13', 'Post 14', 'Post 15',
  // ]; // Example list of posts
  // const totalPages = Math.ceil(allPosts.length / postsPerPage);
  // const totalPages = 55;
  const handlePageChange = page => {
    setCurrentPage(page);
  };
  // <-------------------TEMP SAMPLE PAGINATION---------------------->

  useEffect(() => {
    if (data) {
      const respData = data;
      const totalData = respData?.total || 1,
        perPages = respData?.per_page || 1;

      const tp = Math.ceil(totalData / perPages);
      // console.log("setting total pages value ======>",tp);
      setTotalPagesVal(tp);
    }
  }, [data]);

  if (isLoading) return <SuspenseLoader />;
  return (
    <div className={styles.AreaSelectionLogBlock}>
      <h1>Area Selection Log</h1>
      <div className="customTableCard text-center">
        <Table responsive>
          <thead>
            <tr>
              <th>S.No</th>
              <th>Date</th>
              <th>Time</th>
              <th>Select </th>
              <th>DeSelect</th>
              <th>Select Area</th>
              <th>Area Total</th>
              <th>Action By</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(data?.data) && data?.data?.length > 0 ? (
              data?.data?.map((record, index) => (
                <tr key={index}>
                  <td width="5%">{index + 1}</td>
                  <td width="7%">{record?.date}</td>
                  <td width="7%">
  {record?.time
    ? (() => {
        const [h, m] = record.time.split(":");
        const newHour = (parseInt(h, 10) + 1) % 24;
        return `${String(newHour).padStart(2, "0")}:${m}`;
      })()
    : "-"}
</td>
                  <td width="7%">{record?.area_selected || "-"}</td>
                  <td width="7%">{record?.area_deselected || "-"}</td>
                 <td
                  style={{
                      textAlign: "left",
                      whiteSpace: "normal",
                      overflowWrap: "break-word", // or wordBreak: "break-word"
                      lineHeight: 1.3,  // reasonable tight line height
                      fontSize: "14px",
                      verticalAlign: "middle"
                    }}
                  >
                    {record?.current_selection}
                  </td>
                  <td>{record?.area_total}</td>
                  <td>
                    {record?.performed_by != null
                      ? record?.performed_by == record?.member_id
                        ? record?.member?.company_name
                        : record?.admin?.name
                      : "-"}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={10} className="text-center">
                  No data available
                </td>
              </tr>
            )}
          </tbody>
        </Table>
      </div>
      <PaginationComp
        totalPages={totalPagesVal}
        currentPage={currentPage}
        onPageChange={handlePageChange}
      />
    </div>
  );
};

export default AreaSelectionLog;
