import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import CalendarSelector from './CalendarSelector';
import { motion } from 'framer-motion';

export default function EventPoll() {
    const { id } = useParams();
    const [event, setEvent] = useState(null);
    const [loading, setLoading] = useState(true);
    const [name, setName] = useState('');
    const [votes, setVotes] = useState({});
    const [submitting, setSubmitting] = useState(false);
    const [submitted, setSubmitted] = useState(false);

    useEffect(() => {
        fetch(`/api/events/${id}`)
            .then(res => {
                if (!res.ok) throw new Error('Event not found');
                return res.json();
            })
            .then(data => {
                setEvent(data);
                setLoading(false);
            })
            .catch(err => {
                console.error(err);
                setLoading(false);
            });
    }, [id]);

    const toggleDate = (dateStr) => {
        setVotes(prev => {
            const current = prev[dateStr];
            const next = !current ? 'available' : current === 'available' ? 'unavailable' : undefined;
            const newVotes = { ...prev };
            if (next) newVotes[dateStr] = next;
            else delete newVotes[dateStr];
            return newVotes;
        });
    };

    const handleSubmit = async () => {
        if (!name.trim()) return alert('Please enter your name');
        if (Object.keys(votes).length === 0) return alert('Please select at least one date preference');
        setSubmitting(true);

        try {
            const votesArray = Object.entries(votes).map(([date, status]) => ({ date, status }));
            const res = await fetch(`/api/events/${id}/respond`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, votes: votesArray }),
            });

            if (res.ok) {
                setSubmitted(true);
            } else {
                alert('Failed to submit response');
            }
        } catch (err) {
            console.error(err);
            alert('Error submitting response');
        } finally {
            setSubmitting(false);
        }
    };

    if (loading) return <div className="text-slate-400 text-center mt-20 font-medium">Loading invitation...</div>;
    if (!event) return <div className="text-rose-500 text-center mt-20">Event not found</div>;

    if (submitted) {
        return (
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-white shadow-stripe p-10 rounded-xl text-center max-w-lg mx-auto mt-10"
            >
                <div className="w-16 h-16 bg-emerald-50 rounded-full flex items-center justify-center mx-auto mb-6">
                    <svg className="w-8 h-8 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                </div>
                <h1 className="text-2xl font-bold text-slate-800 mb-2">You're all set!</h1>
                <p className="text-slate-500 mb-8">Thanks for helping pick a date.</p>
                <button
                    onClick={() => window.location.reload()}
                    className="text-primary hover:text-primary-hover font-medium underline underline-offset-4 transition-colors"
                >
                    Submit for someone else?
                </button>
            </motion.div>
        );
    }

    return (
        <div className="w-full pb-32 max-w-lg mx-auto">
            <div className="text-center mb-10 px-4">
                <h2 className="text-slate-500 font-medium text-sm uppercase tracking-wider mb-3">You're invited to</h2>
                <h1 className="text-3xl md:text-4xl font-bold text-slate-900 mb-4 leading-tight">
                    {event.name}
                </h1>
                {event.description && (
                    <p className="text-slate-500 text-lg leading-relaxed">{event.description}</p>
                )}
            </div>

            <div className="mb-10 px-4">
                <input
                    type="text"
                    placeholder="Enter your name..."
                    className="w-full bg-white border border-slate-200 shadow-sm rounded-lg px-4 py-3 text-lg text-center font-medium text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                />
            </div>

            <div className="bg-white rounded-xl p-6 shadow-stripe border border-slate-100">
                <div className="flex justify-between items-center mb-6 text-xs font-semibold text-slate-400 uppercase tracking-wider px-2">
                    <span>Select Dates</span>
                    <div className="flex gap-4">
                        <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-primary"></span> Yes</span>
                        <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-rose-400"></span> No</span>
                    </div>
                </div>

                <CalendarSelector
                    startDate={event.start_date}
                    endDate={event.end_date}
                    votes={votes}
                    onToggle={toggleDate}
                />
            </div>

            <motion.div
                initial={{ y: 100 }}
                animate={{ y: 0 }}
                className="fixed bottom-0 left-0 w-full p-6 bg-white/80 backdrop-blur-lg border-t border-slate-200 flex justify-center z-50 transition-all"
            >
                <button
                    onClick={handleSubmit}
                    disabled={submitting}
                    className="bg-slate-900 text-white font-medium px-8 py-3 rounded-lg shadow-lg hover:shadow-xl hover:bg-slate-800 active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100 w-full max-w-sm"
                >
                    {submitting ? 'Sending...' : 'Confirm Availability'}
                </button>
            </motion.div>
        </div>
    );
}
