import React from 'react';
import { format, parseISO } from 'date-fns';

const HeatMap = ({ timeHabits, sessions }) => {
    if (!timeHabits) return null;

    const heatmapCompressed = timeHabits.heatmap_compressed || timeHabits.heatmap || [];
    const blockLabels = timeHabits.block_labels || ["12am-4am", "4am-8am", "8am-12pm", "12pm-4pm", "4pm-8pm", "8pm-12am"];
    const sessionList = sessions?.session_list || [];
    
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    const blocks = blockLabels.length > 0 ? blockLabels : Array.from({ length: 6 }, (_, i) => `${i*4}h-${(i+1)*4}h`);
    
    const maxVal = Math.max(...heatmapCompressed.flat(), 1);

    const getIntensityClass = (val) => {
        if (val === 0) return "bg-[#1e293b]";
        const ratio = val / maxVal;
        if (ratio > 0.8) return "bg-primary";
        if (ratio > 0.6) return "bg-primary/80";
        if (ratio > 0.4) return "bg-primary/60";
        if (ratio > 0.2) return "bg-primary/40";
        return "bg-primary/20";
    };

    const recentSessions = sessionList.slice(-5).reverse();

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

    const getSessionTypeColor = (type) => {
        if (type === "Marathon") return "bg-primary";
        if (type === "Micro") return "bg-slate-600";
        return "bg-primary/50";
    };

    return (
        <div className="bg-card-dark border border-[#222f49] rounded-xl p-6 h-full">
            <h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
                <span className="material-symbols-outlined text-primary">history</span>
                Chronobiology
            </h3>

            <div className="mb-8">
                <h4 className="text-sm text-slate-400 mb-3 font-medium">Listening Heatmap</h4>
                
                <div className="flex gap-2">
                    <div className="flex flex-col justify-between text-[10px] text-slate-500 pr-1 py-1">
                        {blocks.map((label, i) => (
                            <span key={i} className="leading-tight">{label.split('-')[0]}</span>
                        ))}
                    </div>
                    
                    <div className="flex-1">
                        <div className="grid grid-cols-7 gap-1 mb-2">
                            {days.map((d, i) => (
                                <div key={i} className="text-[10px] text-center text-slate-500 font-medium">{d}</div>
                            ))}
                        </div>
                        
                        <div className="grid grid-cols-7 gap-1">
                            {blocks.map((block, blockIdx) => (
                                days.map((day, dayIdx) => {
                                    const val = heatmapCompressed[dayIdx]?.[blockIdx] || 0;
                                    return (
                                        <div 
                                            key={`${dayIdx}-${blockIdx}`} 
                                            className={`h-6 rounded ${getIntensityClass(val)} transition-colors hover:ring-2 hover:ring-primary/50`}
                                            title={`${day} ${block} - ${val} plays`}
                                        />
                                    );
                                })
                            )).flat()}
                        </div>
                    </div>
                </div>
                
                <div className="flex justify-end gap-1 mt-3 items-center">
                    <span className="text-[9px] text-slate-500">Less</span>
                    <div className="w-3 h-3 rounded-sm bg-primary/20"></div>
                    <div className="w-3 h-3 rounded-sm bg-primary/40"></div>
                    <div className="w-3 h-3 rounded-sm bg-primary/60"></div>
                    <div className="w-3 h-3 rounded-sm bg-primary/80"></div>
                    <div className="w-3 h-3 rounded-sm bg-primary"></div>
                    <span className="text-[9px] text-slate-500">More</span>
                </div>
            </div>

            <div>
                <h4 className="text-sm text-slate-400 mb-4 font-medium">Recent Sessions</h4>
                {recentSessions.length > 0 ? (
                    <div className="relative pl-4 border-l border-[#334155] space-y-4">
                        {recentSessions.map((session, idx) => (
                            <div key={idx} className="relative">
                                <span className={`absolute -left-[21px] top-1 h-2.5 w-2.5 rounded-full ${getSessionTypeColor(session.type)} ring-4 ring-card-dark`}></span>
                                <p className="text-xs text-slate-400">{formatSessionTime(session.start_time)}</p>
                                <p className="text-white font-bold text-sm">{session.type} Session</p>
                                <p className="text-xs text-primary mt-0.5">
                                    {session.duration_minutes}m · {session.track_count} tracks
                                </p>
                            </div>
                        ))}
                    </div>
                ) : (
                    <p className="text-sm text-slate-500">No session data yet</p>
                )}
            </div>
        </div>
    );
};

export default HeatMap;
