"use client";
import { Alert, Form, Image, Table } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/LeadsLimitation.module.scss";
import { useEffect, useState } from "react";
import { useRequest } from "@/components/App/request";
import { formatDate, formatDateWithFormatType, toastrC } from "@/utils/helpers";
import useFetchData from "@/components/App/useFetchData";
import { useApp } from "@/components/App";
import TableNoData from "@/components/common/TableNoData";
import PaginationComp from "@/Layout/Component/Pagination/pagination";

/*!SECTION{
    "id": 1,
    "member_id": 19,
    "action": 1,
    "created_at": "2025-03-21T11:50:09.000000Z",
    "updated_at": "2025-03-21T11:50:09.000000Z",
    "day": "Friday"
}*/
interface LogsResponse {
  id: number;
  member_id: number;
  action: number;
  created_at: string;
  updated_at: string;
  day: string;
  performedby: {
    id: number;
    company_name: string;
  };
}
const PauseAccount = () => {
  const { userDetail, setUserDetail } = useApp();
  // console.log('df', userDetail);
  const [dependency, setDependency] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPagesVal, setTotalPagesVal] = useState(10);
  const { request } = useRequest();

  const { data: logData, isLoading } = useFetchData<{
    data: LogsResponse[];
    total: number;
    per_page: number;
  }>("MEMBER_PAUSE_UNPAUSE_LOGS", { page: currentPage }, [
    dependency,
    currentPage
  ]);

  const handlePageChange = page => {
    setCurrentPage(page);
  };

  const handlePauseAccount = async () => {
    try {
      const res = await request("PAUSE_STATUS_UPDATE", {
        pause_status: userDetail?.pause_unpause_status ? 0 : 1
      });
      toastrC(res.message, "success", "success");
      setDependency(prev => prev + 1);
      setUserDetail({
        ...userDetail,
        pause_unpause_status: userDetail?.pause_unpause_status ? 0 : 1
      });
    } catch (e) {
      // toastrC(e.message, "success", "success");
       toastrC(e.message, "error", "Error");
    }
  };

  useEffect(() => {    
    if (logData) {
      const respData = logData;
      const totalData = respData?.total || 1,
      perPages = respData?.per_page || 1;
      const tp = Math.ceil(totalData / perPages);
      setTotalPagesVal(tp);
    }
  }, [logData]);

  return (
    
    <div className={styles.PauseAccountBlock}>
      <h1>
        Pause Account
        <Form.Check
          type="switch"
          id="custom-switch"
          checked={Boolean(userDetail?.pause_unpause_status)}
          onChange={() => handlePauseAccount()}
          className="custom-switch ms-4"
          disabled={userDetail?.is_pause_admin === 1}
        />
      </h1>

      {(userDetail?.is_pause_admin) === 1 ? (
            <>
            <Alert
              variant="danger"
              className="mt-2 p-2 small"
            >
              <p> Your account has been pause by admin.</p>
            </Alert>
            </>
          ) : null}

      <div className="customTableCard text-center">
        <Table responsive>
          <thead>
            <tr>
              <th>S.No</th>
              <th className="dateTh">Date</th>
              <th>Day</th>
              <th>Time</th>
              <th>Action By</th>
              <th className="actionTh">Action</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(logData?.data) ? (
              logData?.data.map((item, index) => (
                <tr key={index}>
                  <td>{index + 1}</td>
                  <td>{formatDate(item.created_at)}</td>
                  <td>{item.day}</td>
                  <td>
                    {formatDateWithFormatType(item.created_at, "HH:mm:ss")}
                  </td>
                  <td>
                    {item.performedby != null
                      ? item.performedby.id == 1
                        ? "Admin"
                        : item.performedby.company_name
                      : "-"}
                  </td>
                  <td>
                    {!(item.action === 1) ? (
                      <Image src="/assets/playBtn.png" alt="playBtn" />
                    ) : (
                      <Image src="/assets/pauseIcon.png" alt="pauseIcon" />
                    )}
                  </td>
                </tr>
              ))
            ) : (
              <TableNoData isLoading={isLoading} colSpan={4} />
            )}
          </tbody>
        </Table>
      </div>
      <PaginationComp
        // styles={styles}
        totalPages={totalPagesVal}
        currentPage={currentPage}
        onPageChange={handlePageChange}
      />
    </div>
  );
};

export default PauseAccount;
