/* 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<SignUpModalProps> = ({
  isSubmitting,
  setModalType,
  token = "",
  resetToken = "",
  handleInitialRegister,
  activeTabLogin = "",
}) => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [showConfirmPassword, setShowConfirmPassword] =
    useState<boolean>(false);

  // If you have specific tabs like "user" | "staff", type it as a union
  type TabType = "user" | "staff";

  const [activeTab, setActiveTab] = useState<TabType>("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<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const [roads, setRoads] = useState<any[]>([]);
  const [blocks, setBlocks] = useState<any[]>([]);
  const [buildings, setBuildings] = useState<any[]>([]);

  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 (
    <>
      <style>
        {`
          .input-style {
            position: relative;
          }

          .password-eye {
            position: absolute;
            top: 50%;
            right: 10px; /* Adjust this value to move it further/closer to the edge */
            transform: translateY(-50%); /* Vertically centers the icon */
            cursor: pointer;
            font-size: 18px; /* Adjust the icon size as needed */
          }
            .page-content.header-clear-medium { padding-top: 0!important; }
            .page-content.header-clear-medium .card-style { margin-bottom: 0!important; }
            .input-style .react-select__control, .input-style .css-13cymwt-control {
              border-top: 0;
              border-right: 0;
              border-left: 0;
              border-radius: 0;
              margin-left: 15px;
          }
          .input-style.mb-0 {
            margin-bottom: 0!important;
          }
          .PhoneInput {
            height: 50px;
            display: flex;
            align-items: center;
            border-radius: 0px;
            border-top: 0px;
            border-right: 0px;
            border-left: 0px;
            padding-left: 0;
          }
          .PhoneInputInput {
            flex: 1;
            height: 50px;
            border: none;
            outline: none;
            padding-left: 0 !important;
          }
          .PhoneInputCountry {
            margin-right: 10px;
          }
          .PhoneInputCountrySelect {
            margin-right: 10px;
          }
          .PhoneInputCountryIcon {
            width: 24px;
            height: 24px;
            box-shadow: none;
            border: 0;
            background-color: #fff;
          }
          .input-style.has-icon.has-borders .phone-input-country input.PhoneInputInput {
            padding-left: 0 !important;
          }

        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div className="content" id="tab-group-2">
        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={handleRegister}
          validationContext={{ activeTab }} // This is the fix
          enableReinitialize // This will reinitialize the form when the activeTab changes
        >
          {({ resetForm }) => (
            <Form>
              {!token && !resetToken && (
                <div className="tab-controls tabs-small tabs-rounded mb-4">
                  <a
                    onClick={() => {
                      setActiveTab("user");
                      resetForm(); // Clears errors, touched, and sets values to initial
                    }}
                    className={`tab-btn rounded-0 font-600  ${
                      activeTab === "user" ? "active" : ""
                    }`}
                  >
                    User Registration
                  </a>
                  <a
                    onClick={() => {
                      setActiveTab("staff");
                      resetForm();
                    }}
                    className={`tab-btn rounded-0 font-600  ${
                      activeTab === "staff" ? "active" : ""
                    }`}
                  >
                    Corporate <span className="d-xs-none">Enquiry</span>
                    <span className="d-lg-none">Enquiry</span>
                  </a>
                </div>
              )}
              {activeTab === "staff" && !token && !resetToken ? (
                <>
                  <p className="font-600 color-highlight mb-n1">{`Let's start`}</p>
                  <h1 className="font-30">Corporate Enquiry</h1>
                  <p>
                    Enter your details below to send a new corporate enquiry.
                  </p>
                </>
              ) : !token && !resetToken ? (
                <>
                  <p className="font-600 color-highlight mb-n1">{`Let's start`}</p>
                  <h1 className="font-30">Sign Up</h1>
                  <p>Enter your details below to create a new account.</p>
                </>
              ) : null}

              {errorMessage && (
                <div className="alert alert-danger">{errorMessage}</div>
              )}
              {token || resetToken ? (
                <>
                  <p className="font-600 color-highlight mb-n1">{`Let's start`}</p>
                  <h1 className="font-30">
                    {resetToken ? "Reset Password" : "Set Password"}
                  </h1>
                  <p>
                    {resetToken
                      ? "Please enter your new password below to reset your account password."
                      : "Enter your password below to complete registration."}
                  </p>

                  {/* Password */}
                  <div className="input-outer-box mb-3">
                    <div className="input-style no-borders has-icon validate-field mb-0">
                      <i className="fa fa-lock" />
                      <Field
                        type={showPassword ? "text" : "password"}
                        name="password"
                        className="form-control"
                        placeholder="Password"
                      />
                      <label className="color-highlight">Password</label>

                      <i
                        className={`fa ${
                          showPassword ? "fa-eye" : "fa-eye-slash"
                        } password-eye`}
                        onClick={() => setShowPassword(!showPassword)}
                      />
                    </div>
                    <ErrorMessage
                      name="password"
                      component="div"
                      className="error-message"
                    />
                  </div>

                  {/* Confirm Password */}
                  <div className="input-outer-box mb-3">
                    <div className="input-style no-borders has-icon validate-field mb-0">
                      <i className="fa fa-lock" />
                      <Field
                        type={showConfirmPassword ? "text" : "password"}
                        name="confirm_password"
                        className="form-control"
                        placeholder="Confirm Password"
                      />
                      <label className="color-highlight">
                        Confirm Password
                      </label>
                      <i
                        className={`fa ${
                          showConfirmPassword ? "fa-eye" : "fa-eye-slash"
                        } password-eye`}
                        onClick={() =>
                          setShowConfirmPassword(!showConfirmPassword)
                        }
                      />
                    </div>
                    <ErrorMessage
                      name="confirm_password"
                      component="div"
                      className="error-message"
                    />
                  </div>
                </>
              ) : (
                <>
                  {activeTab === "user" ? (
                    <>
                      {/* First Name */}
                      <div className="input-outer-box mb-3">
                        <div className="input-style no-borders has-icon validate-field mb-0">
                          <i className="fa fa-user" />
                          <Field
                            type="text"
                            name="first_name"
                            className="form-control"
                            placeholder="First Name"
                          />
                          <label className="color-highlight">First Name</label>
                        </div>
                        <ErrorMessage
                          name="first_name"
                          component="div"
                          className="error-message"
                        />
                      </div>

                      {/* Last Name */}
                      <div className="input-outer-box mb-3">
                        <div className="input-style no-borders has-icon validate-field mb-0">
                          <i className="fa fa-user" />
                          <Field
                            type="text"
                            name="last_name"
                            className="form-control"
                            placeholder="Last Name"
                          />
                          <label className="color-highlight">Last Name</label>
                        </div>
                        <ErrorMessage
                          name="last_name"
                          component="div"
                          className="error-message"
                        />
                      </div>

                      {/* Email */}
                      <div className="input-outer-box mb-3">
                        <div className="input-style no-borders has-icon validate-field mb-0">
                          <i className="fa fa-envelope" />
                          <Field
                            type="email"
                            name="email"
                            className="form-control"
                            placeholder="Email"
                          />
                          <label className="color-highlight">Email</label>
                        </div>
                        <ErrorMessage
                          name="email"
                          component="div"
                          className="error-message"
                        />
                      </div>

                      {/* Phone */}
                      <PhoneInputField />
                    </>
                  ) : (
                    <>
                      <div className="corp-reg-box">
                        {/* Hidden User Type with default value */}
                        <Field
                          type="hidden"
                          name="user_type_id"
                          value={userTypes[0]?.id?.toString() || ""}
                        />
                        {/* Organization Name */}
                        <div className="input-outer-box mb-3">
                          <div className="input-style no-borders has-icon validate-field mb-0">
                            <i className="fa fa-id-card" />
                            <Field
                              type="text"
                              name="organization_name"
                              className="form-control"
                              placeholder="Organization Name"
                            />
                            <label className="color-highlight">
                              Organization Name
                            </label>
                          </div>
                          <ErrorMessage
                            name="organization_name"
                            component="div"
                            className="error-message"
                          />
                        </div>
                        {/* First Name */}
                        <div className="input-outer-box mb-3">
                          <div className="input-style no-borders has-icon validate-field mb-0">
                            <i className="fa fa-user" />
                            <Field
                              type="text"
                              name="first_name"
                              className="form-control"
                              placeholder="First Name"
                            />
                            <label className="color-highlight">
                              First Name
                            </label>
                          </div>
                          <ErrorMessage
                            name="first_name"
                            component="div"
                            className="error-message"
                          />
                        </div>

                        {/* Last Name */}
                        <div className="input-outer-box mb-3">
                          <div className="input-style no-borders has-icon validate-field mb-0">
                            <i className="fa fa-user" />
                            <Field
                              type="text"
                              name="last_name"
                              className="form-control"
                              placeholder="Last Name"
                            />
                            <label className="color-highlight">Last Name</label>
                          </div>
                          <ErrorMessage
                            name="last_name"
                            component="div"
                            className="error-message"
                          />
                        </div>

                        {/* Email */}
                        <div className="input-outer-box mb-3">
                          <div className="input-style no-borders has-icon validate-field mb-0">
                            <i className="fa fa-envelope" />
                            <Field
                              type="email"
                              name="email"
                              className="form-control"
                              placeholder="Email"
                            />
                            <label className="color-highlight">Email</label>
                          </div>
                          <ErrorMessage
                            name="email"
                            component="div"
                            className="error-message"
                          />
                        </div>

                        {/* Phone */}
                        <PhoneInputField />

                        {/* Description */}
                        <DescriptionField />
                      </div>
                    </>
                  )}
                  {/* Hidden user_type */}
                  <Field type="hidden" name="user_type" />
                </>
              )}
              {/* Submit Button */}
              <button
                type="submit"
                className="btn btn-full btn-l font-600 font-13 gradient-highlight mt-4 rounded-s text-white w-100"
                disabled={isSubmitting}
              >
                {resetToken
                  ? "Reset Password"
                  : activeTab === "staff"
                  ? "Send Corporate Enquiry"
                  : "Create Account"}
              </button>

              <div className="row pt-3 mb-3">
                <div className="col-6 text-start">
                  <a
                    href="#"
                    onClick={() => setModalType("forgot")}
                    className="color-highlight"
                  >
                    Forgot Password?
                  </a>
                </div>
                <div className="col-6 text-end">
                  <a
                    href="#"
                    onClick={() => {
                      setModalType("login");
                      handleInitialRegister();
                    }}
                    className="color-highlight"
                  >
                    Sign In here
                  </a>
                </div>
              </div>
            </Form>
          )}
        </Formik>
      </div>
    </>
  );
};

export default SignUpModal;
