import { Turnstile } from '@marsidev/react-turnstile';
import InputError from '@/components/input-error';
import { useCallback, useState } from 'react';

type Props = {
    /** When empty, verification is skipped (local dev without keys). */
    siteKey?: string | null;
    message?: string;
    /** Notified whenever the verification token becomes available or is cleared */
    onTokenChange?: (token: string | null) => void;
};

export default function TurnstileField({
    siteKey,
    message,
    onTokenChange,
}: Props) {
    const [token, setTokenState] = useState<string | null>(null);

    const setBoth = useCallback(
        (value: string | null) => {
            setTokenState(value);
            onTokenChange?.(value);
        },
        [onTokenChange],
    );

    const handleSuccess = useCallback(
        (t: string) => {
            setBoth(t);
        },
        [setBoth],
    );

    const handleExpire = useCallback(() => {
        setBoth(null);
    }, [setBoth]);

    const handleError = useCallback(() => {
        setBoth(null);
    }, [setBoth]);

    if (!siteKey?.trim()) {
        return null;
    }

    return (
        <div className="grid gap-2">
            <input
                type="hidden"
                name="cf-turnstile-response"
                value={token ?? ''}
                readOnly
            />
            <p className="text-center text-xs text-muted-foreground">
                Verificación de seguridad
            </p>
            <div className="flex justify-center [&_iframe]:rounded-md">
                <Turnstile
                    siteKey={siteKey}
                    options={{ theme: 'auto', language: 'es' }}
                    onSuccess={handleSuccess}
                    onExpire={handleExpire}
                    onError={handleError}
                />
            </div>
            <InputError message={message} />
        </div>
    );
}
