"use client";
import { TextLink, SocialButton } from "@/app/components/button";
import { FormButton, FormInput } from "@/app/components/form/forms";
import InputPassword from "@/app/components/form/inputpassword";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import Cookies from "js-cookie";
import React from "react";
import { signIn } from "next-auth/react";

export default function LoginForm() {

  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [emailError, setEmailError] = useState(false);
  const [passwordError, setPasswordError] = useState(false);
  const [success, setSuccess] = useState("");
  const [error, setError] = useState("");
  const searchParams = useSearchParams();
  // Fix: reconstruct full redirect param, including all query params after first '='
  const [redirect, setRedirect] = useState("/category");

  const [hasNormalRedirection, setHasNormalRedirection] = useState(true);

  // Only run on client side
  React.useEffect(() => {
    if (searchParams.has("redirect") && typeof window !== "undefined") {
      const fullQuery = window.location.search; 

      // Find where 'redirect=' starts
      const redirectStart = fullQuery.indexOf('redirect=');
      const redirectValue = fullQuery.substring(redirectStart + 9); // 9 is length of 'redirect='

     

      setHasNormalRedirection(false);
      setRedirect(decodeURIComponent(redirectValue));
      
    }
  }, [searchParams]);



  const handleGoogleSignIn = () => {
    // Store the source before initiating OAuth
    if (typeof window !== 'undefined') {
      localStorage.setItem("google_auth_source", "login");
      
      // Store the redirect URL for use after Google authentication
      if (redirect && redirect !== "/category") {
        localStorage.setItem("google_auth_redirect", redirect);
      }
    }
    
    signIn("google", {
      callbackUrl: "/google-login"
    });
  };
  
  const handleSignup = async (e: any) => {
    e.preventDefault();

    // Basic validation
    if (!email) {
      setEmailError(true);
      return;
    }
    if (!password) {
      setPasswordError(true);
      return;
    }

    setPasswordError(false);
    setEmailError(false);
    setError(""); // Clear any previous errors
    setSuccess(""); // Clear any previous success messages

    try {
      // Use Next.js API route - handles both server-side and returns token for client-side
      const response = await fetch('/api/auth/login', {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      const data = await response.json();

      console.log("Login_response", data);
 
      if (response.ok && data.success) {
        // Set client-side cookies for backward compatibility
        if (data.access_token) {
          Cookies.set("token", data.access_token, {
            expires: 7,
            path: "/",
          });
        }

        if (data.data?.has_user_allow_to_share_vision_board !== undefined || data.has_user_allow_to_share_vision_board !== undefined) {
          const visionBoardValue = data.data?.has_user_allow_to_share_vision_board ?? data.has_user_allow_to_share_vision_board;
          Cookies.set("has_user_allow_to_share_vision_board", 
            visionBoardValue.toString(), {
            expires: 7,
            path: "/",
          });
        }

        // getUser is set server-side, but also available in response
        if (data.data) {
          Cookies.set("getUser", JSON.stringify(data.data), {
            expires: 7,
            path: "/",
          });
        }

        // Clear error state before redirect
        setError("");
        setSuccess("Login successful! Redirecting...");

        if (hasNormalRedirection) {
          router.push(redirect);
        } else {
          window.location.href = redirect;
        }
      } else {
        // Handle error
        setError(data.message || "Invalid email or password");
        console.error(data.message);
      }
    } catch (err) {
      console.error("Something went wrong. Please try again.", err);
      setError("Something went wrong. Please try again.");
    }
  };

  return (
    <>
      
      <div className="mt-2 flex flex-col">
        <div className="flex flex-row">
          <SocialButton
            id="btn_google_auth"
            type="button"
            icon="icon-[flat-color-icons--google]"
            label="Continue with Google"
            color="gray"
            onClick={handleGoogleSignIn}
          />
          {/* <SocialButton
            id="btn_apple_auth"
            type="button"
            icon="icon-[devicon--apple]"
            label="Apple"
            color="gray"
          /> */}
        </div>
      </div>

      <div className="flex flex-col">
        <div className="text-md mt-10 font-medium text-gray-800">
          Or continue with
        </div>
        <form onSubmit={handleSignup} autoComplete="off">
          <FormInput
            type="email"
            id="email_login"
            label="Email"
            require={true}
            value={email}
            onChange={(e: any) => {
              setEmail(e.target.value);
              setError(""); // Clear error when user types
            }}
          />
          <div className="mt-8">
            <InputPassword
              id="password_login"
              name="password"
              label="Password"
              require={true}
              value={password}
              onChange={(e: any) => {
                setPassword(e.target.value);
                setError(""); // Clear error when user types
              }}
            />
          </div>
          {error && <p className="text-red-500 mt-2">{error}</p>}
          {success && <p className="text-green-500 mt-2">{success}</p>}
          <FormButton
            id="btn_login"
            label="Log in"
            type="submit"
            color="gray"
            hairline="amber"
            disabled={false}
          />
        </form>
      </div>
    </>
  );
}
