"use client";

import React, { useState, Suspense, useEffect } from "react";
import Link from "next/link";
import { useRouter, useSearchParams, useParams } from "next/navigation";
import { Eye, EyeOff, Check } from "lucide-react";
import type {
  SubmitPasswordResetPayload,
  SubmitPasswordResetResult,
} from "@/lib/submit-password-reset";
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,
    isPassword = false,
}: {
    label: string;
    id: string;
    type?: string;
    placeholder: string;
    required?: boolean;
    value: string;
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    isPassword?: boolean;
}) => {
    const [show, setShow] = useState(false);
    const inputType = isPassword ? (show ? "text" : "password") : type;

    return (
        <div>
            <label
                htmlFor={id}
                className="block text-[16px] font-medium text-[#000000] mb-[9px]"
            >
                {label} {required && <span className="text-[#FF0000]">*</span>}
            </label>
            <div className="relative">
                <input
                    id={id}
                    type={inputType}
                    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-[#000000] placeholder:text-[#999999] ${isPassword ? "pr-12" : ""}`}
                />

                {isPassword && (
                    <button
                        type="button"
                        onClick={() => setShow(!show)}
                        className="absolute right-4 top-1/2 -translate-y-1/2 text-[#053F31]/50 hover:text-[#053F31] focus:outline-none z-20"
                    >
                        {show ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                )}

                <div className="absolute bottom-0 left-[30px] h-[3px] 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.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z"
            fill="#F7FAF8"
        />
        <path
            d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5"
            stroke="#053F31"
            strokeWidth="2"
        />
    </svg>
);

export type ResetPasswordPageProps = {
    submitPasswordReset?: (
        payload: SubmitPasswordResetPayload
    ) => Promise<SubmitPasswordResetResult>;
};

function ResetPasswordForm({ submitPasswordReset }: ResetPasswordPageProps) {
    const router = useRouter();
    const params = useParams();
    const searchParams = useSearchParams();
    const email = searchParams.get("email");
    const routeToken = params?.token;
    const resetToken = (typeof routeToken === "string" ? routeToken : Array.isArray(routeToken) ? routeToken[0] : searchParams.get("token")) ?? "";

    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [status, setStatus] = useState<"idle" | "success" | "error">("idle");
    const [message, setMessage] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

    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 t =
        staticCopy.resetPassword[uiLocale as keyof typeof staticCopy.resetPassword] ??
        staticCopy.resetPassword["en-EN"];

    const passwordRegex = {
        minLength: 8,
        uppercase: /[A-Z]/,
        lowercase: /[a-z]/,
        number: /[0-9]/,
        specialChar: /[!@#$%^&*(),.?":{}|<>]/,
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setStatus("idle");
        setMessage("");

        if (!resetToken) {
            setStatus("error");
            setMessage("Invalid link. No reset token.");
            return;
        }

        if (!submitPasswordReset && !email) {
            setStatus("error");
            setMessage("Invalid link. No email provided.");
            return;
        }

        if (password !== confirmPassword) {
            setStatus("error");
            setMessage("Passwords do not match.");
            return;
        }

        if (password.length < passwordRegex.minLength ||
            !passwordRegex.uppercase.test(password) ||
            !passwordRegex.lowercase.test(password) ||
            !passwordRegex.number.test(password) ||
            !passwordRegex.specialChar.test(password)) {
            setStatus("error");
            setMessage("Password does not meet the requirements.");
            return;
        }

        if (submitPasswordReset) {
            setIsSubmitting(true);
            try {
                const result = await submitPasswordReset({
                    token: decodeURIComponent(resetToken),
                    new_password: password,
                    confirm_password: confirmPassword,
                });
                if (!result.ok) {
                    setStatus("error");
                    setMessage(result.message);
                    return;
                }
                setStatus("success");
                setMessage(
                    result.message?.trim() ||
                        "Password reset successfully! Redirecting to login..."
                );
                setTimeout(() => {
                    router.push("/login");
                }, 2000);
            } finally {
                setIsSubmitting(false);
            }
            return;
        }

        const storedUsers = localStorage.getItem("mock_users");
        if (storedUsers) {
            const users = JSON.parse(storedUsers);
            const userIndex = users.findIndex((u: { email: string }) => u.email === email);

            if (userIndex !== -1) {
                users[userIndex].password = password;
                localStorage.setItem("mock_users", JSON.stringify(users));

                setStatus("success");
                setMessage("Password reset successfully! Redirecting to login...");

                setTimeout(() => {
                    router.push("/login");
                }, 2000);
            } else {
                setStatus("error");
                setMessage("User not found.");
            }
        } else {
            setStatus("error");
            setMessage("User database not found.");
        }
    };

    return (
        <section className="mx-4 sm:mx-6 md:mx-8 lg:mx-10 xl:mx-12 font-outfit selection:bg-[#053F31] selection:text-white">
            <div className="mx-4 sm:mx-6 md:mx-8 lg:mx-10 xl:mx-12 mb-[50px] xl:mb-[70px]">
                <div className="max-w-[520px] mx-auto bg-[#F7FAF8] border border-gray-200 rounded-2xl p-[25px] sm:p-[40px] shadow-sm">
                    <p className="font-semibold text-[#053F31] mb-[20px] pb-[15px] border-b-2">
                        {t.title}
                    </p>

                    {message && (
                        <div className={`mb-6 p-4 border rounded-lg text-sm ${status === "success"
                            ? "bg-green-100 border-green-200 text-[#053F31]"
                            : "bg-red-50 border-red-200 text-red-700"
                            }`}>
                            {message}
                        </div>
                    )}

                    <form className="space-y-6" onSubmit={handleSubmit}>
                        <div className="flex flex-col gap-2">
                            <InputItem
                                id="new-password"
                                label={t.newPasswordLabel}
                                type="password"
                                placeholder={t.newPasswordPlaceholder}
                                required
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                isPassword={true}
                            />

                            {password.length > 0 && (
                                <div className="bg-white p-3 rounded-[5px] border border-[#053F31]/20 shadow-sm mt-2 text-sm space-y-1 font-outfit">
                                    <p className="text-xs font-semibold text-[#053F31]/70 mb-2 uppercase tracking-wide">{t.requirementsHeading}</p>

                                    <div className={`flex items-center gap-2 ${password.length >= passwordRegex.minLength ? "text-[#053F31]" : "text-gray-400"}`}>
                                        {password.length >= passwordRegex.minLength ? <Check size={14} /> : <div className="w-3.5 h-3.5 rounded-full border border-gray-300"></div>}
                                        <span>{t.reqMinLength}</span>
                                    </div>

                                    <div className={`flex items-center gap-2 ${passwordRegex.uppercase.test(password) ? "text-[#053F31]" : "text-gray-400"}`}>
                                        {passwordRegex.uppercase.test(password) ? <Check size={14} /> : <div className="w-3.5 h-3.5 rounded-full border border-gray-300"></div>}
                                        <span>{t.reqUppercase}</span>
                                    </div>

                                    <div className={`flex items-center gap-2 ${passwordRegex.lowercase.test(password) ? "text-[#053F31]" : "text-gray-400"}`}>
                                        {passwordRegex.lowercase.test(password) ? <Check size={14} /> : <div className="w-3.5 h-3.5 rounded-full border border-gray-300"></div>}
                                        <span>{t.reqLowercase}</span>
                                    </div>

                                    <div className={`flex items-center gap-2 ${passwordRegex.number.test(password) ? "text-[#053F31]" : "text-gray-400"}`}>
                                        {passwordRegex.number.test(password) ? <Check size={14} /> : <div className="w-3.5 h-3.5 rounded-full border border-gray-300"></div>}
                                        <span>{t.reqNumber}</span>
                                    </div>

                                    <div className={`flex items-center gap-2 ${passwordRegex.specialChar.test(password) ? "text-[#053F31]" : "text-gray-400"}`}>
                                        {passwordRegex.specialChar.test(password) ? <Check size={14} /> : <div className="w-3.5 h-3.5 rounded-full border border-gray-300"></div>}
                                        <span>{t.reqSpecialChar}</span>
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="mb-[21px]">
                            <InputItem
                                id="confirm-new-password"
                                label={t.confirmPasswordLabel}
                                type="password"
                                placeholder={t.confirmPasswordPlaceholder}
                                required
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                                isPassword={true}
                            />
                        </div>

                        <div className="pt-[20px]">
                            <button
                                type="submit"
                                disabled={isSubmitting}
                                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"
                            >
                                {isSubmitting ? t.saving : t.submitButton}
                                <IconArrowRight />
                            </button>
                        </div>

                        <p className="text-center text-[18px] text-gray-600 font-light pt-[10px]">
                            {t.rememberPassword}{" "}
                            <Link
                                href="/login"
                                className="text-[#053F31] font-medium hover:underline transition-colors"
                            >
                                {t.signIn}
                            </Link>
                        </p>
                    </form>
                </div>
            </div>
        </section>
    );
}

export default function ResetPasswordPage(props: ResetPasswordPageProps) {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <ResetPasswordForm {...props} />
        </Suspense>
    );
}
