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: