/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { ErrorMessage, Field, Form, Formik, useFormikContext } from "formik"; import React, { useEffect, useState } from "react"; import { initiateRegistration, registerCustomer, resetPassword, } from "../../Api/CustomerApi"; import { api } from "../../Api/Api"; import * as Yup from "yup"; import Swal from "sweetalert2"; import HourGlassLoader from "../Loader/Loader"; import { getMasterList } from "../../Api/MastersApi"; import CustomSelect from "../TextField/CustomSelect"; import PhoneInput from "react-phone-number-input"; import "react-phone-number-input/style.css"; import { DefaultSetupValues } from "@/Constant/enums"; import PhoneInputField from "../TextField/PhoneInputField"; import DescriptionField from "../TextField/DescriptionField"; interface FormValues { first_name: string; last_name: string; email: string; phone: string; password: string; confirm_password: string; user_type: string; // Corporate-only fields user_type_id: string; nationality: string; city: string; road: string; block: string; building: string; address_line1: string; address_line2: string; organization_name: string; organization_reg_no: string; vat_number: string; first_name_ar: string; last_name_ar: string; description: string; } interface SignUpModalProps { isSubmitting: boolean; setModalType: (type: string) => void; token: string; resetToken?: string; handleInitialRegister: () => void; activeTabLogin: string; } const SignUpModal: React.FC = ({ isSubmitting, setModalType, token = "", resetToken = "", handleInitialRegister, activeTabLogin = "", }) => { const [isLoading, setIsLoading] = useState(false); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); // If you have specific tabs like "user" | "staff", type it as a union type TabType = "user" | "staff"; const [activeTab, setActiveTab] = useState("user"); useEffect(() => { setActiveTab(activeTabLogin === "staff" ? "staff" : "user"); }, [activeTabLogin]); const userTypes = [ { id: 4, name: "Standard Customer" }, { id: 5, name: "COD Customer" }, ]; //MASTER LIST const [nationalities, setNationalities] = useState([]); const [cities, setCities] = useState([]); const [roads, setRoads] = useState([]); const [blocks, setBlocks] = useState([]); const [buildings, setBuildings] = useState([]); const initialValues = { first_name: "", last_name: "", email: "", phone: "", password: "", confirm_password: "", user_type: "user", user_type_id: activeTab === "staff" ? userTypes[0]?.id?.toString() || "" : "", nationality: "", city: "", road: "", block: "", building: "", address_line1: "", address_line2: "", organization_name: "", organization_reg_no: "", vat_number: "", first_name_ar: "", last_name_ar: "", description: "", }; useEffect(() => { const fetchMasterLists = async () => { try { setIsLoading(true); const [nat, city, road, block, building] = await Promise.all([ getMasterList("nationality"), getMasterList("city"), getMasterList("road"), getMasterList("block"), getMasterList("building"), ]); setNationalities(nat.data || []); setCities(city.data?.data || []); setRoads(road.data || []); setBlocks(block.data || []); setBuildings(building.data || []); } catch (err) { console.error("Error loading masterlists", err); } finally { setIsLoading(false); } }; fetchMasterLists(); }, []); const validationSchema = Yup.object().shape({ organization_name: activeTab === "staff" ? Yup.string().required("Organization Name Required") : Yup.string(), description: activeTab === "staff" ? Yup.string() .required("Description is required") .min(10, "Description must be at least 10 characters") .max(500, "Description must not exceed 500 characters") : Yup.string(), first_name: Yup.string().when([], { is: () => !token && !resetToken, then: (schema) => schema.required("First name is required"), otherwise: (schema) => schema.notRequired(), }), last_name: Yup.string().when([], { is: () => !token && !resetToken, then: (schema) => schema.required("Last name is required"), otherwise: (schema) => schema.notRequired(), }), email: Yup.string() .email("Invalid email") .when([], { is: () => !token && !resetToken, then: (schema) => schema.required("Email is required"), otherwise: (schema) => schema.notRequired(), }), // phone: Yup.string() // .when([], { // is: () => !token && !resetToken, // then: (schema) => // schema // .required("Phone number is required") // .matches(/^\+?\d+$/, "Phone number must contain only digits") // .test( // "min-digits", // "Phone number is too short", // value => value ? value.replace(/^\+/, "").length >= 8 : false // ) // .test( // "max-digits", // "Phone number is too long", // value => value ? value.replace(/^\+/, "").length <= 15 : false // ), // otherwise: (schema) => schema.notRequired(), // }), phone: Yup.string() .when([], { is: () => !token && !resetToken, then: (schema) => schema .required("Phone number is required") .matches(/^\+?\d+$/, "Phone number must contain only digits") .test("valid-country-phone", "Invalid phone number", (value) => { if (!value) return false; const digits = value.replace(/^\+/, ""); // Bahrain (+973) if (value.startsWith("+973")) { return digits.length === 11; // +973 + 8 digits = 11 total } // India (+91) if (value.startsWith("+91")) { return digits.length === 12 && /^[6-9]\d{9}$/.test(digits.slice(2)); } // Generic fallback: 8–15 digits return digits.length >= 8 && digits.length <= 15; }), otherwise: (schema) => schema.notRequired(), }), password: Yup.string() .min(6, "Password must be at least 6 characters") .when([], { is: () => !!token || !!resetToken, then: (schema) => schema.required("Password is required"), otherwise: (schema) => schema.notRequired(), }), confirm_password: Yup.string() .oneOf([Yup.ref("password"), undefined], "Passwords must match") .when([], { is: () => !!token || !!resetToken, then: (schema) => schema.required("Confirm password is required"), otherwise: (schema) => schema.notRequired(), }), user_type: Yup.string().oneOf(["user", "corporate"]).required(), }); const [errorMessage] = useState(""); const handleRegister = async (values: FormValues) => { try { setIsLoading(true); let response; if (resetToken) { response = await resetPassword({ password: values?.password, reset_token: resetToken, }); } else if (token) { response = await registerCustomer({ password: values?.password, token: token, }); } else { response = await initiateRegistration({ ...values, user_type: 3 }); } if (response?.status) { // Show success popup Swal.fire({ icon: "success", title: resetToken ? "Password Reset Successful!" : activeTab === "staff" ? "Request Send Successfully!" : "Registration Successful", text: resetToken ? "Your password has been reset successfully! Please login with your new password." : token ? "Your password has been set successfully! Please login." : activeTab === "staff" ? "Our representative will contact you soon." : "Congratulations! Your account has been successfully created. Please check your email and set a password.", confirmButtonText: "OK", customClass: { confirmButton: "delybell-primary px-4", cancelButton: "delybell-dark", }, }).then(() => { // Redirect to login modal setModalType("login"); handleInitialRegister(); }); } else { Swal.fire({ icon: "error", title: resetToken ? "Password Reset Failed" : "Registration Failed", text: response?.message || "Something went wrong. Please try again.", customClass: { confirmButton: "delybell-primary px-4", cancelButton: "delybell-dark", }, }); } } catch (error: any) { console.error("Operation failed:", error); Swal.fire({ icon: "error", title: resetToken ? "Password Reset Failed" : "Registration Failed", text: error?.message || "Something went wrong. Please try again.", customClass: { confirmButton: "delybell-primary px-4", cancelButton: "delybell-dark", }, }); } finally { setIsLoading(false); } }; return ( <> {isLoading && }
{({ resetForm }) => (
{!token && !resetToken && ( )} {activeTab === "staff" && !token && !resetToken ? ( <>

{`Let's start`}

Corporate Enquiry

Enter your details below to send a new corporate enquiry.

) : !token && !resetToken ? ( <>

{`Let's start`}

Sign Up

Enter your details below to create a new account.

) : null} {errorMessage && (
{errorMessage}
)} {token || resetToken ? ( <>

{`Let's start`}

{resetToken ? "Reset Password" : "Set Password"}

{resetToken ? "Please enter your new password below to reset your account password." : "Enter your password below to complete registration."}

{/* Password */}
setShowPassword(!showPassword)} />
{/* Confirm Password */}
setShowConfirmPassword(!showConfirmPassword) } />
) : ( <> {activeTab === "user" ? ( <> {/* First Name */}
{/* Last Name */}
{/* Email */}
{/* Phone */} ) : ( <>
{/* Hidden User Type with default value */} {/* Organization Name */}
{/* First Name */}
{/* Last Name */}
{/* Email */}
{/* Phone */} {/* Description */}
)} {/* Hidden user_type */} )} {/* Submit Button */} )}
); }; export default SignUpModal;