import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { format, parseISO, eachDayOfInterval } from 'date-fns';

export default function AnalyticsDashboard() {
    const { id } = useParams();
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetch(`/api/events/${id}/analytics`)
            .then(res => {
                if (!res.ok) throw new Error('Failed to load analytics');
                return res.json();
            })
            .then(setData)
            .catch(err => {
                console.error(err);
                setLoading(false);
            });
    }, [id]);

    if (loading && !data) return <div className="text-slate-400 animate-pulse text-center mt-20 font-medium">Analysing responses...</div>;
    if (!data) return <div className="text-rose-500 text-center mt-20">Failed to load analytics</div>;

    const { event, participants, votes } = data;

    const allDates = eachDayOfInterval({
        start: parseISO(event.start_date),
        end: parseISO(event.end_date)
    }).map(d => format(d, 'yyyy-MM-dd'));

    const scores = {};
    allDates.forEach(date => scores[date] = 0);

    votes.forEach(v => {
        if (v.status === 'available') {
            scores[v.date] = (scores[v.date] || 0) + 1;
        }
    });

    const rankedDates = Object.entries(scores)
        .sort(([, a], [, b]) => b - a)
        .slice(0, 5);

    const maxVotes = participants.length > 0 ? participants.length : 1;

    return (
        <div className="w-full pb-32">
            <div className="text-center mb-12">
                <h2 className="text-xs uppercase tracking-widest text-slate-500 mb-2 font-bold">Results for</h2>
                <h1 className="text-3xl md:text-5xl font-bold text-slate-900 capitalize leading-tight">{event.name}</h1>
            </div>

            <div className="grid md:grid-cols-2 gap-8 max-w-5xl mx-auto">
                {/* Best Dates Panel */}
                <div className="bg-white p-6 rounded-xl shadow-stripe border border-slate-200">
                    <h2 className="text-lg font-bold mb-6 text-slate-800 flex items-center gap-2">
                        <span className="text-primary">
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clipRule="evenodd" />
                            </svg>
                        </span>
                        Top Dates
                    </h2>
                    <div className="space-y-6">
                        {rankedDates.map(([date, score], idx) => {
                            const percentage = Math.round((score / maxVotes) * 100);
                            return (
                                <div key={date} className="group">
                                    <div className="flex justify-between items-end mb-2">
                                        <div className="flex items-center gap-3">
                                            <span className={`font-semibold text-lg ${idx === 0 ? 'text-primary' : 'text-slate-700'}`}>
                                                {format(parseISO(date), 'EEE, MMM do')}
                                            </span>
                                            {idx === 0 && <span className="text-[10px] uppercase font-bold tracking-wider bg-primary/10 text-primary px-2 py-0.5 rounded-full">Best</span>}
                                        </div>
                                        <span className="text-sm font-medium text-slate-500">{score} / {maxVotes}</span>
                                    </div>
                                    <div className="h-2.5 bg-slate-100 rounded-full overflow-hidden">
                                        <div
                                            className={`h-full rounded-full transition-all duration-1000 ease-out ${idx === 0 ? 'bg-primary' : 'bg-slate-300'}`}
                                            style={{ width: `${percentage}%` }}
                                        ></div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Participants Panel */}
                <div className="bg-white p-6 rounded-xl shadow-stripe border border-slate-200 overflow-hidden">
                    <div className="flex justify-between items-center mb-6">
                        <h2 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                            <span className="text-slate-400">
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                    <path d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
                                </svg>
                            </span>
                            Availability
                        </h2>
                        <span className="text-xs font-semibold text-slate-500 bg-slate-100 px-2.5 py-1 rounded-full">{participants.length}</span>
                    </div>

                    <div className="overflow-x-auto -mx-6 px-6 pb-2">
                        <table className="w-full text-left border-collapse min-w-[300px]">
                            <thead>
                                <tr>
                                    <th className="p-3 pl-0 text-xs font-bold text-slate-400 uppercase tracking-widest border-b border-slate-100 sticky left-0 bg-white z-10 w-32">Name</th>
                                    {allDates.map(date => (
                                        <th key={date} className="p-2 text-[10px] font-bold text-slate-400 border-b border-slate-100 text-center min-w-[40px]">
                                            {format(parseISO(date), 'dd')}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {participants.map(p => (
                                    <tr key={p.id} className="group hover:bg-slate-50 transition-colors">
                                        <td className="p-3 pl-0 border-b border-slate-100 font-medium text-slate-700 sticky left-0 bg-white group-hover:bg-slate-50 transition-colors z-10 text-sm">{p.name}</td>
                                        {allDates.map(date => {
                                            const vote = votes.find(v => v.participant_id === p.id && v.date === date);

                                            if (vote?.status === 'available') {
                                                return (
                                                    <td key={date} className="p-2 border-b border-slate-100 text-center">
                                                        <div className="w-3 h-3 bg-primary rounded-full mx-auto"></div>
                                                    </td>
                                                );
                                            } else if (vote?.status === 'unavailable') {
                                                return (
                                                    <td key={date} className="p-2 border-b border-slate-100 text-center">
                                                        <div className="w-1.5 h-1.5 bg-rose-200 rounded-full mx-auto"></div>
                                                    </td>
                                                );
                                            }
                                            return (
                                                <td key={date} className="p-2 border-b border-slate-100 text-center text-slate-200">·</td>
                                            );
                                        })}
                                    </tr>
                                ))}
                                {participants.length === 0 && (
                                    <tr>
                                        <td colSpan={allDates.length + 1} className="p-8 text-center text-slate-400 text-sm italic">Waiting for responses...</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    );
}
