'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;
  }[];
}

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 [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [routinesData, streaksData, summaryData] = await Promise.all([
          api.routines.list(),
          api.stats.getStreaks(),
          api.stats.getWeeklySummary(),
        ]);
        setRoutines(routinesData);
        setStreaks(streaksData);
        setWeeklySummary(summaryData);
        
        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) => {
    if (minutes < 60) return `${minutes}m`;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 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">Stats</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">Time</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">Started</p>
          </div>
        </div>
      )}

      {/* Streaks */}
      {streaks.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 mb-3">Streaks</h2>
          <div className="space-y-2">
            {streaks.map((streak) => (
              <div key={streak.routine_id} className="bg-white 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 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">{streak.routine_name}</p>
                  <p className="text-sm text-gray-500">
                    Last: {streak.last_completed_date ? new Date(streak.last_completed_date).toLocaleDateString() : 'Never'}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-2xl font-bold text-orange-500">{streak.current_streak}</p>
                  <p className="text-xs text-gray-500">day streak</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Per-Routine Stats */}
      {routines.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 mb-3">Routine Stats</h2>
          <select
            value={selectedRoutine}
            onChange={(e) => setSelectedRoutine(e.target.value)}
            className="w-full px-4 py-3 border border-gray-300 rounded-xl bg-white 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 rounded-xl p-4 shadow-sm">
                <TargetIcon className="text-indigo-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900">{routineStats.completion_rate_percent}%</p>
                <p className="text-sm text-gray-500">Completion Rate</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <ClockIcon className="text-purple-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900">{formatTime(routineStats.avg_duration_minutes)}</p>
                <p className="text-sm text-gray-500">Avg Duration</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <StarIcon className="text-green-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900">{routineStats.completed}</p>
                <p className="text-sm text-gray-500">Completed</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <ActivityIcon className="text-pink-500 mb-2" size={24} />
                <p className="text-2xl font-bold text-gray-900">{routineStats.total_sessions}</p>
                <p className="text-sm text-gray-500">Total Sessions</p>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
