import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { format } from 'date-fns';

function CreateEvent() {
    const [eventName, setEventName] = useState('');
    const [description, setDescription] = useState('');
    const [startDate, setStartDate] = useState(format(new Date(), 'yyyy-MM-dd'));
    const [endDate, setEndDate] = useState(format(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd'));
    const [links, setLinks] = useState(null);
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!eventName || !startDate || !endDate) return;

        setLoading(true);
        try {
            const response = await fetch('/api/events', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    name: eventName,
                    description,
                    startDate,
                    endDate
                }),
            });
            const data = await response.json();
            if (data.id) {
                const origin = window.location.origin;
                setLinks({
                    invite: `${origin}/event/${data.id}`,
                    analytics: `${origin}/event/${data.id}/analytics`,
                });
            }
        } catch (error) {
            console.error('Error creating event:', error);
            alert('Failed to create event');
        } finally {
            setLoading(false);
        }
    };

    if (links) {
        return (
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-white shadow-stripe p-8 rounded-xl text-center max-w-lg mx-auto"
            >
                <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">Event Created!</h1>
                <p className="text-slate-500 mb-8">Share these links with your group.</p>

                <div className="mb-6 text-left">
                    <label className="block text-slate-500 text-xs mb-2 uppercase tracking-wider font-bold">Invite Link</label>
                    <div
                        className="bg-slate-50 p-4 rounded-lg flex justify-between items-center group cursor-pointer border border-slate-200 hover:border-primary transition-colors"
                        onClick={() => navigator.clipboard.writeText(links.invite)}
                    >
                        <span className="truncate text-slate-700 text-sm font-mono">{links.invite}</span>
                        <span className="text-primary text-sm font-medium ml-2">Copy</span>
                    </div>
                </div>

                <div className="mb-8 text-left">
                    <label className="block text-slate-500 text-xs mb-2 uppercase tracking-wider font-bold">Analytics (Secret)</label>
                    <div
                        className="bg-slate-50 p-4 rounded-lg flex justify-between items-center group cursor-pointer border border-slate-200 hover:border-primary transition-colors"
                        onClick={() => navigator.clipboard.writeText(links.analytics)}
                    >
                        <span className="truncate text-slate-700 text-sm font-mono">{links.analytics}</span>
                        <span className="text-primary text-sm font-medium ml-2">Copy</span>
                    </div>
                </div>

                <button
                    onClick={() => setLinks(null)}
                    className="text-primary hover:text-primary-hover font-medium underline underline-offset-4 transition-colors"
                >
                    Create Another Event
                </button>
            </motion.div>
        );
    }

    return (
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="w-full max-w-md mx-auto"
        >
            <div className="bg-white rounded-xl shadow-stripe p-6 sm:p-8">
                <h1 className="text-2xl font-bold text-slate-800 mb-6">Create New Event</h1>

                <form onSubmit={handleSubmit} className="space-y-6">
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-2">
                            Event Name
                        </label>
                        <input
                            type="text"
                            value={eventName}
                            onChange={(e) => setEventName(e.target.value)}
                            placeholder="e.g., Team Dinner, Project Kickoff"
                            className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all placeholder:text-slate-400 text-slate-800"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-2">
                            Description (Optional)
                        </label>
                        <textarea
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            placeholder="Add some details about the event..."
                            className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all placeholder:text-slate-400 text-slate-800 resize-none h-24"
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-2">
                                Earliest Date
                            </label>
                            <input
                                type="date"
                                value={startDate}
                                onChange={(e) => setStartDate(e.target.value)}
                                className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all text-slate-800"
                                required
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-2">
                                Latest Date
                            </label>
                            <input
                                type="date"
                                value={endDate}
                                onChange={(e) => setEndDate(e.target.value)}
                                className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all text-slate-800"
                                required
                            />
                        </div>
                    </div>

                    <button
                        type="submit"
                        disabled={loading}
                        className="w-full bg-primary hover:bg-primary-hover text-white font-medium py-2.5 rounded-lg shadow-sm hover:shadow-md transition-all active:scale-[0.98] mt-8 disabled:opacity-50"
                    >
                        {loading ? 'Creating...' : 'Create Event'}
                    </button>
                </form>
            </div>
        </motion.div>
    );
}

export default CreateEvent;
