import { Head, useForm } from '@inertiajs/react';
import { QRCodeSVG } from 'qrcode.react';
import { FormEventHandler } from 'react';
import GuestLayout from '@/Layouts/GuestLayout';

interface Props {
    alreadyEnabled: boolean;
    qrCodeUrl?: string;
    secret?: string;
}

export default function TwoFactorSetup({ alreadyEnabled, qrCodeUrl, secret }: Props) {
    const { data, setData, post, processing, errors } = useForm({ code: '' });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('two-factor.confirm'));
    };

    if (alreadyEnabled) {
        return (
            <GuestLayout>
                <Head title="Two-factor authentication" />
                <p className="text-gray-300">Two-factor authentication is already enabled on your account.</p>
            </GuestLayout>
        );
    }

    return (
        <GuestLayout>
            <Head title="Set up two-factor authentication" />

            <h1 className="mb-4 text-lg font-semibold text-white">Set up two-factor authentication</h1>
            <p className="mb-4 text-sm text-gray-400">
                Scan this QR code with Google Authenticator, Authy, or a similar app, then enter the 6-digit code it
                generates.
            </p>

            {qrCodeUrl && (
                // Rendered entirely client-side (no network request) so the
                // otpauth:// URI — which embeds the raw TOTP secret — is
                // never sent to a third-party image service.
                <div className="mb-4 flex justify-center rounded-md bg-white p-4">
                    <QRCodeSVG value={qrCodeUrl} size={200} />
                </div>
            )}

            {secret && (
                <p className="mb-6 break-all rounded-md bg-gray-800 p-3 text-center font-mono text-xs text-gray-300">
                    {secret}
                </p>
            )}

            <form onSubmit={submit} className="space-y-4">
                <input
                    type="text"
                    inputMode="numeric"
                    maxLength={6}
                    value={data.code}
                    onChange={(e) => setData('code', e.target.value)}
                    className="w-full rounded-md border-gray-700 bg-gray-800 text-center text-2xl tracking-[0.5em] text-white"
                />
                {errors.code && <p className="text-sm text-red-400">{errors.code}</p>}

                <button
                    type="submit"
                    disabled={processing}
                    className="w-full rounded-md bg-brand-600 px-4 py-2.5 font-medium text-white hover:bg-brand-700 disabled:opacity-50"
                >
                    Enable two-factor authentication
                </button>
            </form>
        </GuestLayout>
    );
}
