import { useState } from 'react';
import CaptchaController from '@/actions/App/Http/Controllers/CaptchaController';
import { RefreshIcon } from '@/components/Icons';
import type { CaptchaPayload } from '@/types/binder';

interface InteractiveCaptchaProps {
    initialCaptcha: CaptchaPayload;
    value: string;
    onChange: (value: string) => void;
    error?: string;
}

export default function InteractiveCaptcha({
    initialCaptcha,
    value,
    onChange,
    error,
}: InteractiveCaptchaProps) {
    const [captcha, setCaptcha] = useState<CaptchaPayload>(initialCaptcha);
    const [refreshing, setRefreshing] = useState(false);

    async function refreshCaptcha() {
        setRefreshing(true);
        try {
            const response = await fetch(CaptchaController.url(), {
                headers: { Accept: 'application/json' },
            });
            if (response.ok) {
                const payload = (await response.json()) as CaptchaPayload;
                setCaptcha(payload);
                onChange('');
            }
        } finally {
            setRefreshing(false);
        }
    }

    return (
        <div className="rounded-xl border border-slate-200 bg-slate-50/70 p-3 sm:p-4">
            {/* Honeypot anti-bot field */}
            <div className="hidden" aria-hidden="true">
                <label htmlFor="website_hp">Website</label>
                <input
                    id="website_hp"
                    name="website_hp"
                    type="text"
                    tabIndex={-1}
                    autoComplete="off"
                />
            </div>

            <div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
                <label className="text-xs font-bold text-slate-700 sm:text-sm sm:font-semibold">
                    تأیید امنیتی (کپچا) <span className="text-rose-600">*</span>
                </label>
                <p className="text-[11px] text-slate-500 sm:text-xs">
                    {captcha.prompt}
                </p>
            </div>

            <div className="grid grid-cols-[1fr_auto] items-center gap-2 sm:flex sm:flex-wrap sm:gap-3">
                <img
                    src={captcha.image}
                    alt="کد امنیتی"
                    className="h-10 w-full rounded-lg border border-slate-300 bg-white object-contain sm:h-12 sm:w-44"
                />
                <button
                    type="button"
                    onClick={refreshCaptcha}
                    disabled={refreshing}
                    title="دریافت کد امنیتی جدید"
                    className="inline-flex h-10 shrink-0 items-center justify-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-xs font-medium text-slate-700 transition hover:bg-slate-100 disabled:opacity-50 sm:h-12"
                >
                    <RefreshIcon
                        className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`}
                    />
                    <span>کد جدید</span>
                </button>
                <input
                    type="text"
                    inputMode="numeric"
                    dir="ltr"
                    name="captcha"
                    aria-invalid={Boolean(error)}
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    placeholder="پاسخ عددی..."
                    required
                    className={`col-span-2 h-10 w-full rounded-lg border bg-white px-3.5 text-base text-slate-900 placeholder:text-right placeholder:text-slate-400 focus:border-brand-blue focus:ring-2 focus:ring-blue-500/20 focus:outline-none sm:h-12 sm:min-w-[140px] sm:flex-1 sm:text-sm ${
                        error ? 'border-rose-400' : 'border-slate-300'
                    }`}
                />
            </div>

            {error && (
                <p className="mt-2 text-xs font-medium text-rose-600">
                    {error}
                </p>
            )}
        </div>
    );
}
