import React, { useMemo, useState } from "react";
import { useProjectAssignedServices } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
import {
  useOrganizationType,
  useServices,
} from "../../hooks/masterHook/useMaster";
import Label from "../common/Label";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { assignedOrgToProject } from "./OrganizationSchema";
import {
  useAssignOrgToProject,
  useOrganizationModal,
} from "../../hooks/useOrganization";

const AssignOrg = ({ setStep }) => {
  const { isOpen, orgData, startStep, onOpen, flowType, prevStep, onClose } =
    useOrganizationModal();
  const selectedProject = useSelectedProject();
  const { data: masterService, isLoading: isMasterserviceLoading } =
    useServices();
  const { data: projectServices, isLoading } =
    useProjectAssignedServices(selectedProject);
  const { data: orgType, isLoading: orgLoading } = useOrganizationType();

  const { mutate: AssignToProject, isPending } = useAssignOrgToProject(() =>
    onClose()
  );

  const mergedServices = useMemo(() => {
    if (!masterService || !projectServices) return [];

    const combined = [...masterService?.data, ...projectServices];

    const unique = combined.filter(
      (item, index, self) => index === self.findIndex((s) => s.id === item.id)
    );

    return unique;
  }, [masterService, projectServices]);

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

  const onSubmit = (formData) => {
    const payload = {
      ...formData,
      projectId: selectedProject,
      organizationId: orgData.id,
      parentOrganizationId: null,
    };
    AssignToProject(payload);
  };
  const handleEdit = () => {
    onOpen({ startStep: 4, orgData: orgData });
  };
  const handleBack = () => {
    if (prevStep == 1 && flowType == "assign") {
      onOpen({ startStep: prevStep });
    } else if (prevStep == 1 && flowType == "assign") {
      onOpen({ startStep: 1 });
    } else {
      onOpen({ startStep: 2 });
    }
  };
  if (isMasterserviceLoading || isLoading)
    return <div className="text-center">Loading....</div>;
  return (
    <div className="row text-black mb-3">
      <div className="col-12 mb-3">
        <div className="d-flex justify-content-between align-items-center text-start mb-2">
          <div className="fw-semibold text-wrap">{orgData.name}</div>
          <div className="text-end">
            <button
              type="button"
              onClick={handleEdit}
              className="btn btn-link p-0"
            >
              <i className="bx bx-edit text-secondary"></i>
            </button>
          </div>
        </div>
      </div>

      <div className="col-md-6 mb-3">
        <div className="d-flex">
          <label
            className="form-label me-2 mb-0 fw-semibold text-start"
            style={{ minWidth: "130px" }}
          >
            Constact Person :
          </label>
          <div className="text-muted">{orgData.name}</div>
        </div>
      </div>
      <div className="col-md-6 mb-3">
        <div className="d-flex">
          <label
            className="form-label me-2 mb-0 fw-semibold text-start"
            style={{ minWidth: "130px" }}
          >
            Contact Number :
          </label>
          <div className="text-muted">{orgData.contactNumber}</div>
        </div>
      </div>
      <div className="col-md-6 mb-3">
        <div className="d-flex">
          <label
            className="form-label me-2 mb-0 fw-semibold text-start"
            style={{ minWidth: "130px" }}
          >
            Email Address :
          </label>
          <div className="text-muted">{orgData.email}</div>
        </div>
      </div>
      <div className="col-12 mb-3">
        <div className="d-flex">
          <label
            className="form-label me-2 mb-0 fw-semibold text-start text-wrap"
            style={{ maxWidth: "130px" }}
          >
            Service provider Id (SPRID) :
          </label>
          <div className="text-muted">{orgData.sprid}</div>
        </div>
      </div>

      <div className="col-12 mb-3">
        <div className="d-flex">
          <label
            className="form-label me-1 mb-0 fw-semibold text-start"
            style={{ minWidth: "130px" }}
          >
            Address :
          </label>
          <div className="text-muted text-start">{orgData.address}</div>
        </div>
      </div>

      <div className="text-black text-start">
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="mb-1 text-start">
            <Label htmlFor="organizationTypeId" required>
              Organization Type
            </Label>

            <div className="d-flex flex-wrap gap-3  mt-1">
              {orgType?.data.map((type) => (
                <div
                  key={type.id}
                  className="form-check d-flex align-items-center gap-2 p-0 m-0"
                >
                  <input
                    type="radio"
                    id={`organizationType-${type.id}`}
                    value={type.id}
                    {...register("organizationTypeId", {
                      required: "Please select an organization type",
                    })}
                    className="form-check-input m-0"
                  />
                  <label
                    className="form-check-label m-0"
                    htmlFor={`organizationType-${type.id}`}
                  >
                    {type.name}
                  </label>
                </div>
              ))}
            </div>

            {errors.organizationTypeId && (
              <span className="danger-text">
                {errors.organizationTypeId.message}
              </span>
            )}
          </div>

          <div className="mb-3">
            <Label htmlFor="serviceId" required>
              Select Services
            </Label>
            {mergedServices?.map((service) => (
              <div key={service.id} className="form-check">
                <input
                  type="checkbox"
                  value={service.id}
                  {...register("serviceIds")}
                  className="form-check-input"
                />
                <label className="form-check-label">{service.name}</label>
              </div>
            ))}
            {errors.serviceIds && (
              <div className="text-danger small">
                {errors.serviceIds.message}
              </div>
            )}
          </div>

          {/* Buttons */}
          <div className="d-flex justify-content-between mt-3">
            <button
              type="button"
              className="btn btn-xs btn-outline-secondary"
              onClick={handleBack}
              disabled={isPending}
            >
              <i className="bx bx-left-arrow-alt"></i> Back
            </button>
            <button
              type="submit"
              className="btn btn-sm btn-primary"
              disabled={isPending}
            >
              {isPending ? "Please wait..." : "Add"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AssignOrg;
