"use client";

import { FormEvent, useEffect, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';

import IvoryLogo from '@/assets/logo-footer.png';
import LoginBG from '@/assets/used-images/login.png';

import { Bomb, Eye, EyeClosed, Loader } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

import { useTranslation } from 'react-i18next';
import { useMutation } from '@tanstack/react-query';
import { useLanguage } from '@/store/language-context';
import { useToast } from '@/hooks/use-toast';
import LanguageSwitcher from '@/views/home/components/language-switcher';

export default function ResetPassword() {
    const [data, setData] = useState({
        password: '',
        submitPassword: ''
    });

    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);

    const { URL } = useLanguage();
    const { t } = useTranslation();
    const { toast } = useToast();

    const naviagte = useNavigate();
    const location = useLocation();
    const { contact, contact_type } = location.state || {};

    // Immediate redirect if no valid state
    // useEffect(() => {
    //     if (!contact || !contact_type) {
    //         naviagte('/forget-password');
    //         return;
    //     }
    // }, [contact, contact_type, naviagte]);

    const updatePass = useMutation({
        mutationKey: ['reset-password'],
        mutationFn: async (formData: { password: string; submitPassword: string }) => {
            if (formData.password !== formData.submitPassword) {
                throw new Error(t('register.pass-err'));
            }

            const response = await axios.post(`${URL}/reset-password`, {
                contact: contact || 'hjjh',
                contact_type: contact_type || 'email',
                password: formData.password,
                password_confirmation: formData.submitPassword,
            });

            return response.data;
        },
        onSuccess: () => {
            toast({
                variant: 'success',
                title: `🎉 ${t('register.done-pass')}`,
                description: t('custom.done-desc')
            });
            naviagte('/profile');
        },
        onError: (error: any) => {
            toast({
                variant: "destructive",
                title: (
                    <div className='flex items-center gap-2'>
                        <Bomb size={19} />
                        <p>
                            ${t('custom.failed')}
                        </p>
                    </div>
                ),
                description: error.message || t('custom.err')
            });
        }
    });

    const submitFnc = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        // Password mismatch validation can be done here too
        if (data.password !== data.submitPassword) {
            toast({
                variant: "warning",
                title: t('register.pass-err'),
            });
            return;
        }

        updatePass.mutate({
            password: data.password,
            submitPassword: data.submitPassword
        });
    };



    return (
        <div className='grid grid lg:grid-cols-[58%_38%]  max-lg:grid-cols-1 max-lg:flex-col-reverse max-lg:gap-4  overflow-hidden'>
  <section className='relative w-full lg:min-h-dvh '>
                <div className=' bg-gradient-to-t from-[#6a2f38] to-[#6a2f38] opacity-90 absolute w-full h-full max-lg:rounded-b-[65px]'></div>
                <img src={LoginBG} alt="" className='max-lg:rounded-b-[65px] w-full h-full object-cover' />
                <Link to={'/'}>
                    <img src={IvoryLogo} alt={t("ivory")} className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2' />
                </Link>
            </section>
            <section className='flex flex-col justify-center items-center lg:minh-dvh w-full relative layout gap-4 !pl-5 !pr-5'>
                <li  className='grid gap-2 lg:absolute lg:top-20 lg:-end-0 z-[10000] max-lg:w-full'>
                <LanguageSwitcher/>
                </li>
                <section className='grid place-items-center w-full'>

                    <div className='text-center my-8'>
                        <p className='text-3xl text-secondary-tw'>
                            {t('hello')}
                        </p>
                        <h1 className='text-2xl text-primary-tw'>
                            {t('routes.reset-password')}
                        </h1>
                    </div>

                    <form className='w-full space-y-4' onSubmit={(e) => submitFnc(e)}>
                        <div className='space-y-1 w-full relative'>
                            <Label htmlFor='password' className='text-gray-500 text-base'>
                                {t('contact.new-pass')}
                            </Label>
                            <Input
                                id='password'
                                type={showPassword ? 'text' : 'password'}
                                placeholder={t('footer.enter-new-pass')}
                                value={data.password ?? ''}
                                onChange={(e) => setData(prev => ({ ...prev, password: e.target.value }))}
                                className='w-full focus:ring-secondary-tw text-common-text'
                            />
                            <Button
                                type='button'
                                className='absolute top-6 end-0 bg-gray-200 transition-all'
                                variant='outline'
                                onClick={() => setShowPassword((prev: boolean) => !prev)}>
                                {showPassword ? <Eye /> : <EyeClosed />}
                            </Button>
                        </div>

                        <div className='space-y-1 w-full relative'>
                            <Label htmlFor='submit-password' className='text-gray-500 text-base'>
                                {t('custom.confirm')}  {t('contact.new-pass')}
                            </Label>
                            <Input
                                id='submit-password'
                                type={showConfirmPassword ? 'text' : 'password'}
                                placeholder={`${t('footer.confirm-new-pass')}`}
                                value={data.submitPassword ?? ''}
                                onChange={(e) => setData(prev => ({ ...prev, submitPassword: e.target.value }))}
                                className='w-full focus:ring-secondary-tw text-common-text'
                            />
                            <Button
                                type='button'
                                className='absolute top-6 end-0 bg-gray-200 transition-all'
                                variant='outline'
                                onClick={() => setShowConfirmPassword((prev: boolean) => !prev)}>
                                {showConfirmPassword ? <Eye /> : <EyeClosed />}
                            </Button>
                        </div>


                        <Button type='submit' variant='outline'
                            className='w-full bg-primary-tw text-white disabled:!cursor-not-allowed'
                            disabled={updatePass.isPending}
                        >
                            {updatePass.isPending ?
                                <>
                                    <Loader className='animate-spin' />
                                    {t('custom.updating')}
                                </>
                                :
                                t('custom.update')}
                        </Button>
                    </form>

                </section>
            </section>

          
        </div>
    );
};