'use client';

import { useEffect, useState } from 'react';
import api from '@/lib/api';
import { FlameIcon, StarIcon, ClockIcon, ActivityIcon, TargetIcon } from '@/components/ui/Icons';

interface RoutineStats {
  routine_id: string;
  routine_name: string;
  period_days: number;
  total_sessions: number;
  completed: number;
  aborted: number;
  completion_rate_percent: number;
  avg_duration_minutes: number;
  total_time_minutes: number;
}

interface Streak {
  routine_id: string;
  routine_name: string;
  current_streak: number;
  longest_streak: number;
  last_completed_date?: string;
}

interface WeeklySummary {
  total_completed: number;
  total_time_minutes: number;
  routines_started: number;
  routines: {
    routine_id: string;
    name: string;
    completed_this_week: number;
  }[];
}

function getStreakMessage(streak: number): string {
  if (streak === 0) return 'Ready for a fresh start';
  if (streak === 1) return "You're back! Day 1";
  if (streak <= 3) return `${streak} days of showing up`;
  if (streak <= 7) return `${streak} days — building momentum`;
  return `${streak} days — you're someone who shows up`;
}

function getCompletionLabel(rate: number): { label: string; color: string } {
  if (rate >= 80) return { label: 'Rock solid', color: 'text-green-600' };
  if (rate >= 60) return { label: 'Strong habit', color: 'text-indigo-600' };
  if (rate >= 30) return { label: 'Building momentum', color: 'text-amber-600' };
  return { label: 'Getting started', color: 'text-gray-600' };
}

interface Victory {
  type: string;
  message: string;
  date?: string;
}

export default function StatsPage() {
  const [routines, setRoutines] = useState<{ id: string; name: string }[]>([]);
  const [selectedRoutine, setSelectedRoutine] = useState<string>('');
  const [routineStats, setRoutineStats] = useState<RoutineStats | null>(null);
  const [streaks, setStreaks] = useState<Streak[]>([]);
  const [weeklySummary, setWeeklySummary] = useState<WeeklySummary | null>(null);
  const [victories, setVictories] = useState<Victory[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [routinesData, streaksData, summaryData, victoriesData] = await Promise.all([
          api.routines.list(),
          api.stats.getStreaks(),
          api.stats.getWeeklySummary(),
          api.victories.get(30).catch(() => []),
        ]);
        setRoutines(routinesData);
        setStreaks(streaksData);
        setWeeklySummary(summaryData);
        setVictories(victoriesData);

        if (routinesData.length > 0) {
          setSelectedRoutine(routinesData[0].id);
        }
      } catch (err) {
        console.error('Failed to fetch stats:', err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchRoutineStats = async () => {
      if (!selectedRoutine) return;
      try {
        const stats = await api.routines.getStats(selectedRoutine, 30);
        setRoutineStats(stats);
      } catch (err) {
        console.error('Failed to fetch routine stats:', err);
      }
    };
    fetchRoutineStats();
  }, [selectedRoutine]);

  const formatTime = (minutes: number) => {
    const m = Math.max(0, minutes);
    if (m < 60) return `${m}m`;
    const hours = Math.floor(m / 60);
    const mins = m % 60;
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  return (
    <div className="p-4 space-y-6">
      <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Your Progress</h1>

      {/* Weekly Summary */}
      {weeklySummary && (
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl p-4 text-white">
            <StarIcon className="text-white/80 mb-2" size={24} />
            <p className="text-3xl font-bold">{weeklySummary.total_completed}</p>
            <p className="text-white/80 text-sm">Completed</p>
          </div>
          <div className="bg-gradient-to-br from-pink-500 to-rose-600 rounded-2xl p-4 text-white">
            <ClockIcon className="text-white/80 mb-2" size={24} />
            <p className="text-3xl font-bold">{formatTime(weeklySummary.total_time_minutes)}</p>
            <p className="text-white/80 text-sm">Invested</p>
          </div>
          <div className="bg-gradient-to-br from-amber-500 to-orange-600 rounded-2xl p-4 text-white">
            <ActivityIcon className="text-white/80 mb-2" size={24} />
            <p className="text-3xl font-bold">{weeklySummary.routines_started}</p>
            <p className="text-white/80 text-sm">Active</p>
          </div>
        </div>
      )}

      {/* Wins This Month */}
      {victories.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">Wins This Month</h2>
          <div className="space-y-2">
            {victories.map((victory, i) => (
              <div key={i} className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-100 to-emerald-100 dark:from-green-900/30 dark:to-emerald-900/30 rounded-xl flex items-center justify-center">
                  <span className="text-lg">
                    {victory.type === 'comeback' ? '💪' :
                     victory.type === 'weekend' ? '🎉' :
                     victory.type === 'variety' ? '🌈' :
                     victory.type === 'consistency' ? '🔥' : '⭐'}
                  </span>
                </div>
                <p className="text-sm text-gray-700 dark:text-gray-300 flex-1">{victory.message}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Consistency (formerly Streaks) */}
      {streaks.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">Your Consistency</h2>
          <div className="space-y-2">
            {streaks.map((streak) => (
              <div key={streak.routine_id} className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-center gap-4">
                <div className="w-12 h-12 bg-gradient-to-br from-orange-100 to-red-100 dark:from-orange-900/30 dark:to-red-900/30 rounded-xl flex items-center justify-center">
                  <FlameIcon className="text-orange-500" size={24} />
                </div>
                <div className="flex-1">
                  <p className="font-medium text-gray-900 dark:text-gray-100">{streak.routine_name}</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    {getStreakMessage(streak.current_streak)}
                  </p>
                </div>
                <div className="text-right">
                  {streak.current_streak > 0 ? (
                    <>
                      <p className="text-2xl font-bold text-orange-500">{streak.current_streak}</p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">days</p>
                    </>
                  ) : (
                    <p className="text-sm text-gray-400 dark:text-gray-500">Ready</p>
                  )}
                </div>
              </div>
            ))}
            {/* Longest streak callout */}
            {streaks.some(s => s.longest_streak > 0) && (
              <p className="text-sm text-gray-400 dark:text-gray-500 text-center mt-2">
                Your personal best: {Math.max(...streaks.map(s => s.longest_streak))} days — you&apos;ve done it before
              </p>
            )}
          </div>
        </div>
      )}

      {/* Per-Routine Stats */}
      {routines.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">Routine Details</h2>
          <select
            value={selectedRoutine}
            onChange={(e) => setSelectedRoutine(e.target.value)}
            className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 mb-4"
          >
            {routines.map((routine) => (
              <option key={routine.id} value={routine.id}>
                {routine.name}
              </option>
            ))}
          </select>

          {routineStats && (
            <div className="grid grid-cols-2 gap-3">
              <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
                <TargetIcon className="text-indigo-500 mb-2" size={24} />
                <p className={`text-lg font-bold ${getCompletionLabel(routineStats.completion_rate_percent).color}`}>
                  {getCompletionLabel(routineStats.completion_rate_percent).label}
                </p>
                <p className="text-sm text-gray-400 dark:text-gray-500">{routineStats.completion_rate_percent}%</p>
              </div>
              <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
                <ClockIcon className="text-purple-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{formatTime(routineStats.avg_duration_minutes)}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">Avg Duration</p>
              </div>
              <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
                <StarIcon className="text-green-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{routineStats.completed}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">Completed</p>
              </div>
              <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
                <ActivityIcon className="text-pink-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{routineStats.total_sessions}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">Total Sessions</p>
              </div>
            </div>
          )}

          {/* Plateau messaging */}
          {routineStats && routineStats.total_sessions >= 5 && (
            <p className="text-sm text-gray-400 dark:text-gray-500 text-center mt-3">
              {routineStats.completion_rate_percent >= 60
                ? "You're showing up consistently — that's the hard part. The exact rate doesn't matter."
                : "Life has seasons. The fact that you're checking in shows this matters to you."}
            </p>
          )}
        </div>
      )}
    </div>
  );
}
