import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Label from "../common/Label";
import PmsEmployeeInputTag from "../common/PmsEmployeeInputTag";
import { useManageEmployeeHierarchy, useOrganizationHierarchy } from "../../hooks/useEmployees";
import { ManageReportingSchema, defaultManageReporting } from "./EmployeeSchema";

const ManageReporting = ({ onClosed, employee, employeeId }) => {
  const {
    handleSubmit,
    control,
    reset,
    formState: { errors },
    watch,
  } = useForm({
    resolver: zodResolver(ManageReportingSchema),
    defaultValues: defaultManageReporting,
  });

  const { data, isLoading } = useOrganizationHierarchy(employeeId);

  // mutation hook
  const { mutate: manageHierarchy, isPending } = useManageEmployeeHierarchy(
    employeeId,
    onClosed
  );

  const primaryValue = watch("primaryNotifyTo");
  const secondaryValue = watch("secondaryNotifyTo");

  // Prefill hierarchy data
  useEffect(() => {
    if (data && Array.isArray(data)) {
      const primary = data.find((r) => r.isPrimary);
      const secondary = data.filter((r) => !r.isPrimary);

      reset({
        primaryNotifyTo: primary ? [primary.reportTo.id] : [],
        secondaryNotifyTo: secondary.map((r) => r.reportTo.id),
      });
    }
  }, [data, reset]);

  const handleClose = () => {
    reset(defaultManageReporting);
    onClosed();
  };

  const onSubmit = (formData) => {
    // Build set of currently selected IDs
    const selectedIds = new Set([
      ...(formData.primaryNotifyTo || []),
      ...(formData.secondaryNotifyTo || []),
    ]);

    // Build payload including previous assignments, setting isActive true/false accordingly
    const payload = (data || []).map((item) => ({
      reportToId: item.reportTo.id,
      isPrimary: item.isPrimary,
      isActive: selectedIds.has(item.reportTo.id),
    }));

    // Add any new IDs that were not previously assigned
    if (formData.primaryNotifyTo?.length) {
      const primaryId = formData.primaryNotifyTo[0];
      if (!data?.some((d) => d.reportTo.id === primaryId)) {
        payload.push({
          reportToId: primaryId,
          isPrimary: true,
          isActive: true,
        });
      }
    }

    if (formData.secondaryNotifyTo?.length) {
      formData.secondaryNotifyTo.forEach((id) => {
        if (!data?.some((d) => d.reportTo.id === id)) {
          payload.push({
            reportToId: id,
            isPrimary: false,
            isActive: true,
          });
        }
      });
    }

    manageHierarchy(payload);
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)} className="p-sm-0 p-2">
        <h5 className="m-0 py-1 mb-3">
          Update Reporting Manager (
          {`${employee.firstName || ""} ${employee.middleName || ""} ${employee.lastName || ""}`.trim()}
          )
        </h5>

        {/* Primary */}
        <div className="mb-4 text-start">
          <Label className="form-label" required>
            Primary Reporting Manager
          </Label>
          <PmsEmployeeInputTag
            control={control}
            name="primaryNotifyTo"
            placeholder={primaryValue?.length > 0 ? "" : "Select primary report-to"}
            forAll={true}
            disabled={primaryValue?.length > 0}
          />
          {errors.primaryNotifyTo && (
            <div className="text-danger small mt-1">
              {errors.primaryNotifyTo.message}
            </div>
          )}
        </div>


        {/* Secondary */}
        <div className="mb-4 text-start">
          <Label className="form-label">
            Secondary Reporting Manager
          </Label>
          <PmsEmployeeInputTag
            control={control}
            name="secondaryNotifyTo"
            placeholder="Select secondary report-to(s)"
            forAll={true}
          />
        </div>


        <div className="d-flex justify-content-end gap-3 mt-3 mb-3">
          <button
            type="button"
            onClick={handleClose}
            className="btn btn-label-secondary btn-sm"
            disabled={isPending}
          >
            Cancel
          </button>

          <button
            type="submit"
            className="btn btn-primary btn-sm"
            disabled={isPending}
          >
            {isPending ? "Saving..." : "Submit"}
          </button>
        </div>
      </form>
    </div>
  );
};

export default ManageReporting;