import PasswordInput from '@/Components/auth/PasswordInput';
import PasswordStrength from '@/Components/auth/PasswordStrength';
import Section from '@/Components/shared/Section';
import { Button } from '@/Components/ui/button';
import { Field } from '@/Components/ui/field';
import { useForm } from '@inertiajs/react';
import { FormEventHandler, useRef } from 'react';

export default function UpdatePasswordForm() {
    const current = useRef<HTMLInputElement>(null);
    const next = useRef<HTMLInputElement>(null);
    const { data, setData, errors, put, reset, processing, recentlySuccessful } = useForm({ current_password: '', password: '', password_confirmation: '' });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        put(route('password.update'), {
            preserveScroll: true,
            onSuccess: () => reset(),
            onError: (errs) => {
                if (errs.password) { reset('password', 'password_confirmation'); next.current?.focus(); }
                if (errs.current_password) { reset('current_password'); current.current?.focus(); }
            },
        });
    };

    return (
        <Section title="Password" description="Use a long, unique password.">
            <form onSubmit={submit} className="max-w-md space-y-4">
                <Field label="Current password" htmlFor="current_password" error={errors.current_password}>
                    <PasswordInput id="current_password" ref={current as never} autoComplete="current-password" value={data.current_password} onChange={(e) => setData('current_password', e.target.value)} />
                </Field>
                <Field label="New password" htmlFor="password" error={errors.password}>
                    <PasswordInput id="password" ref={next as never} autoComplete="new-password" value={data.password} onChange={(e) => setData('password', e.target.value)} />
                    <PasswordStrength value={data.password} />
                </Field>
                <Field label="Confirm password" htmlFor="password_confirmation" error={errors.password_confirmation}>
                    <PasswordInput id="password_confirmation" autoComplete="new-password" value={data.password_confirmation} onChange={(e) => setData('password_confirmation', e.target.value)} />
                </Field>
                <div className="flex items-center gap-3">
                    <Button type="submit" loading={processing}>Update password</Button>
                    {recentlySuccessful && <span role="status" className="text-sm text-muted-foreground">Saved.</span>}
                </div>
            </form>
        </Section>
    );
}
