'use client';
import axios from "axios"
import * as z from 'zod';
import Image from "next/image";

import { useState, useEffect } from "react";
import { useForm } from 'react-hook-form';
import { useTranslations, useLocale } from 'next-intl';
import { useMutation } from '@tanstack/react-query';
import { Link, useRouter } from '@/i18n/navigation';
import { useSearchParams } from 'next/navigation';
import { CONTROL_USER_DATA } from "@/utils/data/control-user-data";
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { BASE_URL } from "@/utils/url";
import { toast } from '@/hooks/use-toast';

import { Loader, Lock, User2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { TextField } from '@/components/form/text-field';
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";

const loginSchema = z.object({
    username: z.string().min(4, 'Username is required'),
    password: z.string().min(8, 'Password is required'),
});
type LoginFormData = z.infer<typeof loginSchema>;

export function LoginForm() {
    const t = useTranslations();
    const locale = useLocale();
    const router = useRouter();
    const searchParams = useSearchParams();


    useEffect(() => {
        const token = USER_TOKEN_CL();
        if (token) {
            router.push('/');
        }
    }, [router]);

    const {
        register,
        formState: { errors },
        getValues
    } = useForm<LoginFormData>({
        defaultValues: {
            username: '',
            password: '',
        },
    });

    const loginFunc = useMutation({
        mutationKey: ['login'],
        mutationFn: async (data: LoginFormData) => {
            const response = await axios.post(`${BASE_URL}/login`, {
                username: data.username,
                password: data.password
            });

            if (response.status !== 200) throw new Error(response.data);

            return response.data;
        },
        onSuccess: (response) => {
            const token = response?.token;
            CONTROL_USER_DATA({ token, action: "save" });

            toast({
                variant: "success",
                title: t('custom.done'),
            });

            // Always go to email-verify first; it will redirect to dashboard after verification
            const redirect = searchParams.get('redirect');
            router.push(`/email-verify${redirect ? `?redirect=${redirect}` : ''}`);
        },
        onError: () => {
            toast({
                variant: "destructive",
                title: t('custom.failed'),
                description: t('custom.try-again')
            })
        }
    })

    return (
        <div className="w-full px-6">
            <div className="space-y-4">
                <div className="w-40">
                    <Link href={'/'}>
                        <Image
                            src={locale === 'ar' ? '/images/logo.png' : '/images/logo-en.png'}
                            alt="mwaheb-logo"
                            className="w-full h-20 object-contain"
                            width={200}
                            height={200}
                            priority
                        />
                    </Link>
                </div>
                <div className="text-start mb-8">
                    <p className="text-baby-blue w-64 font-bold text-xl">
                        {t("login.desc")}
                    </p>
                </div>
            </div>
            <div className="flex-1 py-10 flex flex-col justify-center mx-auto w-full">
                <form className="space-y-6 text-black"
                    onKeyDown={(e) => {

                        if (e.key === "Enter") {
                            e.stopPropagation();
                            e.preventDefault();
                            loginFunc.mutate(getValues());
                        }
                    }}

                    onSubmit={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        loginFunc.mutate(getValues());
                    }}
                >
                    {/* username */}
                    <TextField
                        label={t("form.username")}
                        placeholder={t('placeholder.username')}
                        labelIcon={<User2 className='size-3.5' />}
                        // type="email"

                        register={register}
                        registerFor='username'
                        errors={errors}
                        required
                    />

                    {/* password */}
                    <TextField
                        label={t("form.password")}
                        placeholder={t('placeholder.password')}
                        labelIcon={<Lock className='size-3.5' />}
                        type='password'

                        register={register}
                        registerFor='password'
                        errors={errors}
                        toggleSeePassword
                        required
                    />



                    <Button
                        type="submit"
                        disabled={loginFunc.isPending}
                        className='w-full bg-primary-tw-400 text-white'
                    >
                        {loginFunc.isPending ? (
                            <>
                                <Loader className="w-5 h-5 animate-spin" />
                                {t('custom.submitting')}
                            </>
                        ) : (
                            t("custom.submit")
                        )}
                    </Button>

                    {/* Register Link */}
                    <div className="text-center text-gray-600 text-sm">
                        {t("form.no-acc")}{' '}
                        <Link
                            href="/register"
                            className="text-purple-800 font-semibold !underline underline-offset-1"
                        >
                            {t("custom.register now")}
                        </Link>
                    </div>

                    {/* Forgot Password Link */}
                    <div className="text-center">
                        <Link
                            href="/reset-password"
                            className="text-primary-tw-400 hover:underline text-sm"
                        >
                            {t("custom.forgot-password")}
                        </Link>
                    </div>
                </form>
            </div>
        </div>
    );
};