import React, { useState, useEffect } from 'react';
import axios from 'axios';
import NarrativeSection from './NarrativeSection';
import StatsGrid from './StatsGrid';
import PlaylistsSection from './PlaylistsSection';
import VibeRadar from './VibeRadar';
import HeatMap from './HeatMap';
import TopRotation from './TopRotation';
import ListeningLog from './ListeningLog';
import Navbar from './Navbar';
import { Spin } from 'antd';

const API_BASE_URL = '/api';

const Dashboard = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    const getTodayKey = () => `sonicstats_v2_${new Date().toISOString().split('T')[0]}`;

    const fetchData = async (forceRefresh = false) => {
        setLoading(true);
        const todayKey = getTodayKey();

        if (!forceRefresh) {
            const cached = localStorage.getItem(todayKey);
            if (cached) {
                console.log("Loading from cache");
                setData(JSON.parse(cached));
                setLoading(false);
                return;
            }
        }

        try {
            let payload;
            if (forceRefresh) {
                const res = await axios.post(`${API_BASE_URL}/trigger-analysis?days=30`);
                payload = res.data;
            } else {
                const snapRes = await axios.get(`${API_BASE_URL}/snapshots?limit=1`);
                if (snapRes.data && snapRes.data.length > 0) {
                    const latest = snapRes.data[0];
                    payload = {
                        metrics: latest.metrics_payload,
                        narrative: latest.narrative_report
                    };
                } else {
                    const res = await axios.post(`${API_BASE_URL}/trigger-analysis?days=30`);
                    payload = res.data;
                }
            }

            if (payload) {
                setData(payload);
                localStorage.setItem(todayKey, JSON.stringify(payload));
            }

        } catch (error) {
            console.error("Failed to fetch data", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    if (loading && !data) {
        return (
            <div className="min-h-screen bg-background-dark flex flex-col items-center justify-center text-white">
                <Spin size="large" />
                <p className="mt-4 text-slate-400 animate-pulse">Analyzing your auditory aura...</p>
            </div>
        );
    }

    const vibeCheckFull = data?.narrative?.vibe_check || "";
    const patterns = data?.narrative?.patterns || [];

    return (
        <>
            <Navbar onRefresh={() => fetchData(true)} />

            <main className="flex-grow w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
                <NarrativeSection narrative={data?.narrative} vibe={data?.metrics?.vibe} />
                
                <StatsGrid metrics={data?.metrics} />

                <PlaylistsSection />

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div className="lg:col-span-2 space-y-8">
                        <VibeRadar vibe={data?.metrics?.vibe} />
                        <TopRotation volume={data?.metrics?.volume} />
                    </div>

                    <div className="lg:col-span-1 space-y-8">
                        <HeatMap timeHabits={data?.metrics?.time_habits} sessions={data?.metrics?.sessions} />
                    </div>
                </div>

                <ListeningLog />

                {(vibeCheckFull || patterns.length > 0) && (
                    <div className="bg-card-dark border border-[#222f49] rounded-xl p-6">
                        <h3 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
                            <span className="material-symbols-outlined text-primary">psychology</span>
                            Full Analysis
                        </h3>
                        
                        {vibeCheckFull && (
                            <div className="prose prose-invert max-w-none mb-6">
                                <p className="text-slate-300 leading-relaxed whitespace-pre-line">{vibeCheckFull}</p>
                            </div>
                        )}

                        {patterns.length > 0 && (
                            <div className="mt-4">
                                <h4 className="text-sm text-slate-400 uppercase font-medium mb-3">Patterns Detected</h4>
                                <ul className="space-y-2">
                                    {patterns.map((pattern, idx) => (
                                        <li key={idx} className="flex items-start gap-2 text-slate-300">
                                            <span className="material-symbols-outlined text-primary text-sm mt-0.5">insights</span>
                                            {pattern}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        )}
                    </div>
                )}

                {data?.narrative?.roast && (
                    <footer className="pb-8">
                        <div className="paper-texture rounded-xl p-8 border border-white/10 relative overflow-hidden group">
                            <div className="relative z-10 flex flex-col md:flex-row gap-8 items-start md:items-center justify-between">
                                <div className="max-w-md">
                                    <div className="text-xs font-mono text-gray-500 mb-2 uppercase tracking-widest">Analysis Complete</div>
                                    <h2 className="text-3xl font-black text-gray-900 leading-tight">
                                        Your Musical Age is <span className="text-primary underline decoration-wavy">{data?.metrics?.era?.musical_age || "Unknown"}</span>.
                                    </h2>
                                    <p className="text-gray-600 mt-2 font-medium">
                                        {data?.narrative?.era_insight || "You are timeless."}
                                    </p>
                                </div>
                                <div className="flex-1 bg-white p-6 rounded-lg shadow-sm border border-gray-200 transform rotate-1 md:group-hover:rotate-0 transition-transform duration-300">
                                    <div className="flex items-start gap-3">
                                        <span className="material-symbols-outlined text-gray-400">smart_toy</span>
                                        <div>
                                            <p className="font-mono text-sm text-gray-800 leading-relaxed">
                                                "{data.narrative.roast}"
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </footer>
                )}
            </main>
        </>
    );
};

export default Dashboard;
