'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';
import { useAuth } from '@/components/auth/AuthProvider';
import { PlayIcon, ClockIcon, FlameIcon, StarIcon, ActivityIcon } from '@/components/ui/Icons';
import Link from 'next/link';

interface Routine {
  id: string;
  name: string;
  description?: string;
  icon?: string;
}

interface ActiveSession {
  session: {
    id: string;
    routine_id: string;
    status: string;
    current_step_index: number;
  };
  routine: {
    id: string;
    name: string;
    icon?: string;
  };
  current_step: {
    id: string;
    name: string;
    step_type: string;
    duration_minutes?: number;
  } | null;
}

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

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

export default function DashboardPage() {
  const { user } = useAuth();
  const router = useRouter();
  const [routines, setRoutines] = useState<Routine[]>([]);
  const [activeSession, setActiveSession] = useState<ActiveSession | null>(null);
  const [weeklySummary, setWeeklySummary] = useState<WeeklySummary | null>(null);
  const [streaks, setStreaks] = useState<Streak[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [routinesData, activeData, summaryData, streaksData] = await Promise.all([
          api.routines.list().catch(() => []),
          api.sessions.getActive().catch(() => null),
          api.stats.getWeeklySummary().catch(() => null),
          api.stats.getStreaks().catch(() => []),
        ]);
        setRoutines(routinesData);
        setActiveSession(activeData);
        setWeeklySummary(summaryData);
        setStreaks(streaksData);
      } catch (err) {
        console.error('Failed to fetch dashboard data:', err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  const handleStartRoutine = (routineId: string) => {
    // If there's an active session, go straight to run
    if (activeSession) {
      router.push(`/dashboard/routines/${activeSession.routine.id}/run`);
    } else {
      router.push(`/dashboard/routines/${routineId}/launch`);
    }
  };

  const handleResumeSession = () => {
    if (activeSession) {
      router.push(`/dashboard/routines/${activeSession.routine.id}/run`);
    }
  };

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return 'Good morning';
    if (hour < 17) return 'Good afternoon';
    return 'Good evening';
  };

  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`;
  };

  // Find routines with broken streaks for "never miss twice" recovery
  const getRecoveryRoutines = () => {
    const today = new Date();
    return streaks.filter(s => {
      if (!s.last_completed_date || s.current_streak > 0) return false;
      const last = new Date(s.last_completed_date);
      const daysSince = Math.floor((today.getTime() - last.getTime()) / (1000 * 60 * 60 * 24));
      return daysSince >= 2 && daysSince <= 14;
    });
  };

  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>
    );
  }

  const recoveryRoutines = getRecoveryRoutines();

  return (
    <div className="p-4 space-y-6">
      {/* Active Session Banner */}
      {activeSession && activeSession.session.status === 'active' && (
        <div className="bg-gradient-to-r from-indigo-500 to-purple-600 rounded-2xl p-4 text-white ring-2 ring-indigo-400/50 ring-offset-2 ring-offset-gray-50 dark:ring-offset-gray-950 animate-gentle-pulse">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/80 text-sm">Continue where you left off</p>
              <h2 className="text-xl font-bold">{activeSession.routine.name}</h2>
              <p className="text-white/80 text-sm mt-1">
                Step {activeSession.session.current_step_index + 1}: {activeSession.current_step?.name}
              </p>
            </div>
            <button
              onClick={handleResumeSession}
              className="bg-white text-indigo-600 px-4 py-2 rounded-lg font-semibold"
            >
              Resume
            </button>
          </div>
        </div>
      )}

      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{getGreeting()}, {user?.username}!</h1>
        <p className="text-gray-500 dark:text-gray-400 mt-1">Let&apos;s build some great habits today.</p>
      </div>

      {/* "Never miss twice" Recovery Cards */}
      {recoveryRoutines.map(recovery => {
        const routine = routines.find(r => r.id === recovery.routine_id);
        if (!routine) return null;
        return (
          <div key={recovery.routine_id} className="bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded-2xl p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-amber-800 dark:text-amber-200 text-sm font-medium mb-1">Welcome back</p>
                <p className="text-amber-700 dark:text-amber-300 text-sm">
                  It&apos;s been a couple days since {routine.icon} {routine.name}. That&apos;s completely okay — picking it back up today is what matters most.
                </p>
              </div>
              <button
                onClick={() => handleStartRoutine(routine.id)}
                className="bg-amber-600 text-white px-4 py-2 rounded-lg font-medium text-sm shrink-0 ml-3"
              >
                Start
              </button>
            </div>
          </div>
        );
      })}

      {/* Weekly Stats — identity-based language */}
      {weeklySummary && weeklySummary.total_completed > 0 && (
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
            <div className="flex items-center gap-2 text-indigo-600 mb-1">
              <StarIcon size={18} />
              <span className="text-xs font-medium">Done</span>
            </div>
            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{weeklySummary.total_completed}</p>
            <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">this week</p>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
            <div className="flex items-center gap-2 text-purple-600 mb-1">
              <ClockIcon size={18} />
              <span className="text-xs font-medium">Invested</span>
            </div>
            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{formatTime(weeklySummary.total_time_minutes)}</p>
            <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">in yourself</p>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
            <div className="flex items-center gap-2 text-pink-600 mb-1">
              <ActivityIcon size={18} />
              <span className="text-xs font-medium">Active</span>
            </div>
            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">{weeklySummary.routines_started}</p>
            <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">routines</p>
          </div>
        </div>
      )}

      {/* Quick Start Routines */}
      <div>
        <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">Your Routines</h2>

        {routines.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center">
            <div className="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
              <FlameIcon className="text-gray-400 dark:text-gray-500" size={32} />
            </div>
            <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1">No routines yet</h3>
            <p className="text-gray-500 dark:text-gray-400 text-sm mb-4">Create your first routine to get started</p>
            <Link
              href="/dashboard/routines/new"
              className="inline-block bg-indigo-600 text-white px-4 py-2 rounded-lg font-medium"
            >
              Create Routine
            </Link>
          </div>
        ) : (
          <div className="space-y-3">
            {routines.map((routine) => {
              const streak = streaks.find(s => s.routine_id === routine.id);
              return (
                <div
                  key={routine.id}
                  className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-center justify-between"
                >
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 bg-gradient-to-br from-indigo-100 to-pink-100 dark:from-indigo-900/50 dark:to-pink-900/50 rounded-xl flex items-center justify-center">
                      <span className="text-2xl">{routine.icon || '✨'}</span>
                    </div>
                    <div>
                      <h3 className="font-semibold text-gray-900 dark:text-gray-100">{routine.name}</h3>
                      {streak && streak.current_streak > 0 ? (
                        <p className="text-sm text-orange-500 flex items-center gap-1">
                          <FlameIcon size={14} />
                          {streak.current_streak} day{streak.current_streak !== 1 ? 's' : ''}
                        </p>
                      ) : routine.description ? (
                        <p className="text-gray-500 dark:text-gray-400 text-sm">{routine.description}</p>
                      ) : null}
                    </div>
                  </div>
                  <button
                    onClick={() => handleStartRoutine(routine.id)}
                    className="bg-indigo-600 text-white p-3 rounded-full"
                  >
                    <PlayIcon size={20} />
                  </button>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Templates CTA */}
      <div className="bg-gradient-to-r from-pink-500 to-rose-500 rounded-2xl p-4 text-white">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-semibold">Need inspiration?</h3>
            <p className="text-white/80 text-sm">Browse pre-made routines</p>
          </div>
          <Link
            href="/dashboard/templates"
            className="bg-white text-pink-600 px-4 py-2 rounded-lg font-medium"
          >
            Browse
          </Link>
        </div>
      </div>

      {error && (
        <div className="bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}
    </div>
  );
}
