import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import TimePicker from "../common/TimePicker";
import { usePositionTracker } from "../../hooks/usePositionTracker";
import { useDispatch, useSelector } from "react-redux";
import { markAttendance } from "../../slices/apiSlice/attedanceLogsSlice";
import showToast from "../../services/toastService";
import {checkIfCurrentDate} from "../../utils/dateUtils";


const schema = z.object({
  time: z.string().nonempty({message:"Time is required"}), 
  description:z.string().optional()
});

const CheckCheckOutmodel = ({modeldata,closeModal,handleSubmitForm,}) => {

  const projectId = useSelector((store)=>store.localVariables.projectId)
  const [isLoading, setIsLoading] = useState(false);
  const coords = usePositionTracker();
  const dispatch = useDispatch()

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
  } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = ( data ) =>
  {
    console.log(data)
    let record = {...data, date: new Date().toLocaleDateString(),latitude:coords.latitude,longitude:coords.longitude,employeeId:modeldata.employeeId,action:modeldata.action}
   if(modeldata.forWhichTab === 1){
    handleSubmitForm(record)
   } else
   {
     console.log("is Date" ,checkIfCurrentDate(modeldata?.currentDate))
     if ( modeldata?.currentDate && checkIfCurrentDate(modeldata?.currentDate) )
     {
      handleSubmitForm(record)
     } else
     {
      let formData = {...data, date: new Date().toLocaleDateString(),latitude:coords.latitude,longitude:coords.longitude,employeeId:modeldata.employeeId,projectId:projectId,action:modeldata.action}
      dispatch(markAttendance(formData))
      .unwrap()
      .then(() => {
        showToast("Attendance Marked Successfully", "success");
      })
      .catch((error) => {
        showToast(error, "error");
      });
     }
     }
    
    closeModal()
  };

  return (
 
   
    <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
    
      <div className="col-12 col-md-12">
        {/* <TimePicker label="Time" onChange={(e) => setValue("time", e)} /> */}

        <TimePicker 
        label="Choose a time" 
        onChange={(e) => setValue("time", e)}  
        interval={10}  
      />
        {errors.time && <p className="text-danger">{errors.time.message}</p>}
      </div>

    
      <div className="col-12 col-md-12">
        <label className="form-label" htmlFor="description">
          Description
        </label>
        <textarea
          rows="3"
          name="description"
          className="form-control"
          {...register("description")}
        />
        {errors.description && (
          <p className="text-danger">{errors.description.message}</p>
        )}
      </div>

     
      <div className="col-12 text-center">
        <button type="submit" className="btn btn-sm btn-primary me-3">
          {isLoading ? "Please Wait..." : "Submit"}
        </button>
        <button
          type="reset"
          className="btn btn-sm btn-label-secondary"
          data-bs-dismiss="modal"
          aria-label="Close"
          onClick={()=>closeModal()}
        >
          Cancel
        </button>
      </div>
    </form>

  )
}


export default CheckCheckOutmodel;


const schemaReg = z.object({
  description:z.string().min(1,{message:"please give reason!"})
});
export const Regularization = ({modeldata,closeModal,handleSubmitForm})=>{
  const [isLoading, setIsLoading] = useState(false);
  const coords = usePositionTracker();
   console.log(modeldata)
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schemaReg),
  });

  const getCurrentDate = () => {
    const today = new Date();
    return today.toISOString().split("T")[0]; 
  };

  
  const onSubmit = (data) => {
    let record = {...data, date: new Date().toLocaleDateString(),latitude:coords.latitude,longitude:coords.longitude}

    
    handleSubmitForm(record)
    closeModal()
  };

  return (
 
   
    <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
      
      <div className="col-12 col-md-12">
      <p>Regularize Attendance</p>
        <label className="form-label" htmlFor="description">
          Description
        </label>
        <textarea
          rows="3"
          name="description"
          className="form-control"
          {...register("description")}
        />
        {errors.description && (
          <p className="danger-text">{errors.description.message}</p>
        )}
      </div>

     
      <div className="col-12 text-center">
        <button type="submit" className="btn btn-sm btn-primary me-3">
          {isLoading ? "Please Wait..." : "Submit"}
        </button>
        <button
          type="reset"
          className="btn btn-sm btn-label-secondary"
          data-bs-dismiss="modal"
          aria-label="Close"
          onClick={()=>closeModal()}
        >
          Cancel
        </button>
      </div>
    </form>

  )
}