import { InputField } from '@/components/ui/inputfield';
import { Button } from '@/components/ui';
import { Separator } from '@/components/ui';
import { useAuthContext } from '@/lib/contexts/Auth.context';
import LogoutButton from './LogoutButton';
import { changeEmail } from '@/lib/api/ChangeEmail';
import { useState } from 'react';
import { ChangePasswordField } from './ChangePassword';
import { SetPasswordField } from './SetPasswordField';
export default function SecurityPage() {
    const { user } = useAuthContext();

    if (!user) return;

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);

    if (!user) return null;

    const hasGoogle = !!user.google_id;
    const hasPassword = user.has_password;
    const showSetPassword = hasGoogle && !hasPassword;

    const handleChangeEmail = async () => {
        if (!email || !password) return;

        setLoading(true);

        const res = await changeEmail(email, password);

        setLoading(false);

        if (res.error) {
            console.error(res.error.general);
            return;
        }

        setEmail('');
        setPassword('');
    };
    return (
        <>
            <div className="flex flex-col flex-start gap-[40px] w-[900px] h-[816px]">
                <div className="flex flex-col gap-[20px] w-[900px] ">
                    {showSetPassword && <SetPasswordField />}

                    <div className="flex flex-col gap-[20px] w-[310px]">
                        <p className="text-light-violet font-medium">
                            СМЕНА ПОЧТЫ
                        </p>

                        <div className="flex flex-col gap-[10px]">
                            <InputField
                                placeholder="Новая почта"
                                type="email"
                                name="email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                            />

                            <InputField
                                isPassword
                                placeholder="Введите пароль"
                                type="password"
                                name="password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>

                        <Button onClick={handleChangeEmail}>Сменить</Button>
                    </div>
                    <Separator className="bg-violet/30 h-[1px] w-[900px]" />
                    {hasPassword && <ChangePasswordField />}
                    <LogoutButton />
                </div>
            </div>
        </>
    );
}
