"use client";

import { useState } from "react";

export default function VolunteerForm({ opportunityId, customFields }: { opportunityId: string, customFields: any[] }) {
    const [formData, setFormData] = useState<any>({});
    const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setStatus("loading");

        // Extract base fields and custom fields
        const payload = {
            opportunityId,
            name: formData.name,
            email: formData.email,
            phone: formData.phone,
            customData: {} as any
        };

        customFields.forEach(cf => {
            if (formData[cf.id]) payload.customData[cf.id] = formData[cf.id];
        });

        try {
            const res = await fetch("/api/volunteer", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
            });
            if (!res.ok) throw new Error("Failed to sign up");
            setStatus("success");
        } catch (err) {
            console.error(err);
            setStatus("error");
        }
    };

    if (status === "success") {
        return (
            <div className="success-pop" style={{ padding: "2rem", background: "rgba(16, 185, 129, 0.1)", borderRadius: "12px", textAlign: "center", color: "#064e3b" }}>
                <svg
                    className="check-icon"
                    width="56"
                    height="56"
                    viewBox="0 0 56 56"
                    fill="none"
                    style={{ marginBottom: "1rem" }}
                >
                    <circle cx="28" cy="28" r="26" stroke="#10b981" strokeWidth="3" />
                    <path d="M17 29L24 36L39 20" stroke="#10b981" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <h3 style={{ fontSize: "1.5rem", marginBottom: "0.5rem", color: "#064e3b" }}>You're Signed Up!</h3>
                <p style={{ color: "#064e3b" }}>Thank you for volunteering. We will be in touch with you shortly.</p>
            </div>
        );
    }

    const inputStyle = {
        width: "100%", padding: "0.75rem 1rem", borderRadius: "8px",
        border: "1px solid var(--border)", background: "var(--background)",
        color: "var(--foreground)", fontFamily: "inherit"
    };

    return (
        <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.5rem" }}>
                <div>
                    <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Full Name *</label>
                    <input required type="text" style={inputStyle} value={formData.name || ''} onChange={e => setFormData({ ...formData, name: e.target.value })} />
                </div>
                <div>
                    <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Email *</label>
                    <input required type="email" style={inputStyle} value={formData.email || ''} onChange={e => setFormData({ ...formData, email: e.target.value })} />
                </div>
            </div>

            <div>
                <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>Phone (optional)</label>
                <input type="tel" style={inputStyle} value={formData.phone || ''} onChange={e => setFormData({ ...formData, phone: e.target.value })} />
            </div>

            {customFields.map(cf => (
                <div key={cf.id}>
                    <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: 500 }}>
                        {cf.name} {cf.required && "*"}
                    </label>
                    {cf.type === "TEXT" && (
                        <input required={cf.required} type="text" style={inputStyle} value={formData[cf.id] || ''} onChange={e => setFormData({ ...formData, [cf.id]: e.target.value })} />
                    )}
                    {cf.type === "SELECT" && (
                        <select required={cf.required} style={inputStyle} value={formData[cf.id] || ''} onChange={e => setFormData({ ...formData, [cf.id]: e.target.value })}>
                            <option value="">Select an option...</option>
                            {JSON.parse(cf.options || "[]").map((opt: string) => (
                                <option key={opt} value={opt}>{opt}</option>
                            ))}
                        </select>
                    )}
                </div>
            ))}

            {status === "error" && (
                <div style={{ color: "#7f1d1d", fontSize: "0.9rem" }}>There was an error submitting your sign up. Please try again.</div>
            )}

            <button type="submit" disabled={status === "loading"} style={{ marginTop: "1rem", alignSelf: "flex-start", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "0.5rem", padding: "0.75rem 2.5rem", background: "#065f46", color: "#fff", borderRadius: "9999px", fontWeight: 600, border: "none", cursor: "pointer", transition: "all 0.2s" }} onMouseOver={(e) => e.currentTarget.style.transform = 'translateY(-2px)'} onMouseOut={(e) => e.currentTarget.style.transform = 'translateY(0)'}>
                {status === "loading" ? "Submitting..." : "Complete Sign Up"}
            </button>
        </form>
    );
}
