import React, { useState,useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import useMaster from "../../hooks/masterHook/useMaster";
import { employee } from "../../data/masters";
import { useForm, Controller } from "react-hook-form";
import { z } from "zod";
import { getCachedData } from "../../slices/apiDataManager";
import {useModal} from "../../ModalContext";
import {useProjects} from "../../hooks/useProjects";
import {useEmployeesAllOrByProjectId} from "../../hooks/useEmployees";
import {TasksRepository} from "../../repositories/ProjectRepository";
import showToast from "../../services/toastService";


const schema = z.object({
  selectedEmployees: z.array( z.number() ).min( 1, {message: "At least one employee must be selected"} ), 
  description: z.string().min( 1, {message: "description required"} ),
  pannedTask: z.number()
  .refine(value => value > 0, { message: "pannedTask should be greater than zero" })
  .refine(value => value !== undefined, { message: "pannedTask is required" }),
})


const AssignRoleModel = ( {assignData,onClose}) => {
  const { openModal, closeModal } = useModal()
  const selectedProject = useSelector((store)=>store.localVariables.projectId)
  const {employees} = useEmployeesAllOrByProjectId( selectedProject )

const dispatch = useDispatch()
const {data,loading} = useMaster()
const jobRoleData = getCachedData("Job Role")


const [selectedRole, setSelectedRole] = useState("all");
const [selectedEmployees, setSelectedEmployees] = useState([]);


const { handleSubmit, control, setValue, watch, formState: { errors } } = useForm({
  defaultValues: {
    selectedEmployees: [],
    description:""
  },
  resolver: (data) => {
    const validation = schema.safeParse(data);
    if (validation.success) return { values: data, errors: {} };
    return { values: {}, errors: validation.error.formErrors.fieldErrors };
  },
});

const handleRoleChange = (event) => {
  setSelectedRole(event.plannedTask.value);
};


const filteredEmployees = selectedRole === "all"
  ? employees
  : employees.filter((emp) => emp.JobRoleId.toString() === selectedRole);


// not need currently for this fun
const handleEmployeeSelection = (employeeId,field) => {
 

  setSelectedEmployees((prevSelected) => {
    let updatedSelection;
    if (!prevSelected.includes(employeeId)) {
      updatedSelection = [...prevSelected, employeeId];
    } else {
      updatedSelection = prevSelected.filter((id) => id !== employeeId);
    }
    field.onChange(updatedSelection); 
    return updatedSelection;
  });
};


const removeEmployee = (employeeId) => {
  setSelectedEmployees((prevSelected) => {
    const updatedSelection = prevSelected.filter((id) => id !== employeeId);
    setValue("selectedEmployees", updatedSelection); 
    return updatedSelection;
  });
};


const onSubmit = async(data) => {
  const formattedData = {
    taskTeam: data.selectedEmployees, 
    plannedTask: parseInt( plannedTask, 10 ),
    description: data.description,
    assignmentDate: new Date().toISOString(),
    workItemId:assignData?.workItem?.workItem.id
  };
  try
  {
    let response = await TasksRepository.assignTask( formattedData );
    console.log( response )
    showToast( "Task Successfully Assigend", "success" )
    closeModal()
  } catch ( error )
  {
    showToast("something wrong","error")
    
  }

};
console.log(assignData?.workItem?.workItem)
useEffect(()=>{
  dispatch(changeMaster("Job Role"))
  return ()=> setSelectedRole("all")
},[dispatch])


  return (<>
 
    <div className="container my-1">
    <div className="mb-2">
    <div className="bs-stepper wizard-numbered d-flex justify-content-center align-items-center flex-wrap">
  {[
    assignData?.building?.name,
    assignData?.floor?.floorName,
    assignData?.workArea?.areaName,
    assignData?.workItem?.workItem?.activityMaster?.activityName
  ].map((item, index, array) => (
    <div key={index} className="col d-flex justify-content-center align-items-center">
      <div className="bs-stepper-header p-1 text-center">
        <span className="fs-5">{item}</span>
        
        {/* Arrow between items */}
        {index < array.length - 1 && (
          <div className="line">
            <i className="icon-base bx bx-chevron-right scaleX-n1-rtl"></i>
          </div>
        )}
      </div>
    </div>
  ))}
   </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="row mb-1">
          <div className="col-sm-4">
            <div className="form-text text-start">Select Role</div>
            <div className="input-group input-group-merge">
              <select
                className="form-select form-select-sm"
                id="Role"
                value={selectedRole}
                onChange={handleRoleChange}
                aria-label=""
              >
                {loading && data ? "Loading..." : (
                  <>
                  <option value="all">All</option>
                { jobRoleData?.map((item) => (
                  <option key={item.id} value={item.id}>
                    {item.name}
                  </option>
                ))}
                  </>
                )}
              </select>
            </div>
          </div>
        </div>
        <div class="divider text-start">
       <div class="divider-text">Employee</div>
       </div>
        {selectedRole !== "" && (
          <div className="row mb-2">
            <div className="col-sm-12">
              <div className="row">
                {filteredEmployees.map((emp) => {
                  const jobRole = jobRoleData?.find((role) => role.id === emp.jobRoleId);

                  return (
                    <div key={emp.id} className="col-6 col-sm-4 col-md-4 col-lg-3 mb-1">
                      <div className="form-check text-start p-0">
                        <div className="li-wrapper d-flex justify-content-start align-items-start">
                          <Controller
                            name="selectedEmployees"
                            control={control}
                            render={({ field }) => (
                              <input
                                {...field}
                                className="form-check-input mx-2"
                                type="checkbox"
                                id={`employee-${emp.id}`}
                                value={emp.id}
                                checked={field.value.includes(emp.id)}  // Ensure the checkbox reflects the current form state
                                onChange={() => {
                                  handleEmployeeSelection( emp.id, field )
                                }}
                              />
                            )}
                          />
                          <div className="list-content">
                            <h6 className="mb-0">{emp.firstName
                            } {emp.lastName}</h6>
                            <small className="text-muted">
                              {loading && (<p className="skeleton para" style={{height:"7px"}}></p>)}
                              {data && !loading && (jobRole ? jobRole.name : 'Unknown Role')}
                            </small>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
        {selectedEmployees.length > 0 && (
          <div className="mt-1">
            <div className="text-start px-2">
              {selectedEmployees.map((empId) => {
                const emp = employees.find((emp) => emp.id === empId);
                return (
                  <span key={empId} className="badge bg-label-primary d-inline-flex align-items-center gap-2 me-1 p-2 mb-2">
                    {emp.firstName
                    } {emp.lastName}
                    <p
                      type="button"
                      className=" btn-close-white p-0 m-0"
                      aria-label="Close"
                      onClick={() => {
                        removeEmployee(empId);
                        setValue("selectedEmployees", selectedEmployees.filter(id => id !== empId));
                      }}
                    ><i className="icon-base bx bx-x icon-md "></i></p>
                  </span>
                );
              })}
            </div>
          </div>
        )}
 {errors.selectedEmployees && (
          <div className="danger-text mt-1">
            <p>{errors.selectedEmployees[0]}</p>
          </div>
        )}
      <div class="col-md text-start mx-0 px-0">
         <div class="form-check form-check-inline mt-4 px-1">
           <label className="form-text fs-6" for="inlineCheckbox1">Pending Work</label>
           <label className="form-check-label ms-2" for="inlineCheckbox1">{ assignData?.workItem?.workItem?.plannedWork - assignData?.workItem?.workItem?.completedWork}</label>
         </div>
         <div className="form-check form-check-inline col-sm-2 col">
              <label for="defaultFormControlInput" className="form-label">Target</label>
              <Controller name="pannedTask" control={control} render={( {field} ) => (
                   <input type="text" className="form-control form-control-sm " {...field}  />   
              )} />
              {errors.pannedTask && (
          <div className="danger-text">
            <p>{errors.pannedTask.message}</p>
          </div>
        )}
         </div>
      </div>       
       
         <label for="exampleFormControlTextarea1" className="form-label">Description</label>
            <Controller
              name="description"
              control={control}
              render={({ field }) => (
                <textarea
                  {...field}
                  className="form-control"
                  id="exampleFormControlTextarea1"
                  rows="3"
                />
              )}
          />
          {errors.description && ( <div>{errors.description.message }</div>)}
      
       <div className="col-12 d-flex justify-content-center align-items-center gap-sm-6 gap-8 text-center mt-1">
        <button type="submit" className="btn btn-sm btn-primary ">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>
      </div>
      </div>
         
      

</>
  );
};
export default AssignRoleModel