import { NextResponse } from 'next/server';
import connectToDatabase from '@/lib/mongodb';
import ScheduleBlock from '@/models/ScheduleBlock';
import TaskCompletion from '@/models/TaskCompletion';
import { validateRequest } from '@/lib/auth';
import { startOfWeek, addDays, format } from 'date-fns';

function timeToMinutes(time: string): number {
  const [h, m] = time.split(':').map(Number);
  return h * 60 + m;
}

function minutesToHours(minutes: number): number {
  return Math.round((minutes / 60) * 10) / 10;
}

export async function GET(request: Request) {
  try {
    const { valid, error } = validateRequest(request);
    if (!valid) {
      return NextResponse.json({ success: false, error }, { status: 401 });
    }

    await connectToDatabase();

    const weekStart = startOfWeek(new Date(), { weekStartsOn: 1 });
    const weekEnd = addDays(weekStart, 6);
    const startDateStr = format(weekStart, 'yyyy-MM-dd');
    const endDateStr = format(weekEnd, 'yyyy-MM-dd');

    const [blocks, completions] = await Promise.all([
      ScheduleBlock.find().sort({ dayOfWeek: 1, startTime: 1 }),
      TaskCompletion.find({ date: { $gte: startDateStr, $lte: endDateStr } }),
    ]);

    // Hours per activity type
    const hoursByType: Record<string, number> = {};
    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    const dailyBreakdown: Record<string, Record<string, number>> = {};

    days.forEach((day) => {
      dailyBreakdown[day] = {};
    });

    blocks.forEach((block) => {
      const mins =
        timeToMinutes(block.endTime) - timeToMinutes(block.startTime);
      const hours = minutesToHours(Math.max(0, mins));
      const type = block.blockType;

      hoursByType[type] = (hoursByType[type] || 0) + hours;
      if (dailyBreakdown[block.dayOfWeek]) {
        dailyBreakdown[block.dayOfWeek][type] =
          (dailyBreakdown[block.dayOfWeek][type] || 0) + hours;
      }
    });

    // Completion stats for the week
    const totalCompletions = completions.length;
    const completedCount = completions.filter((c) => c.completed === true).length;
    const completionRate =
      totalCompletions > 0
        ? Math.round((completedCount / totalCompletions) * 100)
        : 0;

    // Daily productivity (completed productive hours)
    const productiveTypes = ['Course', 'Work', 'Web Dev', 'webdev', 'course', 'work'];
    const dailyProductivity: { day: string; hours: number; date: string }[] = [];

    days.forEach((day, idx) => {
      const date = format(addDays(weekStart, idx), 'yyyy-MM-dd');
      const dayBlocks = blocks.filter((b) => b.dayOfWeek === day);
      const prodHours = dayBlocks
        .filter((b) => productiveTypes.some((t) => b.blockType.toLowerCase().includes(t.toLowerCase())))
        .reduce((sum, b) => {
          const mins = timeToMinutes(b.endTime) - timeToMinutes(b.startTime);
          return sum + minutesToHours(Math.max(0, mins));
        }, 0);
      dailyProductivity.push({ day, date, hours: Math.round(prodHours * 10) / 10 });
    });

    // Sleep hours (average per day from schedule)
    const sleepHours =
      (hoursByType['Sleep'] || hoursByType['sleep'] || 0) / 7;

    // Commute hours (bus)
    const commuteHours = hoursByType['Bus'] || hoursByType['bus'] || 0;

    return NextResponse.json({
      success: true,
      data: {
        hoursByType,
        dailyBreakdown,
        dailyProductivity,
        weekSummary: {
          totalProductiveHours:
            Math.round((hoursByType['Course'] || 0) * 10 +
              (hoursByType['Work'] || 0) * 10 +
              (hoursByType['Web Dev'] || hoursByType['webdev'] || 0) * 10) / 10,
          sleepHoursAvg: Math.round(sleepHours * 10) / 10,
          commuteHours: Math.round(commuteHours * 10) / 10,
          completionRate,
          totalBlocks: blocks.length,
          weekStartDate: startDateStr,
          weekEndDate: endDateStr,
        },
      },
    });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to fetch analytics data' },
      { status: 500 }
    );
  }
}
