import React, { useState, useEffect } from "react";
import ContactInfro from "./ContactInfro";
import SubScription from "./SubScription";
import OrganizationInfo from "./OrganizationInfo";
import Congratulation from "./Congratulation";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  getStepFields,
  getSubscriptionSchema,
  newTenantSchema,
  subscriptionDefaultValues,
  tenantDefaultValues,
} from "./TenantSchema";
import { useSelector } from "react-redux";

const TenantForm = () => {

  const HasSelectedCurrentTenant = useSelector(
    (store) => store.globalVariables.currentTenant
  );
  const [activeTab, setActiveTab] = useState(0);
  const [completedTabs, setCompletedTabs] = useState([]);

  const PlanTextLabel =
    HasSelectedCurrentTenant?.operationMode === 1
      ? "Upgrade Plan"
      : "Select Plan";

  // Jump to subscription if tenant already exists
  useEffect(() => {
    if (HasSelectedCurrentTenant) {
      if (HasSelectedCurrentTenant.operationMode === 1) {
        // Skip to subscription step
        setActiveTab(2); // index for "SubScription"
        setCompletedTabs([0, 1]); // mark previous steps as completed
      } else if (HasSelectedCurrentTenant.operationMode === 0) {
        setActiveTab(0); // start from beginning
      }
    }
  }, [HasSelectedCurrentTenant]);

  const tenantForm = useForm({
    resolver: zodResolver(newTenantSchema),
    defaultValues: tenantDefaultValues,
  });

  const subscriptionForm = useForm({
    resolver: zodResolver(getSubscriptionSchema(HasSelectedCurrentTenant?.data?.activeEmployees)),
    defaultValues: subscriptionDefaultValues,
  });

  const getCurrentTrigger = () =>
    activeTab === 2 ? subscriptionForm.trigger : tenantForm.trigger;

  const handleNext = async () => {
  const currentStepFields = getStepFields(activeTab);
  const trigger = getCurrentTrigger();
  const valid = await trigger(currentStepFields);

  if (valid) {
    setCompletedTabs((prev) => [...new Set([...prev, activeTab])]);

    setActiveTab((prev) => {
      let nextStep = Math.min(prev + 1, newTenantConfig.length - 1);

      //  Check tenant operationMode to decide navigation
      if (
        HasSelectedCurrentTenant &&
        HasSelectedCurrentTenant.operationMode === 1 &&
        nextStep === 2
      ) {
        // If tenant already has subscription, show upgrade
        nextStep = 2;
      } else if (
        HasSelectedCurrentTenant &&
        [0, 2].includes(HasSelectedCurrentTenant.operationMode) &&
        nextStep === 2
      ) {
        // If tenant just created (0) OR exists without subscription (2)
        // → stay on subscription tab
        nextStep = 2;
      }

      return nextStep;
    });
  }
};


  const handlePrev = () => {
    setActiveTab((prev) => Math.max(prev - 1, 0));
  };

  const onSubmitTenant = (data) => {
    console.log("Tenant Data:", data);
  };

  const onSubmitSubScription = (data) => {
    console.log("Subscription Data:", data);
  };

  const newTenantConfig = [
    {
      name: "Contact Info",
      icon: "bx bx-user bx-md",
      subtitle: "Provide Contact Details",
      component: <ContactInfro onNext={handleNext} />,
    },
    {
      name: "Organization",
      icon: "bx bx-buildings bx-md",
      subtitle: "Organization Details",
      component: (
        <OrganizationInfo
          onNext={handleNext}
          onPrev={handlePrev}
          onSubmitTenant={onSubmitTenant}
        />
      ),
    },
    {
      name: "SubScription",
      icon: "bx bx-star bx-md",
      subtitle: PlanTextLabel,
      component: (
        <SubScription
          onSubmitSubScription={onSubmitSubScription}
          onNext={handleNext}
        />
      ),
    },
    {
      name: "Congratulation",
      icon: "bx bx-check-circle bx-md",
      subtitle: "Completed",
      component: <Congratulation />,
    },
  ];

  const isSubscriptionTab = activeTab === 2;

  return (
    <div
      id="wizard-property-listing"
      className="bs-stepper horizontically mt-2"
    >
      <div className="bs-stepper-header border-end text-start ">
        {newTenantConfig
          .filter((step) => step.name.toLowerCase() !== "congratulation")
          .map((step, index) => {
            const isActive = activeTab === index;
            const isCompleted = completedTabs.includes(index);

            return (
              <React.Fragment key={step.name}>
                <div
                  className={`step ${isActive ? "active" : ""} ${
                    isCompleted ? "crossed" : ""
                  }`}
                  data-target={`#step-${index}`}
                >
                  <button
                    type="button"
                    className={`step-trigger ${isActive ? "active" : ""}`}
                    // onClick={() => setActiveTab(index)} // optional
                  >
                    <span className="bs-stepper-circle">
                      {isCompleted ? (
                        <i className="bx bx-check"></i>
                      ) : (
                        <i className={step.icon}></i>
                      )}
                    </span>
                    <span className="bs-stepper-label">
                      <span className="bs-stepper-title">{step.name}</span>
                      <span className="bs-stepper-subtitle">
                        {step.subtitle}
                      </span>
                    </span>
                  </button>
                </div>
                {index < newTenantConfig.length - 1 && (
                  <div className="line text-primary"></div>
                )}
              </React.Fragment>
            );
          })}
      </div>

      <div className="bs-stepper-content py-2">
        {isSubscriptionTab ? (
          <FormProvider {...subscriptionForm}>
            <form
              onSubmit={subscriptionForm.handleSubmit(onSubmitSubScription)}
            >
              {newTenantConfig[activeTab].component}
            </form>
          </FormProvider>
        ) : (
          <FormProvider {...tenantForm}>
            <form onSubmit={tenantForm.handleSubmit(onSubmitTenant)}>
              {newTenantConfig[activeTab].component}
            </form>
          </FormProvider>
        )}
      </div>
    </div>
  );
};

export default TenantForm;
