"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useTranslations } from "next-intl";
import { Link, useRouter } from "@/i18n/navigation";
import { useRegisterControllerRegisterV1 } from "@/api/user/user-authentication/user-authentication";
import { RoleType, UserRegisterDTODeviceType } from "@/api/user/generated.schemas";
import { signupSchema, SignupFormData } from "@/lib/validations/signup";
import { normalizeEmail, isEmailAlreadyExistsError } from "@/lib/email";
import { trackLinkedInConversion } from "@/lib/linkedin-insight";
import { trackGAEvent } from "@/lib/google-analytics";
import { getUtmParams } from "@/lib/utm";
import EmailVerificationModal from "@/components/modals/EmailVerificationModal";

type UserRole = "individual" | "practitioner";

interface SignupFormProps {
  userType?: UserRole;
}

// Map UI role to backend RoleType
const roleMapping: Record<UserRole, RoleType> = {
  individual: RoleType.Individuals,
  practitioner: RoleType.Practitioners,
};

export default function SignupForm({ userType }: SignupFormProps) {
  const t = useTranslations("signup");
  const tAuth = useTranslations("auth");
  const router = useRouter();
  const [selectedRole, setSelectedRole] = useState<UserRole>(userType || "practitioner");
  const [error, setBannerError] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const {
    register,
    handleSubmit,
    getValues,
    setError,
    formState: { errors },
  } = useForm<SignupFormData>({
    resolver: yupResolver(signupSchema),
    mode: "onTouched",
    defaultValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
      agreeTerms: false,
    },
  });

  const [success, setSuccess] = useState(false);
  const [registeredEmail, setRegisteredEmail] = useState("");
  const [showEmailNotice, setShowEmailNotice] = useState(false);

  const { mutate: registerUser, isPending: isLoading } = useRegisterControllerRegisterV1({
    mutation: {
      onSuccess: (data: any) => {
        setSuccess(true);
        setBannerError("");
        setRegisteredEmail(getValues("email"));
        setShowEmailNotice(!!data?.email_notice);
        // Conversion tracking: signup is a marketing page, so no health data here.
        trackLinkedInConversion();
        // GA4 recommended signup event; `method` distinguishes practitioner vs
        // individual, and any captured campaign params tie it to the source.
        trackGAEvent("sign_up", { method: userType || selectedRole, ...getUtmParams() });
      },
      onError: (err: any) => {
        if (isEmailAlreadyExistsError(err)) {
          setError("email", { message: tAuth("emailAlreadyRegistered") });
          return;
        }
        setBannerError(err?.response?.data?.message || "Registration failed. Please try again.");
      },
    },
  });

  const onSubmit = (data: SignupFormData) => {
    setBannerError("");

    // Use the userType prop if provided, otherwise use selectedRole
    const roleToUse = userType || selectedRole;

    const normalizedEmail = normalizeEmail(data.email);
    const username = normalizedEmail.split("@")[0];

    registerUser({
      data: {
        name: data.name,
        username: username,
        email: normalizedEmail,
        password: data.password,
        role: roleMapping[roleToUse],
        device_name: "web",
        device_type: UserRegisterDTODeviceType.web,
        device_id: `web-${Date.now()}`,
      },
    });
  };

  return (
    <>
      {/* Email Verification Modal - outside form to prevent form submission */}
      <EmailVerificationModal
        isOpen={success}
        onClose={() => router.push('/login')}
        email={registeredEmail}
        showEmailNotice={showEmailNotice}
      />

      <form onSubmit={handleSubmit(onSubmit)} className="w-full space-y-5">
        {error && (
          <div className="p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg">
            {error}
          </div>
        )}

      {/* Role Selector - Only show if userType is not passed from parent */}
      {!userType && (
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-800">
            {t("forIndividuals").replace("For ", "")} / {t("forPractitioners").replace("For ", "")}
          </label>
          <div className="flex rounded-xl bg-gray-100 p-1">
            <button
              type="button"
              onClick={() => setSelectedRole("individual")}
              className={`flex-1 py-2.5 px-4 text-sm font-medium rounded-lg transition cursor-pointer ${
                selectedRole === "individual"
                  ? "bg-[#3B9EC9] text-white shadow-sm"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              {t("forIndividuals")}
            </button>
            <button
              type="button"
              onClick={() => setSelectedRole("practitioner")}
              className={`flex-1 py-2.5 px-4 text-sm font-medium rounded-lg transition cursor-pointer ${
                selectedRole === "practitioner"
                  ? "bg-[#3B9EC9] text-white shadow-sm"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              {t("forPractitioners")}
            </button>
          </div>
        </div>
      )}

      {/* Name Field */}
      <div className="space-y-2">
        <label htmlFor="name" className="block text-sm font-medium text-gray-800">
          {t("fullName")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
              />
            </svg>
          </div>
          <input
            id="name"
            type="text"
            {...register("name")}
            placeholder={t("fullNamePlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-4 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.name ? "border-red-500" : "border-gray-100"
            }`}
          />
        </div>
        {errors.name && (
          <p className="text-sm text-red-600">{errors.name.message}</p>
        )}
      </div>

      {/* Email Field */}
      <div className="space-y-2">
        <label htmlFor="email" className="block text-sm font-medium text-gray-800">
          {t("email")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
              />
            </svg>
          </div>
          <input
            id="email"
            type="email"
            {...register("email")}
            placeholder={t("emailPlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-4 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.email ? "border-red-500" : "border-gray-100"
            }`}
          />
        </div>
        {errors.email && (
          <p className="text-sm text-red-600">{errors.email.message}</p>
        )}
      </div>

      {/* Password Field */}
      <div className="space-y-2">
        <label htmlFor="password" className="block text-sm font-medium text-gray-800">
          {t("password")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
              />
            </svg>
          </div>
          <input
            id="password"
            type={showPassword ? "text" : "password"}
            {...register("password")}
            placeholder={t("passwordPlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-12 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.password ? "border-red-500" : "border-gray-100"
            }`}
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className="absolute inset-y-0 right-0 pr-4 flex items-center cursor-pointer"
          >
            {showPassword ? (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"
                />
              </svg>
            ) : (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
                />
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                />
              </svg>
            )}
          </button>
        </div>
        {errors.password && (
          <p className="text-sm text-red-600">{errors.password.message}</p>
        )}
      </div>

      {/* Confirm Password Field */}
      <div className="space-y-2">
        <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-800">
          {t("confirmPassword")}
        </label>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
              />
            </svg>
          </div>
          <input
            id="confirmPassword"
            type={showConfirmPassword ? "text" : "password"}
            {...register("confirmPassword")}
            placeholder={t("confirmPasswordPlaceholder")}
            disabled={isLoading}
            className={`w-full pl-12 pr-12 py-3.5 rounded-xl bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] transition border disabled:opacity-50 ${
              errors.confirmPassword ? "border-red-500" : "border-gray-100"
            }`}
          />
          <button
            type="button"
            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
            className="absolute inset-y-0 right-0 pr-4 flex items-center cursor-pointer"
          >
            {showConfirmPassword ? (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"
                />
              </svg>
            ) : (
              <svg
                className="h-5 w-5 text-gray-400 hover:text-gray-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
                />
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                />
              </svg>
            )}
          </button>
        </div>
        {errors.confirmPassword && (
          <p className="text-sm text-red-600">{errors.confirmPassword.message}</p>
        )}
      </div>

      {/* Terms & Privacy Checkbox */}
      <div className="space-y-1">
        <div className="flex items-start gap-3">
          <input
            id="agreeTerms"
            type="checkbox"
            {...register("agreeTerms")}
            disabled={isLoading}
            className="mt-0.5 w-5 h-5 rounded border-gray-300 text-[#3B9EC9] focus:ring-[#3B9EC9] cursor-pointer disabled:opacity-50"
          />
          <label htmlFor="agreeTerms" className="text-sm text-gray-600 cursor-pointer">
            {t("agreeTerms")}{" "}
            <Link
              href="/terms"
              target="_blank"
              rel="noopener noreferrer"
              className="font-semibold text-[#3B9EC9] underline hover:text-[#3B9EC9]/80"
            >
              {t("termsOfService")}
            </Link>{" "}
            {t("and")}{" "}
            <Link
              href="/privacy-policy"
              target="_blank"
              rel="noopener noreferrer"
              className="font-semibold text-[#3B9EC9] underline hover:text-[#3B9EC9]/80"
            >
              {t("privacyPolicy")}
            </Link>
          </label>
        </div>
        {errors.agreeTerms && (
          <p className="text-sm text-red-600 ml-8">{errors.agreeTerms.message}</p>
        )}
      </div>

      {/* Submit Button */}
      <div className="pt-4">
        <button
          type="submit"
          disabled={isLoading}
          className="w-full py-4 px-4 bg-[#3B9EC9] hover:bg-[#2D8AB5] text-white font-medium rounded-full transition focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center justify-center"
        >
          {isLoading ? (
            <>
              <svg
                className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
              >
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                ></circle>
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                ></path>
              </svg>
              {t("createAccount")}...
            </>
          ) : (
            t("createAccount")
          )}
        </button>
      </div>

      {/* Login Link */}
      <p className="text-center text-sm text-gray-600 pt-2">
        {t("haveAccount")}{" "}
        <Link href="/login" className="font-semibold text-gray-900 hover:text-[#3B9EC9]">
          {t("signIn")}
        </Link>
      </p>
      </form>
    </>
  );
}
