// app/beach/BeachRegistrationForm.tsx

'use client';

import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';
import React, { useRef, useActionState, useEffect, useState } from 'react';
import { FaUser, FaEnvelope, FaPhone, FaUsers, FaTrophy, FaCheckCircle, FaExclamationTriangle } from "react-icons/fa";
import { submitRegistration } from './actions';
import { SiteConfig } from '../lib/config';

export default function BeachRegistrationForm({ config, turnstileSiteKey }: { config: SiteConfig, turnstileSiteKey: string }) {
    const [state, formAction, isPending] = useActionState(submitRegistration, null);
    const formRef = useRef<HTMLFormElement>(null);
    const turnstileRef = useRef<TurnstileInstance>(null);
    const [token, setToken] = useState<string | null>(null);

    const classesData = Array.isArray(config.beachPage?.classes)
        ? config.beachPage.classes
        : [
            { name: 'Grön', color: '#16a34a', desc: 'Nybörjare' },
            { name: 'Blå', color: '#2563eb', desc: 'Spelat lite' },
            { name: 'Svart', color: '#111827', desc: 'Spelat mycket' }
        ];

    useEffect(() => {
        if (state?.success) {
            formRef.current?.reset();
            turnstileRef.current?.reset();
            setToken(null);
        } else if (state?.success === false) {
            turnstileRef.current?.reset();
            setToken(null);
        }
    }, [state]);

    return (
        <section className="w-full flex justify-center px-4 mb-20">
            <div className="bg-[#fdf5e6] p-8 md:p-12 rounded-[40px] w-full max-w-3xl shadow-2xl border-b-8 border-[#e6be8a]">

                <div className="text-center mb-10 px-2">
                    <h2 className="font-beachday text-[clamp(35px,8vw,60px)] text-[#39979f] uppercase tracking-wide leading-[0.9] wrap-break-word w-full max-w-full">
                        Anmälnings&shy;formulär
                    </h2>
                    <div className="h-1.5 w-24 bg-[#fdb84b] mx-auto mt-4 rounded-full" />
                </div>

                <form action={formAction} ref={formRef} className="space-y-6">

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <InputGroup
                            icon={<FaUser />}
                            name="name"
                            placeholder="Ditt namn"
                            required
                            minLength={2}
                            defaultValue={state?.values?.name || ''}
                        />
                        <InputGroup
                            icon={<FaEnvelope />}
                            name="email"
                            type="email"
                            placeholder="namn@domän.com"
                            required
                            defaultValue={state?.values?.email || ''}
                        />
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <InputGroup
                            icon={<FaPhone />}
                            name="tel"
                            type="tel"
                            placeholder="Telefonnummer"
                            required
                            pattern="[0-9+ \-]{8,}"
                            defaultValue={state?.values?.tel || ''}
                        />
                        <InputGroup
                            icon={<FaTrophy />}
                            name="team"
                            placeholder="Lagnamn"
                            required
                            minLength={2}
                            defaultValue={state?.values?.team || ''}
                        />
                    </div>

                    <div className="flex flex-col md:flex-row gap-8 bg-white/50 p-6 rounded-3xl border border-[#e6be8a]/30 shadow-inner">
                        <div className="flex-1">
                            <label className="flex items-center gap-2 font-bold text-[#39979f] mb-3 text-sm uppercase">
                                <FaUsers /> Antal spelare
                            </label>
                            <input
                                type="text"
                                inputMode="numeric"
                                name="count"
                                required
                                pattern="^([2-9]|10)$"
                                title="Ange ett antal mellan 2 och 10"
                                onInput={(e) => {
                                    e.currentTarget.value = e.currentTarget.value.replace(/\D/g, '');
                                }}
                                className="w-full p-4 rounded-xl border-2 border-transparent bg-white focus:border-[#39979f] outline-none transition-all shadow-inner"
                                placeholder="Minst 2"
                                defaultValue={state?.values?.count || ''}
                            />
                        </div>

                        <div className="flex-2">
                            <label className="font-bold text-[#39979f] mb-3 block text-sm uppercase">Välj klass</label>
                            <div className={`grid grid-cols-2 md:grid-cols-${Math.min(classesData.length, 3)} gap-3`}>
                                {classesData.map((c: { name: string; color: string; desc?: string }) => (
                                    <LevelButton
                                        key={c.name}
                                        value={c.name}
                                        label={c.name}
                                        desc={c.desc}
                                        color={c.color}
                                        defaultChecked={state?.values?.level === c.name}
                                    />
                                ))}
                            </div>
                        </div>
                    </div>

                    <textarea
                        name="message"
                        placeholder="Övrig info till oss..."
                        className="w-full h-32 p-4 rounded-2xl border-2 border-transparent bg-white focus:border-[#39979f] outline-none resize-none shadow-inner"
                        defaultValue={state?.values?.message || ''}
                    />

                    <input type="text" name="website" className="hidden" tabIndex={-1} />

                    <div className="flex justify-center py-2">
                        <Turnstile
                            ref={turnstileRef}
                            siteKey={turnstileSiteKey}
                            onSuccess={(token) => setToken(token)}
                            onExpire={() => setToken(null)}
                            options={{ theme: 'light' }}
                        />
                    </div>

                    {state && (
                        <div className={`flex items-center gap-3 p-5 rounded-2xl font-bold transition-all ${state.success ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                            {state.success ? <FaCheckCircle size={24} className="shrink-0" /> : <FaExclamationTriangle size={24} className="shrink-0" />}
                            {state.message}
                        </div>
                    )}

                    <button
                        type="submit"
                        disabled={isPending || !token}
                        className="w-full py-5 bg-[#39979f] text-white rounded-2xl font-bold text-xl uppercase tracking-wide shadow-xl hover:bg-[#fdb84b] hover:text-[#39979f] transition-all active:scale-[0.98] disabled:bg-gray-300 disabled:text-gray-500"
                    >
                        {isPending ? 'Skickar...' : 'Skicka anmälan'}
                    </button>
                </form>
            </div>
        </section>
    );
}

// Uppdaterad med defaultChecked support
function LevelButton({ value, label, desc, color, defaultChecked }: { value: string; label: string; desc?: string; color: string; defaultChecked?: boolean }) {
    return (
        <label className="cursor-pointer flex-1 relative" style={{ '--class-color': color } as React.CSSProperties}>
            <input
                type="radio"
                name="level"
                value={value}
                required
                className="peer sr-only"
                defaultChecked={defaultChecked}
            />

            <div className="text-center p-3 rounded-xl border-2 border-white bg-white text-gray-400 font-black transition-all peer-checked:text-white peer-checked:bg-(--class-color) peer-checked:border-(--class-color) peer-checked:scale-[1.03] shadow-sm h-full flex flex-col justify-center items-center">
                <span className="uppercase tracking-tighter">{label}</span>
                {desc && <span className="text-[10px] font-medium opacity-80 mt-1 uppercase tracking-widest">{desc.replace(/[()]/g, '')}</span>}
            </div>
        </label>
    );
}

function InputGroup({ icon, ...props }: React.InputHTMLAttributes<HTMLInputElement> & { icon: React.ReactNode }) {
    return (
        <div className="relative group">
            <div className="absolute left-4 top-1/2 -translate-y-1/2 text-[#e6be8a] group-focus-within:text-[#39979f] transition-colors">
                {icon}
            </div>
            <input
                {...props}
                className="w-full pl-12 pr-4 py-4 rounded-xl border-2 border-transparent bg-white focus:border-[#39979f] outline-none transition-all shadow-inner placeholder:text-gray-400"
            />
        </div>
    );
}