// app/beach/BeachRegistrationForm.tsx

'use client';

import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';
import React, { useRef, useState } from 'react';
import { PiCheckCircle, PiWarningCircle } from "react-icons/pi";

interface AlertState {
    show: boolean;
    type: 'success' | 'danger' | '';
    message: string;
}

interface SubmitResponse {
    success: boolean;
    message: string;
    detail?: string;
}

export default function BeachRegistrationForm() {
    const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
    const [wasValidated, setWasValidated] = useState<boolean>(false);
    const [alert, setAlert] = useState<AlertState>({ show: false, type: '', message: '' });

    const formRef = useRef<HTMLFormElement>(null);
    const turnstileRef = useRef<TurnstileInstance>(null);

    const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (e) => {
        e.preventDefault();
        const form = formRef.current;
        if (!form) return;

        setWasValidated(true);
        if (!form.checkValidity()) return;

        setIsSubmitting(true);
        setAlert({ show: false, type: '', message: '' });
        const formData = new FormData(form);

        try {
            const response = await fetch('/api/submit', {
                method: 'POST',
                body: formData,
            });

            if (!response.ok) throw new Error(`Network error: ${response.status}`);

            const result = (await response.json()) as SubmitResponse;
            const message = result.detail ? `${result.message} ${result.detail}` : result.message;

            setAlert({
                show: true,
                type: result.success ? 'success' : 'danger',
                message: message,
            });

            if (result.success) {
                form.reset();
                setWasValidated(false);
                if (turnstileRef.current) turnstileRef.current.reset();
            }
        } catch (error) {
            setAlert({
                show: true,
                type: 'danger',
                message: 'Ett tekniskt fel uppstod. Försök igen senare.',
            });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <section className="w-full flex justify-center px-1.25">
            <div className="bg-black p-5 rounded-[20px] my-7.5 mx-1.25 w-full max-w-180 shadow-2xl">
                <h2 className="font-beachday text-[clamp(1.875rem,5.2vw,50px)] text-white text-center m-[5px_0] uppercase tracking-wide">
                    Anmälningsformulär
                </h2>

                <form
                    ref={formRef}
                    onSubmit={handleSubmit}
                    className={`group/form flex flex-col items-center w-full mt-5 ${wasValidated ? 'was-validated' : ''}`}
                    noValidate
                    autoComplete="off"
                >
                    {/* INPUT FÄLT (Namn, Email, Tel, Lagnamn, Antal) */}
                    {[
                        { name: 'name', type: 'text', placeholder: 'Ditt namn', auto: 'name', error: 'Glöm inte ditt namn!' },
                        { name: 'email', type: 'email', placeholder: 'Email', auto: 'email', error: 'Emailadressen är inte giltig.' },
                        { name: 'tel', type: 'tel', placeholder: 'Telefonnummer', auto: 'tel', error: 'Glöm inte ett telefonnummer!' },
                        { name: 'team', type: 'text', placeholder: 'Lagnamn', auto: 'organization', error: 'Glöm inte ert lagnamn!' },
                    ].map((f) => (
                        <div key={f.name} className="relative w-full mb-3.75">
                            <input
                                type={f.type} name={f.name} placeholder={f.placeholder} required autoComplete={f.auto}
                                className="peer bg-transparent text-white border-0 border-b-[5px] border-white w-full h-12.5 outline-none text-[20px] pl-2.5 rounded-none focus:ring-0 group-[.was-validated]/form:invalid:border-[#e60b20] group-[.was-validated]/form:valid:border-[#07ba4c] transition-colors"
                            />
                            <div className="hidden group-[.was-validated]/form:peer-invalid:block absolute right-2.5 top-2.25"><PiWarningCircle color='#dc3545' size={28} /></div>
                            <div className="hidden group-[.was-validated]/form:peer-valid:block absolute right-2.5 top-2.25"><PiCheckCircle color='#198754' size={28} /></div>
                            <div className="hidden group-[.was-validated]/form:peer-invalid:block text-[#e60b20] text-[14px] pl-2.5 mt-1 text-left w-full">{f.error}</div>
                        </div>
                    ))}

                    <div className="relative w-full mb-3.75">
                        <input type="number" name="count" placeholder="Antal spelare" min="2" required
                            className="peer bg-transparent text-white border-0 border-b-[5px] border-white w-full h-12.5 outline-none text-[20px] pl-2.5 rounded-none focus:ring-0 group-[.was-validated]/form:invalid:border-[#e60b20] group-[.was-validated]/form:valid:border-[#07ba4c] transition-colors" />
                        <div className="hidden group-[.was-validated]/form:peer-invalid:block text-[#e60b20] text-[14px] pl-2.5 mt-1 text-left w-full">Glöm inte ange antal lagmedlemmar!</div>
                    </div>

                    {/* RADIOS */}
                    <div className="w-full mt-2.5 text-left group/radios">
                        {[
                            { id: 'level-gron', val: 'Grön', label: 'Grön', color: 'text-green-700', accent: 'accent-green-600', desc: '(Nybörjare)' },
                            { id: 'level-bla', val: 'Blå', label: 'Blå', color: 'text-[#0f65bf]', accent: 'accent-[#0f65bf]', desc: '(Spelat lite)' },
                            { id: 'level-svart', val: 'Svart', label: 'Svart', color: 'text-black', accent: 'accent-black', desc: '(Spelat mycket)' },
                        ].map((l) => (
                            <React.Fragment key={l.id}>
                                <input type="radio" id={l.id} name="level" value={l.val} required className={`inline-block align-middle m-[6px_5px] w-4 h-4 ${l.accent} cursor-pointer`} />
                                <label htmlFor={l.id} className="text-white inline-block align-middle cursor-pointer select-none">
                                    <strong className={`${l.color} bg-white px-0.75 rounded-sm font-bold`}>{l.label}</strong> {l.desc}
                                </label>
                                <br />
                            </React.Fragment>
                        ))}
                        <div className="hidden group-[.was-validated]/form:group-has-invalid/radios:block text-[#e60b20] text-[14px] pl-2.5 mt-2">Glöm inte ange spelarnivå!</div>
                    </div>

                    <textarea name="message" autoComplete="off" placeholder="Övrig info..." className="w-full min-h-37.5 p-[12px_16px] border-[5px] border-white rounded-[10px] bg-transparent text-white text-[15px] resize-y outline-none mt-5" />

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

                    {alert.show && (
                        <div className={`w-full p-4 rounded-md text-center font-bold my-4 ${alert.type === 'success' ? 'bg-[#d1e7dd] text-[#0a3622] border-[#a3cfbb]' : 'bg-[#f8d7da] text-[#58151c] border-[#f1aeb5]'}`}>
                            {alert.message}
                        </div>
                    )}

                    <div className="w-full flex justify-center mt-2.5">
                        <Turnstile ref={turnstileRef} siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || ''} options={{ theme: 'dark' }} />
                    </div>

                    <button type="submit" disabled={isSubmitting} className="bg-white text-black uppercase w-full max-w-75 h-12.5 text-[20px] font-bold rounded-[10px] my-5 flex justify-center items-center cursor-pointer hover:bg-gray-200 transition-all active:scale-95 disabled:opacity-70">
                        {isSubmitting && (
                            <svg className="animate-spin h-5 w-5 text-black mr-3" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                            </svg>
                        )}
                        <span>Skicka anmälan</span>
                    </button>
                </form>
            </div>
        </section>
    );
}