"use client";

import {
  FormInput,
  FormButton,
  FormCheckBox,
} from "@/app/components/form/forms";
import Link from "next/link";
import { SocialButton } from "@/app/components/button";
import { useRouter } from "next/navigation";
import { useState, useEffect, useRef } from "react";
import Cookies from "js-cookie";
import { signIn } from "next-auth/react";
import CheckboxImageGroup from "../form/CheckBoxImg/CheckboxImageGroup";
import { CheckTypes } from "../form/CheckBoxImg/CheckTypes";
import ReCAPTCHA from "react-google-recaptcha";

export default function SignupForm() {
  const router = useRouter();

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [marketingConsent, setMarketingConsent] = useState(true);
  const [tncAccepted, setTncAccepted] = useState(true);

  const [error, setError] = useState("");
  const [errorTnc, setErrorTnc] = useState("");
  const [success, setSuccess] = useState("");

  const [roleSelected, setRoleSelected] = useState<number[]>([]);
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);

  const captchaRef = useRef<ReCAPTCHA>(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("go")) {
      setEmail(localStorage.getItem("email") || "");
    }
  }, []);

  const handleCaptchaChange = (token: string | null) => {
    setCaptchaToken(token);
  };

  const userOptions: CheckTypes[] = [
    {
      id: 1,
      role: "user_co_creator",
      label: "Co-Creator",
      image: "/icons/user-co-creator.png",
      summary: "I want to design and create my own custom piece.",
    },
    {
      id: 9,
      role: "user_seeker",
      label: "Seeker",
      image: "/icons/user-seeker.png",
      summary: "I want to browse and buy unique pieces from the Morni store.",
    },
    {
      id: 4,
      role: "user_brand_partner",
      label: "Brand Partner",
      image: "/icons/user-brand-partner.png",
      summary:
        "I run a brand and want to work with Morni to design and produce clothing.",
    },
    {
      id: 7,
      role: "user_design_house",
      label: "Design House",
      image: "/icons/user-design-house.png",
      summary:
        "I run a studio or workshop that can produce garments for Morni customers.",
    },
    {
      id: 8,
      role: "user_supplier",
      label: "Supplier",
      image: "/icons/user-supplier.png",
      summary:
        "I provide natural fabrics or materials that can be used in Morni's production.",
    },
    {
      id: 6,
      role: "user_wholesaler",
      label: "Wholesaler",
      image: "/icons/user-wholesaler.png",
      summary: "I want to buy Morni pieces in bulk for my store or business.",
    },
  ];

  const handleUserSelection = (roles: number[]) => {
    setRoleSelected(roles);
  };

  const handleGoogleSignIn = () => {
    localStorage.setItem("google_auth_source", "signup");
    signIn("google", { callbackUrl: "/google-login" });
  };

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

    setError("");
    setErrorTnc("");
    setSuccess("");

    if (!name) return setError("Name is required.");
    if (!email) return setError("Email is required.");
    if (!password) return setError("Password is required.");
    if (password.length < 6)
      return setError("Password must be at least 6 characters long.");
    if (!tncAccepted)
      return setErrorTnc("You must accept the terms and conditions.");
    if (!captchaToken)
      return setError("Please verify that you are not a robot.");

    try {
      localStorage.setItem("email", email);
      
      // ✅ NEW: Use Next.js API route - token handled server-side
      const response = await fetch('/api/auth/register', {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          email,
          password,
          password_confirmation: password,
          marketing_consent: marketingConsent,
          roleSelected,
          captchaToken,
        }),
      });

      const data = await response.json();
      
      if (response.ok && data.success) {
        // Reset captcha on success
        captchaRef.current?.reset();
        setCaptchaToken(null);
        
        // Store OTP if provided
        if (data.data?.otp) {
          localStorage.setItem("otp", data.data.otp);
        }

        setSuccess("Verification code sent to your email.");
        router.push("/auth/otpverification");
      } else {
        // Reset captcha on error
        captchaRef.current?.reset();
        setCaptchaToken(null);
        setError(data.message || "Registration failed. Please try again.");
      }
    } catch (err) {
      console.error("Registration error:", err);
      setError("Something went wrong. Please try again.");
    }
  };

  return (
    <>
      <div className="mt-5">
        <SocialButton
          id="btn_google_auth"
          type="button"
          icon="icon-[flat-color-icons--google]"
          label="Continue with Google"
          color="gray"
          onClick={handleGoogleSignIn}
        />
      </div>

      <div className="mt-10">
        <div className="text-md font-medium text-gray-800">
          Or create with email
        </div>

        {success && <p className="text-green-500">{success}</p>}

        <form onSubmit={handleSignup} autoComplete="off">
          <FormInput
            type="text"
            id="signup_name"
            label="Full Name"
            require
            value={name}
            onChange={(e: any) => setName(e.target.value)}
          />

          <FormInput
            type="email"
            id="signup_email"
            label="Email"
            require
            value={email}
            onChange={(e: any) => setEmail(e.target.value)}
          />

          <FormInput
            type="password"
            id="signup_password"
            label="Password"
            require
            value={password}
            onChange={(e: any) => setPassword(e.target.value)}
          />

          {error && <p className="mt-2 text-red-500">{error}</p>}

          <div className="mt-4">
            <CheckboxImageGroup
              options={userOptions}
              onChange={handleUserSelection}
            />
          </div>

          <div className="mt-8">
            <FormCheckBox
              id="check_marketing"
              label="Sign me up to receive Morni offers, promotions and other commercial messages."
              value={marketingConsent.toString()}
              onChange={() => setMarketingConsent(!marketingConsent)}
            />

            <FormCheckBox
              id="check_tnc"
              label={[
                "I acknowledge that I have read and agree to the Morni’s ",
                <Link
                  key="terms"
                  href="/terms-and-conditions"
                  className="underline"
                >
                  Terms of service
                </Link>,
                ", ",
                <Link
                  key="privacy"
                  href="/privacy-policy"
                  className="underline"
                >
                  Privacy policy
                </Link>,
                ", ",
                <Link key="cookies" href="/cookie-policy" className="underline">
                  Cookies policy
                </Link>,
                ".",
              ]}
              value={tncAccepted.toString()}
              onChange={() => setTncAccepted(!tncAccepted)}
            />
          </div>

          {errorTnc && <p className="mt-2 text-red-500">{errorTnc}</p>}

          <div className="mt-6">
            <ReCAPTCHA
              ref={captchaRef}
              sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY!}
              onChange={handleCaptchaChange}
            />
          </div>

          <div className="mt-4">
            <FormButton
              id="btn_signup"
              label="Create Account"
              type="submit"
              color="gray"
              hairline="amber"
              disabled={!captchaToken}
            />
          </div>
        </form>
      </div>
    </>
  );
}
