// frontend/src/pages/Dashboard.tsx

import { Calendar, ChevronDown, ChevronUp, History, Plus, PlusCircle, SlidersHorizontal, Loader2 } from 'lucide-react';
import { useEffect, useState, useCallback } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import DashCard from '../components/Dashboard/DashCard';
import TournamentForm from '../components/Forms/TournamentForm';
import Modal from '../components/UI/Modal';
import api, { WS_URL } from '../services/api';

export interface TournamentType {
    id: string | number;
    name: string;
    timestamp: string;
    type: string;
    team_count: number;
    court_count: number;
}

interface OutletContextType {
    setNavTitle: (title: string) => void;
    setNavSubtitle: (subtitle: string) => void;
    role: 'admin' | 'ref' | null;
    showSettings: boolean;
    setShowSettings: (show: boolean) => void;
}

export default function Dashboard() {
    const { setNavTitle, setNavSubtitle, role, showSettings, setShowSettings } = useOutletContext<OutletContextType>();

    const [tournaments, setTournaments] = useState<TournamentType[]>([]);
    const [editTarget, setEditTarget] = useState<TournamentType | null>(null);
    const [showPast, setShowPast] = useState<boolean>(false);
    const [showAllFuture, setShowAllFuture] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(true);
    const navigate = useNavigate();

    const loadDashboard = useCallback(async () => {
        try {
            const res = await api.get<{ items?: TournamentType[] } | TournamentType[]>('/tournaments');
            const list = Array.isArray(res) ? res : (res?.items || []);
            setTournaments(list as TournamentType[]);
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        setNavTitle('Dashboard');
        setNavSubtitle('');
        localStorage.removeItem('volley_view');

        (async () => {
            await loadDashboard();
        })();

        let ws: WebSocket;
        let reconnectTimeout: ReturnType<typeof setTimeout>;

        const connect = () => {
            try {
                ws = new WebSocket(WS_URL);
                ws.onmessage = (e: MessageEvent) => {
                    const msg = JSON.parse(e.data);
                    if (msg.type === 'dashboard_update') loadDashboard();
                };
                ws.onclose = () => {
                    reconnectTimeout = setTimeout(connect, 3000);
                };
            } catch (err) {
                console.error("WebSocket connection failed", err);
            }
        };
        connect();

        const handleVisibilityChange = () => {
            if (document.visibilityState === 'visible') {
                (async () => {
                    await loadDashboard();
                })();
                if (!ws || ws.readyState === WebSocket.CLOSED) {
                    clearTimeout(reconnectTimeout);
                    connect();
                }
            }
        };
        document.addEventListener('visibilitychange', handleVisibilityChange);

        return () => {
            clearTimeout(reconnectTimeout);
            document.removeEventListener('visibilitychange', handleVisibilityChange);
            if (ws) {
                ws.onclose = null;
                ws.close();
            }
        };
    }, [setNavTitle, setNavSubtitle, loadDashboard]);

    const handleEdit = (t: TournamentType) => {
        setEditTarget(t);
        setShowSettings(true);
    };

    const handleSuccess = () => {
        setShowSettings(false);
        setEditTarget(null);
        loadDashboard();
    };

    const handleDelete = async (id: string | number) => {
        if (window.confirm("Purge this tournament and all its history?")) {
            await api.delete(`/tournaments/${id}`);
            handleSuccess();
        }
    };

    if (loading) {
        return (
            <div className="flex h-full items-center justify-center">
                <Loader2 className="animate-spin text-orange-600" size={48} />
            </div>
        );
    }

    const now = new Date();
    const groups: { live: TournamentType[]; future: TournamentType[]; past: TournamentType[] } = {
        live: [],
        future: [],
        past: []
    };

    tournaments.forEach(t => {
        const tDate = new Date(t.timestamp);
        const isToday = tDate.toDateString() === now.toDateString();

        if (tDate > now && !isToday) groups.future.push(t);
        else if (isToday) groups.live.push(t);
        else groups.past.push(t);
    });

    groups.future.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    groups.live.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    groups.past.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

    const futureShow = showAllFuture ? groups.future : groups.future.slice(0, 4);

    return (
        <div className="h-full overflow-y-auto pt-8 sm:pt-12 pb-32">
            <div className="container mx-auto max-w-5xl px-4 space-y-12">

                {role === 'admin' && (
                    <div className="flex justify-center md:justify-end">
                        <button onClick={() => { setEditTarget(null); setShowSettings(true); }} className="bg-orange-600 hover:bg-orange-500 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 text-[10px] font-black uppercase tracking-wider shadow-xl shadow-orange-600/20 active:scale-95 transition">
                            <Plus size={16} strokeWidth={4} /> Create
                        </button>
                    </div>
                )}

                {groups.live.length > 0 && (
                    <section>
                        <h2 className="text-xs font-black text-green-500 uppercase tracking-[0.2em] mb-6 flex items-center gap-3">
                            <span className="relative flex size-3">
                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
                                <span className="relative inline-flex size-3 rounded-full bg-green-500"></span>
                            </span> Live Events
                        </h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {groups.live.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
                        </div>
                    </section>
                )}

                <section className="mb-10">
                    <h2 className="text-xs font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.2em] mb-6 flex items-center gap-3">
                        <Calendar size={18} /> Upcoming
                    </h2>
                    {groups.future.length > 0 ? (
                        <>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {futureShow.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
                            </div>
                            {groups.future.length > 4 && (
                                <div className="mt-8 text-center">
                                    <button onClick={() => setShowAllFuture(!showAllFuture)} className="text-xs font-black uppercase tracking-widest text-zinc-500 hover:text-orange-500 transition border-b-2 border-transparent hover:border-orange-500 pb-1 flex items-center justify-center gap-1 mx-auto">
                                        {showAllFuture ? 'Show Less' : `Show All (${groups.future.length})`}
                                        {showAllFuture ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                                    </button>
                                </div>
                            )}
                        </>
                    ) : <div className="p-16 text-center rounded-3xl border-2 border-dashed border-zinc-300 dark:border-zinc-800 text-zinc-400 text-xs font-black uppercase tracking-[0.3em]">No Upcoming Events</div>}
                </section>

                {groups.past.length > 0 && (
                    <section>
                        <button onClick={() => setShowPast(!showPast)} className="w-full flex items-center justify-between group py-6 border-t border-zinc-300 dark:border-zinc-800 transition-colors hover:border-zinc-400">
                            <h2 className="text-xs font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.2em] flex items-center gap-3"><History size={18} />Archive</h2>
                            {showPast ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
                        </button>
                        {showPast && (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-75 hover:opacity-100 transition-opacity">
                                {groups.past.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
                            </div>
                        )}
                    </section>
                )}
            </div>

            <Modal isOpen={showSettings} onClose={() => { setShowSettings(false); setEditTarget(null); }} title={editTarget ? 'Tournament Settings' : 'New Tournament'} icon={editTarget ? SlidersHorizontal : PlusCircle}>
                <TournamentForm
                    tournamentId={editTarget?.id}
                    onSuccess={handleSuccess}
                    onDelete={handleDelete}
                />
            </Modal>
        </div>
    );
}