import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { format, parseISO, differenceInMinutes, startOfDay, endOfDay } from 'date-fns';

const API_BASE_URL = '/api';

const ListeningLog = () => {
    const [plays, setPlays] = useState([]);
    const [sessions, setSessions] = useState([]);
    const [days, setDays] = useState(7);
    const [loading, setLoading] = useState(true);
    const [view, setView] = useState('timeline');

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

    const fetchData = async () => {
        setLoading(true);
        try {
            const [logRes, sessRes] = await Promise.all([
                axios.get(`${API_BASE_URL}/listening-log?days=${days}&limit=500`),
                axios.get(`${API_BASE_URL}/sessions?days=${days}`)
            ]);
            setPlays(logRes.data.plays || []);
            setSessions(sessRes.data.sessions || []);
        } catch (error) {
            console.error("Failed to fetch listening log", error);
        } finally {
            setLoading(false);
        }
    };

    const formatTime = (isoString) => {
        try {
            return format(parseISO(isoString), 'MMM d, h:mm a');
        } catch {
            return isoString;
        }
    };

    const formatDuration = (ms) => {
        if (!ms) return '-';
        const mins = Math.round(ms / 60000);
        return `${mins}m`;
    };

    const groupSessionsByDay = () => {
        const dayMap = {};
        sessions.forEach(session => {
            const dayKey = format(parseISO(session.start_time), 'yyyy-MM-dd');
            if (!dayMap[dayKey]) dayMap[dayKey] = [];
            dayMap[dayKey].push(session);
        });
        return dayMap;
    };

    const sessionsByDay = groupSessionsByDay();
    const sortedDays = Object.keys(sessionsByDay).sort().reverse().slice(0, 7);

    const getSessionPosition = (session) => {
        const start = parseISO(session.start_time);
        const startMinutes = start.getHours() * 60 + start.getMinutes();
        const leftPct = (startMinutes / 1440) * 100;
        const widthPct = Math.max((session.duration_minutes / 1440) * 100, 1);
        return { left: `${leftPct}%`, width: `${Math.min(widthPct, 100 - leftPct)}%` };
    };

    const getSessionColor = (type) => {
        if (type === 'Marathon') return 'bg-primary';
        if (type === 'Micro') return 'bg-slate-500';
        return 'bg-primary/70';
    };

    return (
        <div className="bg-card-dark border border-[#222f49] rounded-xl p-6">
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold text-white flex items-center gap-2">
                    <span className="material-symbols-outlined text-primary">library_music</span>
                    Listening Log
                </h3>
                <div className="flex gap-2">
                    <select 
                        value={days}
                        onChange={(e) => setDays(Number(e.target.value))}
                        className="bg-card-darker border border-[#334155] rounded px-3 py-1 text-sm text-white"
                    >
                        <option value={1}>Last 24h</option>
                        <option value={7}>Last 7 days</option>
                        <option value={14}>Last 14 days</option>
                        <option value={30}>Last 30 days</option>
                    </select>
                    <div className="flex border border-[#334155] rounded overflow-hidden">
                        <button 
                            onClick={() => setView('timeline')}
                            className={`px-3 py-1 text-sm ${view === 'timeline' ? 'bg-primary text-white' : 'bg-card-darker text-slate-400'}`}
                        >
                            Timeline
                        </button>
                        <button 
                            onClick={() => setView('list')}
                            className={`px-3 py-1 text-sm ${view === 'list' ? 'bg-primary text-white' : 'bg-card-darker text-slate-400'}`}
                        >
                            List
                        </button>
                    </div>
                </div>
            </div>

            {loading ? (
                <div className="text-slate-400 text-center py-8">Loading...</div>
            ) : view === 'timeline' ? (
                <div className="space-y-4">
                    <div className="flex text-[10px] text-slate-500 mb-2">
                        <div className="w-20"></div>
                        <div className="flex-1 flex justify-between">
                            <span>12am</span>
                            <span>6am</span>
                            <span>12pm</span>
                            <span>6pm</span>
                            <span>12am</span>
                        </div>
                    </div>
                    {sortedDays.map(day => (
                        <div key={day} className="flex items-center gap-2">
                            <div className="w-20 text-xs text-slate-400 shrink-0">
                                {format(parseISO(day), 'EEE, MMM d')}
                            </div>
                            <div className="flex-1 h-8 bg-card-darker rounded relative">
                                {sessionsByDay[day]?.map((session, idx) => {
                                    const pos = getSessionPosition(session);
                                    return (
                                        <div
                                            key={idx}
                                            className={`absolute h-full rounded ${getSessionColor(session.type)} opacity-80 hover:opacity-100 cursor-pointer transition-opacity`}
                                            style={{ left: pos.left, width: pos.width }}
                                            title={`${session.type}: ${session.track_count} tracks, ${session.duration_minutes}m`}
                                        />
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                    <div className="flex gap-4 mt-4 text-xs text-slate-400">
                        <div className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded bg-primary"></div>
                            <span>Marathon (20+ tracks)</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded bg-primary/70"></div>
                            <span>Standard</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <div className="w-3 h-3 rounded bg-slate-500"></div>
                            <span>Micro (1-3 tracks)</span>
                        </div>
                    </div>
                </div>
            ) : (
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="text-left text-slate-400 border-b border-[#334155]">
                                <th className="pb-2 font-medium">Track</th>
                                <th className="pb-2 font-medium">Artist</th>
                                <th className="pb-2 font-medium">Played</th>
                                <th className="pb-2 font-medium">Listened</th>
                                <th className="pb-2 font-medium">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {plays.slice(0, 50).map((play, idx) => (
                                <tr key={idx} className="border-b border-[#222f49] hover:bg-card-darker/50">
                                    <td className="py-3">
                                        <div className="flex items-center gap-3">
                                            {play.image && (
                                                <img src={play.image} alt="" className="w-10 h-10 rounded object-cover" />
                                            )}
                                            <span className="text-white font-medium truncate max-w-[200px]">{play.track_name}</span>
                                        </div>
                                    </td>
                                    <td className="py-3 text-slate-400 truncate max-w-[150px]">{play.artist}</td>
                                    <td className="py-3 text-slate-400">{formatTime(play.played_at)}</td>
                                    <td className="py-3 text-slate-400">{formatDuration(play.listened_ms)}</td>
                                    <td className="py-3">
                                        {play.skipped ? (
                                            <span className="px-2 py-0.5 rounded text-xs bg-red-500/20 text-red-400">Skipped</span>
                                        ) : (
                                            <span className="px-2 py-0.5 rounded text-xs bg-green-500/20 text-green-400">Played</span>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
};

export default ListeningLog;
