import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Checkbox, Card } from "antd";
import OperationTableCard from "./OperationTableCard";
import { setAllListData } from "../../store/AllOperationListSlice";
import { setErrorListData } from "../../store/ErrorOperationListSlice";
import { setDuringListData } from "../../store/DuringOperationListSlice";
import DisplayExecuteModalList from "../../components/dialogs/displayExecuteModalList/DisplayExecuteModalList";
import UpdateScheduleDialog from "../../components/dialogs/updateScheduleDialog/UpdateScheduleDialog";
import "./JobExecutionManagement.scss";
import { SESSION_STORAGE } from "../../constants";
import JobExecutionManagementService from "../../services/JobExecutionManagementService";
import { useDispatch } from "react-redux";
import store from "../../store";
import moment from "moment";
import { setStandardTime, setTimeZone } from "../../store/TimeZoneSlice";


const JobExecutionManagement = ({ category = "jobnet", publicType = true }) => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const [checkOptions, setCheckOptions] = useState(
    JSON.parse(
      sessionStorage.getItem(SESSION_STORAGE.JOB_EXEC_MANAGE_TABLE_VIEW)
    ) ?? [t("situation-list"), t("err-jobnet-list"), t("during-exec-list")]
  );
  const viewOptions = [
    t("situation-list"),
    t("err-jobnet-list"),
    t("during-exec-list"),
  ];

  // useEffect(() => {
  //  loadAllScripts();
  // }, []);

  function getCurrentDateTime() {
  const now = new Date();
  const pad = (num) => num.toString().padStart(2, '0');
 
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hours = pad(now.getHours());
  const minutes = pad(now.getMinutes());
  const seconds = pad(now.getSeconds());
 
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}
 
// Example
// console.log(getCurrentDateTime()); 
// 👉 e.g. "20250825151243"
 
 
  const getAllOperationList = async () => {
    const currentTz = moment.tz.guess();
    const payload = {
      date: getCurrentDateTime(),
      timezone: currentTz
    };
    //console.log("Payload", payload);
 
    const result =
      await JobExecutionManagementService.getAllOperationList(payload).then(
        (result) => {
          let prepareData = result.detail.data.filter(
            (item) =>
              !store
                .getState()
                .allOperationList.hideRow.includes(item?.inner_jobnet_id)
          );
          dispatch(setAllListData(prepareData));
          return prepareData;
        }
      );
    return result;
  };
  
  const getTimeZone = async () => {
    try {
      const result = await JobExecutionManagementService.getTimeZone();
      // console.log("Get time zone result", result);
      // dispatch(setTimeZone(result?.detail?.data))
      return result;
    } catch (error) {
      console.error('Error fetching timezone:', error);
      throw error; // or handle error as needed
    }
  };
  
  const getStandardTime = async () => {
    try {
      const result = await JobExecutionManagementService.getJobArrangerStandardTime();
      console.log("Get standard time result", result);
      // dispatch(setStandardTime(result?.detail?.data))
      return result;
    } catch (error) {
      console.error('Error fetching standard time :', error);
      throw error; // or handle error as needed
    }
  }

  const getErrorOperationList = async () => {
    const result = JobExecutionManagementService.getErrorOperationList().then(
      (result) => {
        let prepareData = result.detail.data.filter(
          (item) =>
            !store
              .getState()
              .errorOperationList.hideRow.includes(item.inner_jobnet_id)
        );
        dispatch(setErrorListData(prepareData));
        return prepareData;
      }
    );
    return result;
  };

  const getDuringOperationList = async () => {
    const result = JobExecutionManagementService.getDuringOperationList().then(
      (result) => {
        let prepareData = result.detail.data.filter(
          (item) =>
            !store
              .getState()
              .duringOperationList.hideRow.includes(item.inner_jobnet_id)
        );
        dispatch(setDuringListData(prepareData));
        return prepareData;
      }
    );
    return result;
  };

    useEffect(() => {
        const fetchTimeZone = async () => {
            const result = await getTimeZone();
            // console.log("Time zone data", timezone);
            dispatch(setTimeZone(result?.detail?.data))
        }
    
        fetchTimeZone();
    }, [])
  
      useEffect(() => {
        const fetchStandardTime = async () => {
          const result = await getStandardTime();
          dispatch(setStandardTime(result?.detail?.data))
        }
    
        fetchStandardTime();   
    }, [])

  const onChange = (checkedValues) => {
    sessionStorage.setItem(
      SESSION_STORAGE.JOB_EXEC_MANAGE_TABLE_VIEW,
      JSON.stringify(checkedValues)
    );
    setCheckOptions(checkedValues);
  };

  const renderAllInfoTable = (checkOptions) => {
    if (checkOptions.includes(t("situation-list"))) {
      return (
        <>
          <OperationTableCard
            key={"all"}
            stateId={"allOperationList"}
            dispatchAction={getAllOperationList}
            tableType={t("title-op-info-job")}
            color={"#40a9ff"}
          />
          <UpdateScheduleDialog />
        </>
      );
    }
  };

  const renderErrorInfoTable = (checkOptions) => {
    if (checkOptions.includes(t("err-jobnet-list"))) {
      return (
        <OperationTableCard
          key={"error"}
          stateId={"errorOperationList"}
          dispatchAction={getErrorOperationList}
          tableType={t("title-op-err-job")}
          color={"#f00"}
        />
      );
    }
  };

  const renderDuringInfoTable = (checkOptions) => {
    if (checkOptions.includes(t("during-exec-list"))) {
      return (
        <OperationTableCard
          key={"warning"}
          stateId={"duringOperationList"}
          dispatchAction={getDuringOperationList}
          tableType={t("title-op-exe-job")}
          color={"#c4cf21"}
        />
      );
    }
  };

  return (
    <>
      <Card
        bordered={false}
        style={{
          height: 60,
        }}
      >
        <Checkbox.Group
          options={viewOptions}
          defaultValue={checkOptions}
          onChange={onChange}
        />
      </Card>
      {renderAllInfoTable(checkOptions)}
      {renderErrorInfoTable(checkOptions)}
      {renderDuringInfoTable(checkOptions)}
      <DisplayExecuteModalList />
    </>
  );
};

export default JobExecutionManagement;
