import React, { useEffect } from "react";
import {
  useProjectLevelEmployeePermission,
  useProjectLevelModules,
  useUpdateProjectLevelEmployeePermission,
} from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useEmployeesByProject } from "../../hooks/useEmployees";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import showToast from "../../services/toastService";

export const ProjectPermissionSchema = z.object({
  employeeId: z.string().min(1, "Employee is required"),
  selectedPermissions: z.array(z.string()).optional(),
});

const ProjectPermission = () => {
  const selectedProject = useSelectedProject();

  const { data: ProjectModules = [] } = useProjectLevelModules();
  const { employees = [], loading } = useEmployeesByProject(selectedProject);

  const {
    register,
    watch,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(ProjectPermissionSchema),
    defaultValues: {
      employeeId: "",
      selectedPermissions: [],
    },
  });

  const selectedEmployee = watch("employeeId");

  const { data: selectedEmpPermissions } = useProjectLevelEmployeePermission(
    selectedEmployee || "",
    selectedProject
  );

useEffect(() => {
  if (!selectedEmployee) return;

  const enabledPerms =
    selectedEmpPermissions?.permissions
      ?.filter((perm) => perm.isEnabled)
      ?.map((perm) => perm.id) || [];

  reset((prev) => ({
    ...prev,
    selectedPermissions: enabledPerms,
  }));
}, [selectedEmpPermissions, reset, selectedEmployee]);


  const { mutate: updatePermission, isPending } =
    useUpdateProjectLevelEmployeePermission();

 const onSubmit = (formData) => {
  if (!formData.employeeId) {
    showToast("Please select an employee", "warn");
    return;
  }

  const existingPermissions = selectedEmpPermissions?.permissions || [];
  const existingEnabledIds = existingPermissions
    .filter((p) => p.isEnabled)
    .map((p) => p.id);

  const newSelectedIds = formData.selectedPermissions || [];

  const removed = existingEnabledIds
    .filter((id) => !newSelectedIds.includes(id))
    .map((id) => ({ id, isEnabled: false }));

  const added = newSelectedIds
    .filter((id) => !existingEnabledIds.includes(id))
    .map((id) => ({ id, isEnabled: true }));

  const payloadPermissions = [...removed, ...added];

  if (payloadPermissions.length === 0) {
    showToast("No changes detected", "info");
    return;
  }

  const payload = {
    employeeId: formData.employeeId,
    projectId: selectedProject,
    permission: payloadPermissions,
  };

  updatePermission(payload);
};


  return (
    <div className="row px-2 py-1">
      <form className="row" onSubmit={handleSubmit(onSubmit)}>
        {/* Employee Dropdown */}
        <div className="d-flex align-items-end gap-2">
          <div className="text-start">
            <label className="form-label">Select Employee</label>
            <select
              className="form-select form-select-sm"
              {...register("employeeId")}
              disabled={isPending}
            >
              {loading ? (
                <option value="">Loading...</option>
              ) : (
                <>
                  <option value="">-- Select Employee --</option>
                  {[...employees]?.sort((a, b) =>
                      `${a.firstName} ${a.firstName}`?.localeCompare(
                        `${b.firstName} ${b.lastName}`
                      )
                    )
                    ?.map((emp) => (
                      <option key={emp.id} value={emp.id}>
                        {emp.firstName} {emp.lastName}
                      </option>
                    ))}
                </>
              )}
            </select>

            {errors.employeeId && (
              <div className="text-danger small">
                {errors.employeeId.message}
              </div>
            )}
          </div>
          <button
            className="btn btn-sm btn-primary"
            disabled={isPending || loading}
          >
            {isPending ? "Please Wait..." : "Update Permission"}
          </button>
        </div>

        {/* Permissions */}
        {ProjectModules.map((feature) => (
          <div key={feature.id} className="row my-2 px-3 ">
            <div className="col-12 text-start fw-semibold mb-2">
              {feature.name}
            </div>
            <div className="col-12">
              <div className="row">
                {feature.featurePermissions?.map((perm) => (
                  <div className="col-12 col-sm-6 col-md-4 mb-2" key={perm.id}>
                    <label
                      className="form-check-label d-flex align-items-center"
                      htmlFor={perm.id}
                    >
                      <input
                        type="checkbox"
                        className="form-check-input me-2"
                        id={perm.id}
                        value={perm.id}
                        {...register("selectedPermissions")}
                      />
                      {perm.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>
            <hr className="my-2" />
          </div>
        ))}
      </form>
    </div>
  );
};

export default ProjectPermission;
