import { zodResolver } from "@hookform/resolvers/zod";
import React, { useMemo, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import {
  defaultOrganizationValues,
  organizationSchema,
} from "./OrganizationSchema";
import Modal from "../common/Modal";
import {
  useCreateOrganization,
  useOrganizationBySPRID,
  useOrganizationModal,
  useOrganizationsList,
} from "../../hooks/useOrganization";
import Label from "../common/Label";
import SelectMultiple from "../common/SelectMultiple";
import { useServices } from "../../hooks/masterHook/useMaster";
import AssignOrg from "./AssignOrg";
import ManagOrg from "./ManagOrg";
import OrgPickerFromSPId from "./OrgPickerFromSPId";
import OrgPickerfromTenant from "./OrgPickerfromTenant";

const OrganizationModal = () => {
  const { isOpen, orgData, startStep, onOpen, onClose, onToggle } =
    useOrganizationModal();
  const { data: masterService, isLoading } = useServices();
  const [searchText, setSearchText] = useState();
  const [SPRID, setSPRID] = useState("");

  const [Organization, setOrganization] = useState({});

  const method = useForm({
    resolver: zodResolver(organizationSchema),
    defaultValues: defaultOrganizationValues,
  });

  const {
    handleSubmit,
    register,
    reset,
    formState: { errors },
  } = method;

  const { mutate: CreateOrganization, isPending } = useCreateOrganization(
    () => {
      reset(defaultOrganizationValues);
      onClose();
    }
  );

  const onSubmit = (OrgPayload) => {
    CreateOrganization(OrgPayload);
  };

  const RenderTitle = useMemo(() => {
    if (orgData) {
      return "Assign Organization";
    }

    if (startStep === 1) {
      return orgData && orgData !== null
        ? "Add Organization"
        : "Choose Organization1";
    }

    if (startStep === 2) {
      return "Add Organization";
    }

    if (startStep === 3) {
      return "Assign Organization";
    }

    return "Manage Organization";
  }, [startStep, orgData]);

  const contentBody = (
    <div>
      {/* ---------- STEP 1: Service Provider- Form Own Tenant list ---------- */}
      {startStep === 1 && <OrgPickerfromTenant title="Find Organization" />}

      {startStep === 2 && (
        <OrgPickerFromSPId
          title="Find Organization"
          placeholder="Enter Service Provider Id"
          projectOrganizations={orgData}
        />
      )}

      {/* ---------- STEP 2: Existing Organization Details ---------- */}
      {startStep === 3 && Organization && (
        <AssignOrg Organization={Organization} />
      )}

      {/* ---------- STEP 3: Add New Organization ---------- */}
      {startStep === 4 && <ManagOrg />}
    </div>
  );

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={RenderTitle}
      body={contentBody}
    />
  );
};

export default OrganizationModal;
