import { CheckCircle2, ExternalLink, Loader2, Star } from 'lucide-react';
import { useRef, useState } from 'react';
import { type Brand, postForm, PublicShell, publicInputStyle, Turnstile } from '@/components/public/PublicShell';

type Props = {
    brand: Brand;
    review: { name: string | null; rating: number | null; comment: string | null; role: string | null; done: boolean; quote_title: string | null };
    action: string; google: string | null; turnstileSiteKey: string | null;
};

const WORDS = ['', 'Poor', 'Fair', 'Good', 'Great', 'Excellent'];

/** The client's review form (from the review request email): 1–5 stars, a comment, then a nudge to Google for 4–5 stars. */
export default function ReviewForm({ brand, review, action, google, turnstileSiteKey }: Props) {
    const ref = useRef<HTMLFormElement>(null);
    const [rating, setRating] = useState(review.rating ?? 0);
    const [hover, setHover] = useState(0);
    const [busy, setBusy] = useState(false);
    const [errors, setErrors] = useState<Record<string, string>>({});
    const [done, setDone] = useState<{ google: string | null } | null>(review.done ? { google: (review.rating ?? 0) >= 4 ? google : null } : null);

    const submit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!ref.current) return;
        if (!rating) { setErrors({ rating: 'Choose a star rating.' }); return; }
        setBusy(true); setErrors({});
        const fd = new FormData(ref.current);
        fd.set('rating', String(rating));
        const r = await postForm(action, fd);
        setBusy(false);
        if (r.ok) setDone({ google: r.data?.google ?? null });
        else setErrors(r.errors);
    };

    return (
        <PublicShell brand={brand} title="Leave a review">
            {({ p, hf }) => {
                const input = 'mt-1 block w-full rounded-lg border px-3 py-2.5 text-[15px] outline-none focus:ring-2';
                if (done) {
                    return (
                        <div className="rounded-2xl p-8 text-center" style={{ background: p.bg, border: `1px solid ${p.cardLine}` }} data-testid="review-thanks" role="status">
                            <CheckCircle2 className="mx-auto h-10 w-10" style={{ color: p.accent }} aria-hidden />
                            <h1 className="mt-3 text-xl font-semibold" style={hf}>Thanks for your review</h1>
                            <p className="mt-2 text-[15px]" style={{ color: p.muted }}>We really appreciate you taking the time.</p>
                            {done.google && (
                                <div className="mt-6 rounded-xl p-5" style={{ background: p.tint }} data-testid="google-prompt">
                                    <p className="text-[15px] font-medium">Would you share it on Google too?</p>
                                    <p className="mt-1 text-sm" style={{ color: p.muted }}>It helps other people find {brand.name}. You can paste the same words.</p>
                                    <a href={done.google} target="_blank" rel="noopener" className="mt-4 inline-flex h-11 items-center gap-2 rounded-lg px-5 text-[15px] font-semibold"
                                        style={{ background: p.button, color: p.onButton }}>Post on Google <ExternalLink className="h-4 w-4" /></a>
                                </div>
                            )}
                        </div>
                    );
                }
                const shown = hover || rating;
                return (
                    <form ref={ref} onSubmit={submit} className="rounded-2xl p-6 sm:p-8" style={{ background: p.bg, border: `1px solid ${p.cardLine}` }} data-testid="review-form">
                        <h1 className="text-2xl font-semibold leading-tight" style={hf}>How did we do{review.name ? `, ${review.name.split(' ')[0]}` : ''}?</h1>
                        {review.quote_title && <p className="mt-2 text-[15px]" style={{ color: p.muted }}>For: {review.quote_title}</p>}
                        <fieldset className="mt-6">
                            <legend className="text-sm font-medium">Your rating</legend>
                            <div className="mt-2 flex items-center gap-1" onMouseLeave={() => setHover(0)} role="radiogroup" aria-label="Star rating">
                                {[1, 2, 3, 4, 5].map((n) => (
                                    <button key={n} type="button" role="radio" aria-checked={rating === n} aria-label={`${n} star${n > 1 ? 's' : ''}`}
                                        onClick={() => setRating(n)} onMouseEnter={() => setHover(n)} className="rounded p-1 outline-none focus-visible:ring-2" data-testid={`star-${n}`}>
                                        <Star className="h-9 w-9" strokeWidth={1.5} style={{ color: n <= shown ? p.accent : p.cardLine, fill: n <= shown ? p.accent : 'transparent' }} />
                                    </button>
                                ))}
                                <span className="ml-2 text-sm" style={{ color: p.muted }}>{WORDS[shown]}</span>
                            </div>
                            {errors.rating && <p className="mt-1 text-sm text-red-700" role="alert">{errors.rating}</p>}
                        </fieldset>
                        <div className="mt-5 grid gap-4">
                            <div>
                                <label htmlFor="rv-comment" className="text-sm font-medium">Tell us more <span className="font-normal" style={{ color: p.muted }}>(optional)</span></label>
                                <textarea id="rv-comment" name="comment" rows={5} defaultValue={review.comment ?? ''} className={input} style={publicInputStyle(p)} />
                            </div>
                            <div className="grid gap-4 sm:grid-cols-2">
                                <div>
                                    <label htmlFor="rv-name" className="text-sm font-medium">Name to show</label>
                                    <input id="rv-name" name="name" required defaultValue={review.name ?? ''} className={input} style={publicInputStyle(p)} />
                                    {errors.name && <p className="mt-1 text-sm text-red-700">{errors.name}</p>}
                                </div>
                                <div>
                                    <label htmlFor="rv-role" className="text-sm font-medium">Role / company <span className="font-normal" style={{ color: p.muted }}>(optional)</span></label>
                                    <input id="rv-role" name="role" defaultValue={review.role ?? ''} className={input} style={publicInputStyle(p)} />
                                </div>
                            </div>
                            <p className="text-xs" style={{ color: p.muted }}>{brand.name} may show your review, name and role on its website and proposals.</p>
                            <Turnstile siteKey={turnstileSiteKey} />
                            {(errors.captcha || errors.form) && <p className="text-sm text-red-700" role="alert">{errors.captcha ?? errors.form}</p>}
                            <button type="submit" disabled={busy} className="inline-flex h-12 items-center justify-center gap-2 rounded-lg px-6 text-[15px] font-semibold disabled:opacity-60"
                                style={{ background: p.button, color: p.onButton }} data-testid="review-submit">
                                {busy && <Loader2 className="h-4 w-4 animate-spin" />} Send review
                            </button>
                        </div>
                    </form>
                );
            }}
        </PublicShell>
    );
}
