"use client";
import Checkbox from "@/components/form/input/Checkbox";
import Input from "@/components/form/input/InputField";
import Label from "@/components/form/Label";
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "@/icons";
import { apiCreateOTP, apiSignUp, apiVerifyOTP } from "@/service/auth";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
import { API, HOME_URL } from "../../../api";
import Swal from "sweetalert2";
import { useRouter } from "next/navigation";


export default function SignUpForm() {
  const [showPassword, setShowPassword] = useState(false);
  const [isChecked, setIsChecked] = useState(false);

  const router = useRouter();

  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    fname: "",
    lname: "",
    email: "",
    password: "",
  });
  const [otp, setOtp] = useState("");
  const [errorMsg, setErrorMsg] = useState("");
  const [loading, setLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
    setErrorMsg("");
  };

  const isValidEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const isValidPassword = (pass: string) => {
    const passwordRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
    return passwordRegex.test(pass);
  };

  const handleSignUpClick = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrorMsg("");

    if (
      !formData.fname ||
      !formData.lname ||
      !formData.email ||
      !formData.password
    ) {
      setErrorMsg("Vui lòng điền đầy đủ thông tin.");
      return;
    }
    if (!isValidEmail(formData.email)) {
      setErrorMsg("Email không đúng định dạng.");
      return;
    }
    if (!isValidPassword(formData.password)) {
      setErrorMsg(
        "Mật khẩu chưa đủ điều kiện. Vui lòng nhập tối thiểu 8 ký tự, 1 in hoa, 1 số và 1 ký tự đặc biệt.",
      );
      return;
    }

    try {
      setLoading(true);
      await apiCreateOTP(formData.email);
      setStep(2);
    } catch (error) {
      setErrorMsg("Lỗi khi tạo OTP. Vui lòng thử lại.");
      toast.error("Tạo OTP thất bại. Vui lòng kiểm tra lại thông tin.");
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtpSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrorMsg("");

    if (!otp) {
      setErrorMsg("Vui lòng nhập OTP.");
      return;
    }

    try {
      setLoading(true);

      const verifyRes = await apiVerifyOTP(formData.email, otp);

      const tokenId = verifyRes?.data?.token_id;
      if (!tokenId) {
        throw new Error("OTP không hợp lệ hoặc không có token_id");
      }

      const signupPayload = {
        display_name: `${formData.fname} ${formData.lname}`.trim(),
        email: formData.email,
        password: formData.password,
        token_id: tokenId,
      };

      const signupRes = await apiSignUp(signupPayload);

      await Swal.fire({
        title: "Tạo tài khoản thành công!. Quay về trang đăng nhập để tiếp tục",
        icon: "success",
        timer: 1500,
        showConfirmButton: false,
      });
      router.push("/signin");

    } catch (error) {
      const errorMessage =
        error instanceof Error
          ? error.message
          : "Xác thực OTP hoặc đăng ký thất bại.";
      setErrorMsg(errorMessage || "Xác thực OTP hoặc đăng ký thất bại.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full overflow-y-auto no-scrollbar">
      <div className="w-full max-w-md sm:pt-10 mx-auto mb-5">
        <Link
          href="/"
          className="inline-flex items-center text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
        >
          <ChevronLeftIcon />
          Back to dashboard
        </Link>
      </div>

      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-5 sm:mb-8">
            <h1 className="mb-2 font-semibold text-gray-800 text-title-sm dark:text-white/90 sm:text-title-md">
              {step === 1 ? "Sign Up" : "Verify OTP"}
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {step === 1
                ? "Enter your email and password to sign up!"
                : `We sent an OTP to ${formData.email}. Please check your email and enter it below.`}
            </p>
          </div>

          {errorMsg && (
            <div className="mb-4 text-sm text-error-500 bg-error-50 p-3 rounded">
              {errorMsg}
            </div>
          )}

          {step === 1 && (
            <>
              <div className="grid grid-cols-1 gap-3 sm:gap-5">
                <button
                  onClick={() => {
                    // Redirect back to the same origin (avoid hard-coded port/env mismatches).
                    const redirectUrl =
                      typeof window !== "undefined" ? window.location.origin : HOME_URL;
                    window.location.href = `${API.Auth.GOOGLE_LOGIN}?redirect=${encodeURIComponent(
                      redirectUrl
                    )}`;
                  }}
                className="inline-flex items-center justify-center gap-3 py-3 text-sm font-normal text-gray-700 transition-colors bg-gray-100 rounded-lg px-7 hover:bg-gray-200 hover:text-gray-800 dark:bg-white/5 dark:text-white/90 dark:hover:bg-white/10"
              >
                  <svg
                    width="20"
                    height="20"
                    viewBox="0 0 20 20"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M18.7511 10.1944C18.7511 9.47495 18.6915 8.94995 18.5626 8.40552H10.1797V11.6527H15.1003C15.0011 12.4597 14.4654 13.675 13.2749 14.4916L13.2582 14.6003L15.9087 16.6126L16.0924 16.6305C17.7788 15.1041 18.7511 12.8583 18.7511 10.1944Z"
                      fill="#4285F4"
                    />
                    <path
                      d="M10.1788 18.75C12.5895 18.75 14.6133 17.9722 16.0915 16.6305L13.274 14.4916C12.5201 15.0068 11.5081 15.3666 10.1788 15.3666C7.81773 15.3666 5.81379 13.8402 5.09944 11.7305L4.99473 11.7392L2.23868 13.8295L2.20264 13.9277C3.67087 16.786 6.68674 18.75 10.1788 18.75Z"
                      fill="#34A853"
                    />
                    <path
                      d="M5.10014 11.7305C4.91165 11.186 4.80257 10.6027 4.80257 9.99992C4.80257 9.3971 4.91165 8.81379 5.09022 8.26935L5.08523 8.1534L2.29464 6.02954L2.20333 6.0721C1.5982 7.25823 1.25098 8.5902 1.25098 9.99992C1.25098 11.4096 1.5982 12.7415 2.20333 13.9277L5.10014 11.7305Z"
                      fill="#FBBC05"
                    />
                    <path
                      d="M10.1789 4.63331C11.8554 4.63331 12.9864 5.34303 13.6312 5.93612L16.1511 3.525C14.6035 2.11528 12.5895 1.25 10.1789 1.25C6.68676 1.25 3.67088 3.21387 2.20264 6.07218L5.08953 8.26943C5.81381 6.15972 7.81776 4.63331 10.1789 4.63331Z"
                      fill="#EB4335"
                    />
                  </svg>
                  Sign up with Google
                </button>
              </div>
              <div className="relative py-3 sm:py-5">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-gray-200 dark:border-gray-800"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="p-2 text-gray-400 bg-white dark:bg-gray-900 sm:px-5 sm:py-2">
                    Or
                  </span>
                </div>
              </div>

              <form onSubmit={handleSignUpClick}>
                <div className="space-y-5">
                  <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <div className="sm:col-span-1">
                      <Label>
                        First Name<span className="text-error-500">*</span>
                      </Label>
                      <Input
                        type="text"
                        name="fname"
                        defaultValue={formData.fname}
                        onChange={handleChange}
                        placeholder="Enter your first name"
                      />
                    </div>

                    <div className="sm:col-span-1">
                      <Label>
                        Last Name<span className="text-error-500">*</span>
                      </Label>
                      <Input
                        type="text"
                        name="lname"
                        defaultValue={formData.lname}
                        onChange={handleChange}
                        placeholder="Enter your last name"
                      />
                    </div>
                  </div>

                  <div>
                    <Label>
                      Email<span className="text-error-500">*</span>
                    </Label>
                    <Input
                      type="email"
                      name="email"
                      defaultValue={formData.email}
                      onChange={handleChange}
                      placeholder="Enter your email"
                    />
                  </div>

                  <div>
                    <Label>
                      Password<span className="text-error-500">*</span>
                    </Label>

                    <div
                      className={`relative ${formData.password.length > 0 && !isValidPassword(formData.password) ? "border border-red-500 ring-1 ring-red-500 rounded-lg" : ""}`}
                    >
                      <Input
                        name="password"
                        defaultValue={formData.password}
                        onChange={handleChange}
                        placeholder="Min. 8 characters"
                        type={showPassword ? "text" : "password"}
                      />
                      <span
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2"
                      >
                        {showPassword ? <EyeIcon /> : <EyeCloseIcon />}
                      </span>
                    </div>

                    <p
                      className={`mt-2 text-xs ${formData.password.length === 0 ? "text-gray-400" : isValidPassword(formData.password) ? "text-green-500" : "text-red-500"}`}
                    >
                      Mật khẩu phải chứa tối thiểu 8 ký tự, 1 chữ cái in hoa, 1
                      chữ số và 1 ký tự đặc biệt.
                    </p>
                  </div>

                  <div className="flex items-center gap-3">
                    <div
                      className={
                        formData.password.length > 0 &&
                        !isValidPassword(formData.password)
                          ? "opacity-50 cursor-not-allowed"
                          : ""
                      }
                    >
                      <Checkbox
                        className="w-5 h-5"
                        checked={isChecked}
                        onChange={(val) => {
                          if (isValidPassword(formData.password))
                            setIsChecked(val);
                        }}
                        disabled={!isValidPassword(formData.password)}
                      />
                    </div>
                    <p className="inline-block font-normal text-gray-500 dark:text-gray-400">
                      By creating an account means you agree to the{" "}
                      <span className="text-gray-800 dark:text-white/90">
                        Terms and Conditions,
                      </span>{" "}
                      and our{" "}
                      <span className="text-gray-800 dark:text-white">
                        Privacy Policy
                      </span>
                    </p>
                  </div>

                  <div>
                    <button
                      type="submit"
                      disabled={
                        !isChecked ||
                        loading ||
                        !isValidPassword(formData.password)
                      }
                      className={`flex items-center justify-center w-full px-4 py-3 text-sm font-medium text-white transition rounded-lg bg-brand-500 shadow-theme-xs 
                        ${!isChecked || !isValidPassword(formData.password) ? "opacity-50 cursor-not-allowed" : "hover:bg-brand-600"}`}
                    >
                      {loading ? "Processing..." : "Sign Up"}
                    </button>
                  </div>
                </div>
              </form>

              <div className="mt-5">
                <p className="text-sm font-normal text-center text-gray-700 dark:text-gray-400 sm:text-start">
                  Already have an account?{" "}
                  <Link
                    href="/signin"
                    className="text-brand-500 hover:text-brand-600 dark:text-brand-400"
                  >
                    Sign In
                  </Link>
                </p>
              </div>
            </>
          )}

          {step === 2 && (
            <form onSubmit={handleVerifyOtpSubmit}>
              <div className="space-y-5">
                <div>
                  <Label>
                    OTP Code<span className="text-error-500">*</span>
                  </Label>
                  <Input
                    type="text"
                    name="otp"
                    defaultValue={otp}
                    onChange={(e) => setOtp(e.target.value)}
                    placeholder="Enter the 6-digit code"
                  />
                </div>

                <div className="flex gap-3">
                  <button
                    type="button"
                    onClick={() => setStep(1)}
                    className="flex items-center justify-center w-1/3 px-4 py-3 text-sm font-medium text-gray-700 transition rounded-lg bg-gray-200 hover:bg-gray-300"
                  >
                    Back
                  </button>
                  <button
                    type="submit"
                    disabled={loading}
                    className="flex items-center justify-center w-2/3 px-4 py-3 text-sm font-medium text-white transition rounded-lg bg-brand-500 shadow-theme-xs hover:bg-brand-600"
                  >
                    {loading ? "Verifying..." : "Verify & Register"}
                  </button>
                </div>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
