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({
  markTime: z.string().nonempty({ message: "Time is required" }),
  description: z.string().max(200, "description should less than 200 chracters").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 today = new Date().toISOString().split('T')[0];

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

  const onSubmit = (data) => {
    let record = { ...data, date: new Date().toLocaleDateString(), latitude: coords.latitude, longitude: coords.longitude, employeeId: modeldata.employeeId, action: modeldata.action, id: modeldata?.id || null }
    if (modeldata.forWhichTab === 1) {
      handleSubmitForm(record)
    } else {

      //  if ( modeldata?.currentDate && checkIfCurrentDate( modeldata?.currentDate ) )
      //  {
      dispatch(markAttendance(record))
        .unwrap()
        .then((data) => {

          showToast("Attendance Marked Successfully", "success");
        })
        .catch((error) => {

          showToast(error, "error");

        });

      //  } else
      //  {
      //   let formData = {...data, date: new Date().toLocaleDateString(),latitude:coords.latitude,longitude:coords.longitude,employeeId:modeldata.employeeId,projectId:projectId,action:modeldata.action,id:modeldata?.id || null}
      //  }
    }

    closeModal()
  };

  return (


    <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>

      <div className="col-12 col-md-12">
        <label className="fs-5 text-dark text-center d-flex align-items-center flex-wrap">
          {modeldata?.checkInTime && !modeldata?.checkOutTime ? 'Check-out :' : 'Check-in :'}
        </label>
      </div>

      <div className="col-6 col-md-6 ">
        <label className="form-label" htmlFor="checkInDate">
          {modeldata?.checkInTime && !modeldata?.checkOutTime ? 'Check-out Date' : 'Check-in Date'}
        </label>
        <input
          type="text"
          id="checkInDate"
          className="form-control"
          value={today}
          disabled
        />
      </div>

      <div className="col-6 col-md-6">
        <TimePicker
          label="Choose a time"
          onChange={(e) => setValue("markTime", e)}
          interval={10}
          checkOutTime={modeldata?.checkOutTime}
          checkInTime={modeldata?.checkInTime}
        />
        {errors.markTime && <p className="text-danger">{errors.markTime.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")}
          maxLength={200}
        />
        {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();

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

  const getCurrentDate = () => {
    const today = new Date();
    return today.toLocaleDateString('en-CA');
  };


  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>

  )
}