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 { zodResolver } from "@hookform/resolvers/zod";
import { getCachedData } from "../../slices/apiDataManager";
import { useProjects } from "../../hooks/useProjects";
import { useEmployeesAllOrByProjectId } from "../../hooks/useEmployees";
import { TasksRepository } from "../../repositories/ProjectRepository";
import showToast from "../../services/toastService";

const AssignRoleModel = ({ assignData, onClose }) => {
  const maxPlanned =
    assignData?.workItem?.workItem?.plannedWork -
    assignData?.workItem?.workItem?.completedWork;

  const schema = z.object({
    selectedEmployees: z
      .array(z.string())
      .min(1, { message: "At least one employee must be selected" }),
    description: z.string().min(1, { message: "Description is required" }),
    plannedTask: z.preprocess(
      (val) => parseInt(val, 10),
      z
        .number({
          required_error: "Planned task is required",
          invalid_type_error: "Planned task must be a number",
        })
        .int()
        .positive({ message: "Planned task must be a positive number" })
        .max(maxPlanned, {
          message: `Planned task cannot exceed ${maxPlanned}`,
        })
    ),
  });
  const [plannedTask, setPlannedTask] = useState();
  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 },
    reset,
  } = useForm({
    defaultValues: {
      selectedEmployees: [],
      description: "",
      plannedTask: "",
    },
    resolver: zodResolver(schema),
  });

  const handleRoleChange = (event) => {
    reset();
    setSelectedEmployees([]);
    setSelectedRole(event.target.value);
  };

  const filteredEmployees =
    selectedRole === "all"
      ? employees
      : employees.filter((emp) => String(emp.jobRoleId || "") === selectedRole);

  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); // Ensure form state is updated
      return updatedSelection;
    });
  };

  const onSubmit = async (data) => {
    const formattedData = {
      taskTeam: data.selectedEmployees,
      plannedTask: data.plannedTask,
      description: data.description,
      assignmentDate: new Date().toISOString(),
      workItemId: assignData?.workItem?.workItem.id,
    };
    try {
      let response = await TasksRepository.assignTask(formattedData);
      showToast("Task Successfully Assigend", "success");
      setSelectedEmployees([]);
      reset();
      onClose();
    } catch (error) {
      showToast("something wrong", "error");
    }
  };
  useEffect(() => {
    dispatch(changeMaster("Job Role"));
    return () => setSelectedRole("all");
  }, [dispatch]);

  const closedModel = () => {
    reset();
    onClose();
  };
  return (
    <div
      className="modal-dialog modal-lg modal-simple mx-sm-auto mx-1 edit-project-modal"
      role="document"
    >
      <div className="modal-content">
        <div className="modal-body p-sm-4 p-0">
          <button
            type="button"
            className="btn-close"
            onClick={onClose}
            aria-label="Close"
          ></button>
          <div className="container my-1">
            <div className="mb-">
              <p className="fs-sm-5 fs-6 text-dark text-start d-flex align-items-center flex-wrap">
                {[
                  assignData?.building?.name,
                  assignData?.floor?.floorName,
                  assignData?.workArea?.areaName,
                  assignData?.workItem?.workItem?.activityMaster?.activityName,
                ]
                  .filter(Boolean)
                  .map((item, index, array) => (
                    <span key={index} className="d-flex align-items-center">
                      {item}
                      {index < array.length - 1 && (
                        <i className="bx bx-chevron-right mx-2"></i>
                      )}
                    </span>
                  ))}
              </p>

              <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 className="divider text-start">
                  <div className="divider-text">Employee</div>
                </div>
                {filteredEmployees?.length === 0 && employees && (
                  <div>No employees found</div>
                )}

                <div className="row">
                  <div className="col-12 col-md-8 h-sm-25 overflow-auto">
                    {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-6 col-md-4 col-lg-4 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
                                            )}
                                            onChange={() => {
                                              handleEmployeeSelection(
                                                emp.id,
                                                field
                                              );
                                            }}
                                          />
                                        )}
                                      />
                                      <div className="list-content">
                                        <p
                                          className=" mb-0"
                                          style={{
                                            fontSize: "12px",
                                            fontWeight: "bolder",
                                          }}
                                        >
                                          {emp.firstName} {emp.lastName}
                                        </p>
                                        <small
                                          className="lead"
                                          style={{ fontSize: "10px" }}
                                        >
                                          {loading && (
                                            <p
                                              className="skeleton para"
                                              style={{ height: "7px" }}
                                            ></p>
                                          )}
                                          {data &&
                                            !loading &&
                                            (jobRole
                                              ? jobRole.name
                                              : "Unknown Role")}
                                        </small>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                  <div
                    className="col-12 col-md-4 h-25 overflow-auto"
                    style={{ maxHeight: "200px" }}
                  >
                    {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-1 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>
                    )}
                  </div>
                </div>

                <div className="col-md text-start mx-0 px-0">
                  <div className="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="plannedTask"
                      control={control}
                      render={({ field }) => (
                        <input
                          type="text"
                          className="form-control form-control-xs"
                          {...field}
                          id="defaultFormControlInput"
                          aria-describedby="defaultFormControlHelp"
                        />
                      )}
                    />
                  </div>
                  {errors.plannedTask && (
                    <div className="danger-text mt-1">
                      {errors.plannedTask.message}
                    </div>
                  )}
                </div>
                {errors.selectedEmployees && (
                  <div className="danger-text mt-1">
                    <p>{errors.selectedEmployees.message}</p>
                  </div>
                )}

                <label for="exampleFormControlTextarea1" className="form-label">
                  Description
                </label>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <textarea
                      {...field}
                      className="form-control"
                      id="exampleFormControlTextarea1"
                      rows="2"
                    />
                  )}
                />
                {errors.description && (
                  <div className="danger-text">
                    {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={closedModel}
                  >
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
export default AssignRoleModel;
