import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { FormField } from "@/components/Fields/form-field";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRequestMagicLink } from "@/hook/queries/authentication";
import { Loader2 } from "lucide-react";
import { LoginFormValues, loginSchema } from "./schema";
import TermloansLogo from "@/assets/Termloans-logo.svg";
import Logo from "@/assets/Logo.svg";
import GoogleLogo from "@/assets/Login/Google-logo.svg";
import { AxiosError } from "axios";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { handleApiError, NewAPIErrorResponse } from "@/utils/handle_api_error";
import { useAuthStore } from "@/store/useAuthStore";
import { googleCallbackUri, googleClientId } from "@/config";
import LazySliderDesktop from "@/components/LazySliderDesktop";
import { useTranslation } from "react-i18next";
import SEO from "@/components/SEO";

const googleSignInUrl = `https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${googleCallbackUri}&prompt=consent&response_type=code&client_id=${googleClientId}&scope=openid%20email%20profile&access_type=offline`

export default function Login() {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const {
        register,
        handleSubmit,
        formState: { errors, isValid },
    } = useForm<LoginFormValues>({
        resolver: zodResolver(loginSchema),
        mode: "onChange",
    });

    const { mutate: requestMagicLink, isPending } = useRequestMagicLink();
    const { clearStorageCompletely } = useAuthStore();

    const onSubmit = (data: LoginFormValues) => {
        clearStorageCompletely();
        requestMagicLink(data.email, {
            onSuccess: (response) => {
                toast.success("Verification code sent to your phone via SMS!");
                navigate("/verify-magic-code", {
                    state: {
                        email: data.email,
                        phoneLastDigits: response.data.phone_last_digits
                    },
                    replace: true
                });
            },
            onError: (error) => {
                const axiosError = error as AxiosError<NewAPIErrorResponse>;
                handleApiError(axiosError);
            }
        });
    };

    return (
        <>
            <SEO
                title="Login"
                description="Secure login to access your TermLoans business financing account. Connect your banking and manage your loan applications efficiently."
                keywords="login, TermLoans, business financing, secure access, business loans"
                canonical="/login"
            />
            <div className="lg:flex lg:bg-[#F2F4F7] lg:p-4 gap-6">
                <div
                    className="flex flex-col items-center gap-8 py-8 px-6 w-full lg:w-[70%] bg-white lg:rounded-2xl"
                >
                    <div className="gap-8 lg:gap-22 flex flex-col items-start lg:items-center relative self-stretch w-full">
                        <header className="flex items-center justify-between relative self-stretch w-full">
                            <div className="flex items-center justify-center gap-3">
                                <img
                                    className="block lg:hidden w-[41.29px] h-[34px]"
                                    alt="Logo termloans"
                                    src={TermloansLogo}
                                />
                                <img src={Logo} className="hidden lg:block" alt="" />
                            </div>

                            <div className="flex flex-col items-end gap-4">
                                <div className="flex items-center gap-4 lg:gap-6">
                                    <a
                                        href="mailto:support@termloans.com"
                                        className="inline-flex items-center justify-center gap-1 text-[#0a243d] font-label-small hover:text-[#70c039] hover:underline transition-colors"
                                    >
                                        {t('auth.contactSupport')}
                                    </a>
                                    <div className="w-px h-5 bg-[#E2E4E9]" />
                                </div>
                                <div className="block lg:hidden h-0.5 w-6 bg-[#70C039]" />
                            </div>
                        </header>

                        <div className="flex flex-col items-start lg:items-center gap-8 w-full lg:w-[410px]">
                            <section className="flex flex-col items-start lg:items-center gap-3 w-full">
                                <h1 className="text-2xl font-semibold text-[#0a243d] w-full lg:text-center">
                                    {t('auth.welcomeBack')}
                                </h1>
                                <p className="text-base text-[#667085] w-full lg:text-center">
                                    {t('auth.welcomeSubtext')}
                                </p>
                            </section>

                            <div className="flex flex-col gap-4 w-full">
                                <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-8 w-full">
                                    <div className="flex flex-col gap-6 self-stretch w-full">
                                        <FormField
                                            id="email"
                                            label={t('auth.emailAddress')}
                                            type="email"
                                            isEmail
                                            placeholder={t('auth.emailPlaceholder')}
                                            error={errors.email?.message}
                                            {...register("email")}
                                        />

                                        <p className="text-sm text-[#667085]">
                                            We'll send a verification code to your phone via SMS
                                        </p>
                                    </div>

                                    <div className="flex flex-col gap-6 self-stretch w-full">
                                        <Button
                                            type="submit"
                                            className="w-full bg-[#70c039] hover:bg-[#65b033] active:bg-[#65b033] text-[#fcfcfd] font-text-14-medium rounded-lg p-3.5 h-auto disabled:opacity-50 disabled:cursor-not-allowed"
                                            disabled={!isValid || isPending}
                                        >
                                            {isPending ? (
                                                <Loader2 className="animate-spin" />
                                            ) : (
                                                "Send Code via SMS"
                                            )}
                                        </Button>

                                        <div className="flex items-center justify-center gap-2 self-stretch">
                                            <span className="font-text-14-regular text-[#667085]">
                                                {t('auth.dontHaveAccount')}
                                            </span>
                                            <button
                                                type="button"
                                                className="font-label-small text-[#0a243d] hover:text-[#70c039] hover:underline transition-colors"
                                                onClick={() => navigate("/register")}
                                                aria-label={t('auth.createAccount')}
                                            >
                                                {t('auth.createAccount')}
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <div className="flex flex-col items-start gap-6 self-stretch w-full">
                                <div className="flex items-center justify-center gap-2.5 self-stretch w-full">
                                    <Separator className="flex-1 bg-[#e2e4e9]" />
                                    <span className="font-text-12-medium text-[#98a2b3] text-center">
                                        {t('auth.or')}
                                    </span>
                                    <Separator className="flex-1 bg-[#e2e4e9]" />
                                </div>

                                <a href={googleSignInUrl} className="w-full">
                                    <Button
                                        type="button"
                                        variant="outline"
                                        className="flex items-center justify-center gap-2 pl-2.5 pr-4 py-2.5 self-stretch w-full bg-white rounded-lg border-[#e2e4e9] shadow-regular-shadow-x-small h-auto hover:bg-gray-50 transition-colors"
                                        aria-label={t('auth.loginWithGoogle')}
                                    >
                                        <img
                                            className="w-5 h-5"
                                            alt="Google logo"
                                            src={GoogleLogo}
                                        />
                                        <span className="font-text-14-medium text-[#0a243d] text-center">
                                            {t('auth.loginWithGoogle')}
                                        </span>
                                    </Button>
                                </a>
                            </div>

                            <footer className="flex gap-2.5 justify-center w-full">
                                <a
                                    href="https://termloans.com/terms"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-[#70c039] font-xs hover:underline active:underline transition-colors"
                                    aria-label={`${t('auth.termsOfUse')} (opens in new tab)`}
                                >
                                    {t('auth.termsOfUse')}
                                </a>
                                <span className="text-[#e2e4e9] font-xs">
                                    |
                                </span>
                                <a
                                    href="https://termloans.com/privacy-policy"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-[#70c039] font-xs hover:underline active:underline transition-colors"
                                    aria-label={`${t('auth.privacyPolicy')} (opens in new tab)`}
                                >
                                    {t('auth.privacyPolicy')}
                                </a>
                            </footer>
                        </div>
                    </div>
                </div>
                <LazySliderDesktop />
            </div>
        </>
    );
};