"use client"
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { Calendar, BarChart2, Settings, TrendingUp, Clock, Moon, Bus, Loader2, Sparkles } from 'lucide-react';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, Legend, PieChart, Pie, Cell, LineChart, Line, ReferenceLine } from 'recharts';
import { format, subDays } from 'date-fns';

interface Block {
  _id: string;
  dayOfWeek: string;
  startTime: string;
  endTime: string;
  blockType: string;
  activityName: string;
  color: string;
}

interface Completion {
  _id: string;
  date: string;
  completed: boolean;
}

interface AIInsight {
  title: string;
  observation: string;
  advice: string[];
}

interface AIInsights {
  greeting: string;
  insights: AIInsight[];
  conclusion: string;
}

export default function AnalyticsPage() {
  const [blocks, setBlocks] = useState<Block[]>([]);
  const [completions, setCompletions] = useState<Completion[]>([]);
  const [loading, setLoading] = useState(true);

  // AI State
  const [aiInsights, setAiInsights] = useState<AIInsights | null>(null);
  const [generatingAI, setGeneratingAI] = useState(false);
  const [aiError, setAiError] = useState('');

  const generateInsights = async () => {
    setGeneratingAI(true);
    setAiError('');
    try {
      const res = await fetch('/api/ai-insights', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          schedule: blocks, 
          completions: completions.filter(c => {
             const d = new Date(c.date);
             const limit = new Date();
             limit.setDate(limit.getDate() - 14);
             return d >= limit;
          }) 
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to generate insights');
      setAiInsights(data.data);
    } catch (err: Error | unknown) {
      setAiError(err instanceof Error ? err.message : 'Failed to generate insights');
    } finally {
      setGeneratingAI(false);
    }
  };

  useEffect(() => {
    Promise.all([
      fetch('/api/schedule').then(res => res.json()),
      fetch('/api/completions').then(res => res.json())
    ]).then(([schedData, compData]) => {
      if (Array.isArray(schedData)) setBlocks(schedData);
      if (Array.isArray(compData)) setCompletions(compData);
      setLoading(false);
    }).catch(err => {
      console.error(err);
      setLoading(false);
    });
  }, []);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen bg-slate-950">
        <Loader2 className="animate-spin text-teal-500" size={48} />
      </div>
    );
  }

  // Calculate Stats
  let totalSleep = 0;
  let totalBus = 0;
  let totalProductive = 0; // Course + Web Dev + Work + Weekend Class

  const getHours = (start: string, end: string) => {
    const [sH, sM] = start.split(':').map(Number);
    const [eH, eM] = end.split(':').map(Number);
    return (eH + eM / 60) - (sH + sM / 60);
  };

  blocks.forEach(b => {
    const hrs = getHours(b.startTime, b.endTime);
    if (b.blockType === 'sleep') totalSleep += hrs;
    if (b.blockType === 'bus') totalBus += hrs;
    if (['course', 'webdev', 'work', 'weekend'].includes(b.blockType)) totalProductive += hrs;
  });

  // Daily distribution for today
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const todayName = days[new Date().getDay()];
  const todayBlocks = blocks.filter(b => b.dayOfWeek === todayName);
  
  const pieDataMap: Record<string, {name: string, value: number, color: string}> = {};
  todayBlocks.forEach(b => {
    const hrs = getHours(b.startTime, b.endTime);
    if (!pieDataMap[b.blockType]) {
      pieDataMap[b.blockType] = { name: b.activityName, value: 0, color: b.color };
    }
    pieDataMap[b.blockType].value += hrs;
  });
  const pieData = Object.values(pieDataMap);

  // Grouped Bar Chart Data
  const weeklyMap: Record<string, { name: string; Course: number; Work: number; Free: number }> = {};
  days.forEach(d => weeklyMap[d] = { name: d.substring(0, 3), Course: 0, Work: 0, Free: 0 });

  blocks.forEach(b => {
    const hrs = getHours(b.startTime, b.endTime);
    if (b.blockType === 'course') weeklyMap[b.dayOfWeek].Course += hrs;
    if (b.blockType === 'work') weeklyMap[b.dayOfWeek].Work += hrs;
    if (b.blockType === 'free') weeklyMap[b.dayOfWeek].Free += hrs;
  });
  const weeklyData = [weeklyMap.Monday, weeklyMap.Tuesday, weeklyMap.Wednesday, weeklyMap.Thursday, weeklyMap.Friday, weeklyMap.Saturday, weeklyMap.Sunday];

  const today = new Date();

  // Streak Calculation & Completion Rate Trend (14 days)
  const completionRateData = [];
  let currentStreak = 0;
  let bestStreak = 0;
  let tempStreak = 0;

  for (let i = 13; i >= 0; i--) {
    const d = subDays(today, i);
    const dateStr = format(d, 'yyyy-MM-dd');
    
    // Count scheduled items for that day of week vs completed
    const dayName = days[d.getDay()];
    const scheduledForDay = blocks.filter(b => b.dayOfWeek === dayName).length;
    const completedForDay = completions.filter(c => c.date === dateStr && c.completed).length;
    
    const rate = scheduledForDay === 0 ? 0 : Math.round((completedForDay / scheduledForDay) * 100);
    
    completionRateData.push({
      name: format(d, 'MMM dd'),
      rate: rate
    });

    // Streak logic (≥80%)
    if (rate >= 80 && scheduledForDay > 0) {
      tempStreak++;
      if (tempStreak > bestStreak) bestStreak = tempStreak;
      if (i === 0) currentStreak = tempStreak; // If today is part of the streak
    } else {
      if (i === 0) currentStreak = tempStreak; // Streak broke today
      tempStreak = 0;
    }
  }
  
  // Backwards iteration for accurate current streak if today is 0 but yesterday was active
  if (currentStreak === 0) {
    let activeStreak = 0;
    for (let i = 1; i <= 30; i++) {
       const d = subDays(today, i);
       const dateStr = format(d, 'yyyy-MM-dd');
       const dayName = days[d.getDay()];
       const sched = blocks.filter(b => b.dayOfWeek === dayName).length;
       const comp = completions.filter(c => c.date === dateStr && c.completed).length;
       const r = sched === 0 ? 0 : (comp / sched) * 100;
       if (r >= 80 && sched > 0) activeStreak++;
       else if (sched > 0) break; // streak broken
    }
    currentStreak = activeStreak;
  }

  // Heatmap Data (Last 12 weeks = 84 days)
  const heatmapData = [];
  const completionsPerDay: Record<string, number> = {};
  
  completions.forEach(c => {
    if (c.completed) {
      completionsPerDay[c.date] = (completionsPerDay[c.date] || 0) + 1;
    }
  });

  for (let i = 83; i >= 0; i--) {
    const d = subDays(today, i);
    const dateStr = format(d, 'yyyy-MM-dd');
    const count = completionsPerDay[dateStr] || 0;
    
    let intensity = 'bg-slate-800';
    if (count > 0) intensity = 'bg-emerald-900';
    if (count > 2) intensity = 'bg-emerald-700';
    if (count > 4) intensity = 'bg-emerald-500';
    if (count >= 6) intensity = 'bg-emerald-400';

    heatmapData.push({ date: dateStr, count, intensity });
  }

  return (
    <div className="max-w-6xl mx-auto pb-16 pt-4">
      <header className="flex justify-between items-center mb-8 px-4">
        <div>
          <h1 className="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-emerald-400 to-teal-400">
            Analytics Dashboard
          </h1>
          <p className="text-slate-400 mt-1">Insights into your productivity and habits.</p>
        </div>
        
        <nav className="flex space-x-4">
          <Link href="/" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <Calendar size={18} />
            <span>සතිය (Week)</span>
          </Link>
          <Link href="/analytics" className="flex items-center space-x-2 px-4 py-2 bg-slate-800 rounded-lg text-teal-400 border border-teal-500/30">
            <BarChart2 size={18} />
            <span>Analytics</span>
          </Link>
          <Link href="/settings" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <Settings size={18} />
          </Link>
        </nav>
      </header>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8 px-4">
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-slate-400 text-sm font-medium">Productive Hours/Wk</p>
              <h3 className="text-3xl font-bold text-emerald-400 mt-1">{totalProductive}h</h3>
            </div>
            <div className="p-2 bg-emerald-500/10 rounded-lg text-emerald-400"><TrendingUp size={24} /></div>
          </div>
        </div>
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-slate-400 text-sm font-medium">Sleep Hours/Wk</p>
              <h3 className="text-3xl font-bold text-indigo-400 mt-1">{totalSleep}h</h3>
            </div>
            <div className="p-2 bg-indigo-500/10 rounded-lg text-indigo-400"><Moon size={24} /></div>
          </div>
        </div>
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-slate-400 text-sm font-medium">Commute Time/Wk</p>
              <h3 className="text-3xl font-bold text-orange-400 mt-1">{totalBus}h</h3>
            </div>
            <div className="p-2 bg-orange-500/10 rounded-lg text-orange-400"><Bus size={24} /></div>
          </div>
        </div>
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-slate-400 text-sm font-medium">Best Streak</p>
              <h3 className="text-3xl font-bold text-blue-400 mt-1">{bestStreak} Days</h3>
              <p className="text-slate-500 text-xs mt-1">Current: {currentStreak} days</p>
            </div>
            <div className="p-2 bg-blue-500/10 rounded-lg text-blue-400"><Clock size={24} /></div>
          </div>
        </div>
      </div>

      {/* AI Insights Section */}
      <div className="px-4 mb-8">
        <div className="bg-slate-900/60 backdrop-blur-md border border-indigo-500/30 p-6 rounded-2xl shadow-lg shadow-indigo-500/10">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-400 to-purple-400 flex items-center space-x-2">
              <Sparkles className="text-indigo-400" size={24} />
              <span>AI Productivity Coach</span>
            </h3>
            <button 
              onClick={generateInsights}
              disabled={generatingAI || blocks.length === 0}
              className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg text-white font-medium transition-colors shadow-lg shadow-indigo-500/20 flex items-center space-x-2"
            >
              {generatingAI ? <Loader2 className="animate-spin" size={18} /> : <span>Generate Insights</span>}
            </button>
          </div>

          {aiError && (
            <div className="p-4 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg mb-4">
              {aiError}
            </div>
          )}

          {aiInsights ? (
            <div className="space-y-6 mt-6">
              <p className="text-slate-300 italic mb-4">{aiInsights.greeting}</p>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {aiInsights.insights?.map((insight: AIInsight, idx: number) => (
                  <div key={idx} className="bg-slate-800/50 border border-indigo-500/20 p-5 rounded-xl hover:bg-slate-800/80 transition-colors">
                    <h4 className="text-lg font-bold text-indigo-300 mb-2">{insight.title}</h4>
                    <p className="text-slate-300 text-sm mb-4 leading-relaxed">{insight.observation}</p>
                    <ul className="space-y-2">
                      {insight.advice?.map((adv: string, i: number) => (
                        <li key={i} className="flex items-start space-x-2 text-sm text-emerald-400/90">
                          <span className="text-emerald-500 mt-0.5">•</span>
                          <span>{adv}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                ))}
              </div>

              <p className="text-slate-400 mt-4 text-center font-medium">{aiInsights.conclusion}</p>
            </div>
          ) : (
            <div className="text-slate-500 text-center py-8">
              Click the button above to have the AI analyze your schedule and task history.
            </div>
          )}
        </div>
      </div>

      {/* GitHub Style Heatmap Calendar */}
      <div className="px-4 mb-8">
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <h3 className="text-lg font-semibold text-slate-200 mb-6">Task Completion History (Last 12 Weeks)</h3>
          <div className="flex flex-col items-start overflow-x-auto pb-4">
            <div 
              className="grid gap-1"
              style={{ gridTemplateRows: 'repeat(7, 1fr)', gridAutoFlow: 'column' }}
            >
              {heatmapData.map((day, idx) => (
                <div 
                  key={idx}
                  className={`w-4 h-4 rounded-sm ${day.intensity} hover:ring-2 hover:ring-slate-400 transition-all cursor-pointer`}
                  title={`${day.date}: ${day.count} tasks completed`}
                ></div>
              ))}
            </div>
            <div className="flex items-center space-x-2 mt-4 text-xs text-slate-400">
              <span>Less</span>
              <div className="w-3 h-3 rounded-sm bg-slate-800"></div>
              <div className="w-3 h-3 rounded-sm bg-emerald-900"></div>
              <div className="w-3 h-3 rounded-sm bg-emerald-700"></div>
              <div className="w-3 h-3 rounded-sm bg-emerald-500"></div>
              <div className="w-3 h-3 rounded-sm bg-emerald-400"></div>
              <span>More</span>
            </div>
          </div>
        </div>
      </div>

      {/* Main Charts Area */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 px-4">
        {/* Bar Chart */}
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <h3 className="text-lg font-semibold text-slate-200 mb-6">Weekly Overview</h3>
          <div className="h-80 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={weeklyData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                <XAxis dataKey="name" stroke="#94a3b8" tick={{fill: '#94a3b8'}} />
                <YAxis stroke="#94a3b8" tick={{fill: '#94a3b8'}} />
                <Tooltip 
                  contentStyle={{ backgroundColor: '#1e293b', borderColor: '#334155', color: '#f8fafc' }}
                  itemStyle={{ color: '#f8fafc' }}
                />
                <Legend wrapperStyle={{ paddingTop: '20px' }} />
                <Bar dataKey="Course" stackId="a" fill="#3b82f6" />
                <Bar dataKey="Work" stackId="a" fill="#10b981" />
                <Bar dataKey="Free" stackId="a" fill="#14b8a6" />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Pie Chart */}
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg">
          <h3 className="text-lg font-semibold text-slate-200 mb-6">Today&apos;s Time Distribution</h3>
          <div className="h-80 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={pieData}
                  cx="50%"
                  cy="50%"
                  innerRadius={80}
                  outerRadius={110}
                  paddingAngle={5}
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${((percent || 0) * 100).toFixed(0)}%`}
                  labelLine={false}
                >
                  {pieData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  formatter={(value) => [`${value || 0} hours`, 'Time Spent']}
                  contentStyle={{ backgroundColor: '#1e293b', borderColor: '#334155', color: '#f8fafc' }}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </div>
        {/* Completion Rate Trend Line Chart */}
        <div className="bg-slate-900/60 backdrop-blur-md border border-slate-700 p-6 rounded-2xl shadow-lg lg:col-span-2">
          <h3 className="text-lg font-semibold text-slate-200 mb-6">Task Completion Rate (Last 14 Days)</h3>
          <div className="h-80 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={completionRateData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
                <XAxis dataKey="name" stroke="#94a3b8" tick={{fill: '#94a3b8'}} />
                <YAxis stroke="#94a3b8" tick={{fill: '#94a3b8'}} domain={[0, 100]} />
                <Tooltip 
                  contentStyle={{ backgroundColor: '#1e293b', borderColor: '#334155', color: '#f8fafc' }}
                  itemStyle={{ color: '#f8fafc' }}
                  formatter={(value) => [`${value}%`, 'Completion Rate']}
                />
                <ReferenceLine y={80} stroke="#10b981" strokeDasharray="3 3" label={{ position: 'top', value: 'Streak Goal (80%)', fill: '#10b981', fontSize: 12 }} />
                <Line type="monotone" dataKey="rate" stroke="#3b82f6" strokeWidth={3} dot={{ r: 4, fill: '#3b82f6', strokeWidth: 2 }} activeDot={{ r: 6 }} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
    </div>
  );
}
