"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Eye, EyeOff } from "lucide-react";
// import { ReCAPTCHA } from "react-google-recaptcha";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";

const InputItem = ({
  label,
  id,
  type = "text",
  placeholder,
  required,
  value,
  onChange,
}: {
  label: string;
  id: string;
  type?: string;
  placeholder: string;
  required?: boolean;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) => (
  <div>
    <label
      htmlFor={id}
      className="block text-[16px] leading-[150%] font-outfit font-medium text-[#000000] "
    >
      {label} {required && <span className="text-[#FF0000] text-[20px] leading-[150%] font-outfit font-medium">*</span>}
    </label>
    <div className="relative">
      <input
        id={id}
        type={type}
        placeholder={placeholder}
        value={value}
        onChange={onChange}
        className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-1.5 focus:outline-none focus:border-gray-300 text-[18px] leading-[150%] font-outfit font-light text-[18px] text-[#000000] placeholder:text-[#999999]"
      />
      <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
    </div>
  </div>
);

const IconArrowRight = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
    <path d="M0 18C0 8.05887 8.05887 0 18 0V0C27.9411 0 36 8.05887 36 18V18C36 27.9411 27.9411 36 18 36V36C8.05887 36 0 27.9411 0 18V18Z" fill="#F7FAF8" />
    <path d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" stroke="#053F31" strokeWidth="2" />
  </svg>
);

export default function LoginComponent() {
  const router = useRouter();
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);
  const [form, setForm] = useState({
    email: "",
    password: "",
  });
  // const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const [error, setError] = useState("");

  useEffect(() => {
    const syncLocale = () => {
      setUiLocale(getStoredLocale());
    };
    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  const update = (field: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm((prev) => ({ ...prev, [field]: e.target.value }));
    setError("");
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!form.email.trim()) {
      setError("Please enter your email.");
      return;
    } else if (!form.password) {
      setError("Please enter your password.");
      return;
    }
    // if (!captchaToken) {
    //   setError("Please verify that you are not a robot.");
    //   return;
    // }
    setError("");
    try {
      const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
      const authUrl = `${base}/store/customers/login`;
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
      };
      const publishableKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY;
      if (publishableKey) {
        headers["x-publishable-api-key"] = publishableKey;
      }
      const res = await fetch(authUrl, {
        method: "POST",
        headers,
        body: JSON.stringify({ email: form.email, password: form.password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError((data.error as string) || data.message || "Invalid email or password.");
        return;
      }
      const token = data.token ?? data.access_token ?? null;
      const userEmail = data.email ?? form.email;
      const firstName = data.customer?.first_name || "";
      const lastName = data.customer?.last_name || "";
      const fullName = (firstName + " " + lastName).trim();
      const displayName = fullName || (userEmail ? userEmail.split("@")[0] : "") || userEmail;
      if (token) {
        localStorage.setItem("currentUser", JSON.stringify({ 
          email: userEmail, 
          token, 
          name: displayName,
          first_name: firstName,
          last_name: lastName,
          fullName: fullName
        }));
      }
      router.push("/dashboard");
    } catch (err) {
      setError("Unable to reach sign-in service. Please try again.");
    } finally {
    }
  };

  return (
    <div className="flex justify-center font-outfit w-full 2xl:max-w-[605px] xl:max-w-[605px] lg:max-w-[450px]">
      <div className="hidden xl:block w-full 2xl:max-w-[605px] xl:max-w-[605px] lg:max-w-[450px] ">
        <div className="rounded-[20px] border border-[#053F31]/15 bg-[#F7FAF8]/80 p-[15px]">
          <p className="font-semibold text-[#053F31] mb-[14px]">{staticCopy.login[uiLocale].signIn}</p>
          {error && (
            <div className="mb-4 p-3 rounded-[5px] bg-red-50 border border-red-200 text-red-700 text-[14px] font-outfit">
              {error}
            </div>
          )}
          <form onSubmit={handleSubmit} className="space-y-[10px]">
            <div>
              <InputItem
                id="signin-email"
                label={staticCopy.login[uiLocale].emailLabel}
                type="email"
                placeholder={staticCopy.login[uiLocale].emailPlaceholder}
                required
                value={form.email}
                onChange={update("email")}
              />
            </div>

            <div>
              <InputItem
                id="signin-password"
                label={staticCopy.login[uiLocale].passwordLabel}
                type="password"
                placeholder={staticCopy.login[uiLocale].passwordPlaceholder}
                required
                value={form.password}
                onChange={update("password")}
              />
            </div>

            <div className="flex items-center justify-between pt-[10px]">
              {/* reCAPTCHA disabled for login
              <div className="mt-2">
                <ReCAPTCHA
                  sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || ""}
                  onChange={(token: string | null) => setCaptchaToken(token)}
                  onExpired={() => setCaptchaToken(null)}
                />
              </div>
              */}
              <Link
                href="/forgot-password"
                className="text-[16px] leading-[150%] font-outfit text-[#053F31] font-semibold hover:underline transition-colors"
              >
                {staticCopy.login[uiLocale].forgotPassword}
              </Link>
            </div>

            <div className="pt-[8px]">
              <button
                type="submit"
                className="inline-flex items-center justify-center gap-[10px] bg-[#053F31] font-outfit text-[18px] leading-[150%] text-white font-semibold p-[7px_7px_7px_15px] cursor-pointer rounded-full border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
              >
                {staticCopy.login[uiLocale].submitButton}
                <IconArrowRight />
              </button>
            </div>
          </form>
        </div>
      </div>
      <div className="w-full  flex flex-col lg:flex-row gap-[30px] rounded-[20px] xl:hidden">
        <div className="w-full mx-auto bg-[#F7FAF8] border border-[#053F31]/20 rounded-[20px] p-[20px] sm:p-[17px]">
          <h3 className="font-semibold text-[#053F31] mb-[20px] pb-[15px] border-b-2 border-[#000000]/10">
            {staticCopy.login[uiLocale].signIn}
          </h3>

          {error && (
            <div className="mb-4 p-3 rounded-[5px] bg-red-50 border border-red-200 text-red-700 text-[14px] font-outfit">
              {error}
            </div>
          )}

          <form className="3" onSubmit={handleSubmit}>
            <div className="mb-[21px]">
              <InputItem
                id="signin-email"
                label={staticCopy.login[uiLocale].emailLabel}
                type="email"
                placeholder={staticCopy.login[uiLocale].emailPlaceholder}
                required
                value={form.email}
                onChange={update("email")}
              />
            </div>
            <div className="mb-[21px]">
              <InputItem
                id="signin-password"
                label={staticCopy.login[uiLocale].passwordLabel}
                type="password"
                placeholder={staticCopy.login[uiLocale].passwordPlaceholder}
                required
                value={form.password}
                onChange={update("password")}
              />
            </div>

            <Link
              href="/forgot-password"
              className="text-[18px] leading-[150%] font-outfit mt-2 md:mt-0 text-[#053F31] font-semibold hover:underline transition-colors"
            >
              {staticCopy.login[uiLocale].forgotPassword}
            </Link>

            {/* reCAPTCHA disabled for login
            <div className="mt-4 mb-4">
              <ReCAPTCHA
                sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || ""}
                onChange={(token: string | null) => setCaptchaToken(token)}
                onExpired={() => setCaptchaToken(null)}
              />
            </div>
            */}

            <div className="pt-[8px]">
              <button
                type="submit"
                className="inline-flex items-center justify-center gap-[10px] bg-[#053F31] font-outfit text-[18px] leading-[150%] text-white font-semibold p-[7px_7px_7px_15px] cursor-pointer rounded-full border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
              >
                {staticCopy.login[uiLocale].submitButton}
                <IconArrowRight />
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

 