import React, { act, useEffect, useState } from 'react'
import useAttendanceStatus, { ACTIONS } from '../../hooks/useAttendanceStatus';
import { useDispatch, useSelector } from 'react-redux';
import { usePositionTracker } from '../../hooks/usePositionTracker';
import {cacheData, getCachedData, useSelectedProject} from '../../slices/apiDataManager';
import showToast from '../../services/toastService';
import { useMarkAttendance } from '../../hooks/useAttendance';
import { useQueryClient } from '@tanstack/react-query';


const RegularizationActions = ({attendanceData,handleRequest,refresh}) => {
const [status,setStatus] = useState()
const [loadingApprove,setLoadingForApprove] = useState(false)
const [loadingReject,setLoadingForReject] = useState(false)
const {mutate:MarkAttendance,isPending} = useMarkAttendance()
const queryClient = useQueryClient()

// const projectId = useSelector((store)=>store.localVariables.projectId)
const projectId = useSelectedProject();
const {latitude,longitude} = usePositionTracker();
const dispatch = useDispatch()

  const handleRegularization =(request_attendance,IsReqularize)=>{
 
    if(IsReqularize){
      setLoadingForApprove(true)
    }else{
      setLoadingForReject(true)
    }

    let payload = {
      id:request_attendance.id || null,
      comment: ` ${IsReqularize ? "Approved" : "Rejected"}! regularization request`,
      employeeID:request_attendance?.employeeId,
      projectId:projectId,
      date:new Date().toISOString(),
      markTime:new Date().toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }),
      latitude:latitude.toString(),
      longitude: longitude.toString(),
      action:IsReqularize ? 4 : 5,
      image:null 
    }
     

    MarkAttendance(
    { payload, forWhichTab: 3 },
    {
      onSuccess: () => {
       queryClient.invalidateQueries({queryKey:["regularizedList"]})
         if (IsReqularize) {
          setLoadingForApprove(false);
        } else {
          setLoadingForReject(false);
        }
        showToast(`Successfully ${IsReqularize ? "approved" : "rejected"}`, "success");
      },
      onError: (error) => {
        showToast(error.message || "Failed to submit", "error");
        if (IsReqularize) {
          setLoadingForApprove(false);
        } else {
          setLoadingForReject(false);
        }
      },
    }
  );
  
  //   dispatch( markCurrentAttendance( req_Data ) ).then( ( action ) =>
  //   {

  //     const regularizedList = getCachedData("regularizedList")
      
  //     const updatedata = regularizedList?.data?.filter( item => item.id !== action.payload.id );
     
  //     cacheData("regularizedList",{data:updatedata,projectId:projectId})
  //     setLoadingForApprove( false )
  //     setLoadingForReject( false )
  //     refresh()
  //  }).catch( ( error ) =>
  //   {
  //     showToast(error.message,"error")
  // });
    
    
  }

  useEffect(()=>{
    const  {activity,checkInTime,checkOutTime} = attendanceData;
      if (activity === 2 && checkInTime !== null ||  checkOutTime !== null) {
        setStatus({
          status: "Approve",
          action: ACTIONS.APPROVED,
          disabled: false,
          text: "Approve",
          color: 'btn-success',
        });
      }
  },[attendanceData])


  return (
    <div className="w-auto d-flex gap-2 align-items-center justify-content-end">
   {attendanceData.activity == 2 && (  
    <>
      <button
        type="button"
        className={`btn btn-success btn-${loadingApprove ? "sm":"xs"} ${status?.color}`}
        tabIndex="0"
        aria-controls="DataTables_Table_0"
        data-bs-toggle="modal"
        data-bs-target="#check-Out-modal"
        onClick={()=>handleRegularization(attendanceData,true)}
        disabled={status?.disabled || loadingApprove} 
      >
        {loadingApprove ? (
          <>
            <span className="spinner-border spinner-border-md" role="status" aria-hidden="true"></span>
            <span className="visually-hidden">Loading...</span>
          </>
        ) : (
          status?.text
        )}
      </button>
   
      <button
        type="button"
        className={`btn btn-danger btn-${loadingReject ? "sm":"xs"} ${status?.color}`}
        tabIndex="0"
        aria-controls="DataTables_Table_0"
        data-bs-toggle="modal"
        onClick={()=>handleRegularization(attendanceData,false)}
        disabled={status?.disabled || loadingReject} 
      >
        {loadingReject ? (
          <>
            <span className="spinner-border spinner-border-md" role="status" aria-hidden="true"></span>
            <span className="visually-hidden">Loading...</span>
          </>
        ) : (
          "Reject"
        )}
      </button>
      </>
    )}
  </div>
  )
}

export default RegularizationActions