/**
 * MyLearning Page
 * Shows user's enrolled courses with progress and gamification stats
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  BookOpen,
  Clock,
  CheckCircle,
  Play,
  Trophy,
  Flame,
  Zap,
  Award,
  TrendingUp,
  Loader2,
} from 'lucide-react';
import { useEducationStore } from '../../../stores/educationStore';
import { XPProgress, StreakCounter, AchievementBadge } from '../../../components/education';
import type { EnrollmentWithCourse } from '../../../types/education.types';

type TabType = 'in_progress' | 'completed' | 'all';

export default function MyLearning() {
  const {
    myEnrollments,
    loadingEnrollments,
    gamificationSummary,
    loadingGamification,
    fetchMyEnrollments,
    fetchGamificationSummary,
  } = useEducationStore();

  const [activeTab, setActiveTab] = useState<TabType>('in_progress');

  useEffect(() => {
    fetchMyEnrollments();
    fetchGamificationSummary();
  }, [fetchMyEnrollments, fetchGamificationSummary]);

  const filteredEnrollments = myEnrollments.filter((enrollment) => {
    if (activeTab === 'all') return true;
    if (activeTab === 'completed') return enrollment.status === 'completed';
    return enrollment.status === 'active' && enrollment.progressPercentage < 100;
  });

  const stats = {
    inProgress: myEnrollments.filter(
      (e) => e.status === 'active' && e.progressPercentage < 100
    ).length,
    completed: myEnrollments.filter((e) => e.status === 'completed').length,
    total: myEnrollments.length,
  };

  const formatDuration = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    if (hours === 0) return `${minutes}m`;
    return `${hours}h`;
  };

  const EnrollmentCard: React.FC<{ enrollment: EnrollmentWithCourse }> = ({
    enrollment,
  }) => {
    const { course } = enrollment;
    const isCompleted = enrollment.status === 'completed';

    return (
      <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden hover:border-blue-500/50 transition-colors">
        {/* Thumbnail */}
        <div className="relative aspect-video bg-gray-900">
          {course.thumbnailUrl ? (
            <img
              src={course.thumbnailUrl}
              alt={course.title}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-600/20 to-purple-600/20">
              <BookOpen className="w-12 h-12 text-gray-600" />
            </div>
          )}

          {/* Progress Overlay */}
          <div className="absolute bottom-0 left-0 right-0 h-1.5 bg-gray-700">
            <div
              className={`h-full transition-all ${
                isCompleted ? 'bg-green-500' : 'bg-blue-500'
              }`}
              style={{ width: `${enrollment.progressPercentage}%` }}
            />
          </div>

          {/* Status Badge */}
          {isCompleted && (
            <div className="absolute top-3 right-3 px-2 py-1 bg-green-500 text-white text-xs font-semibold rounded flex items-center gap-1">
              <CheckCircle className="w-3 h-3" />
              Completado
            </div>
          )}
        </div>

        {/* Content */}
        <div className="p-4">
          <h3 className="font-semibold text-white mb-2 line-clamp-2">
            {course.title}
          </h3>

          {/* Progress Stats */}
          <div className="flex items-center gap-4 text-sm text-gray-400 mb-4">
            <span className="flex items-center gap-1">
              <BookOpen className="w-4 h-4" />
              {enrollment.completedLessons}/{enrollment.totalLessons}
            </span>
            <span className="flex items-center gap-1">
              <TrendingUp className="w-4 h-4" />
              {enrollment.progressPercentage.toFixed(0)}%
            </span>
            <span className="flex items-center gap-1">
              <Clock className="w-4 h-4" />
              {formatDuration(course.totalDuration)}
            </span>
          </div>

          {/* Last Accessed */}
          {enrollment.lastAccessedAt && (
            <p className="text-xs text-gray-500 mb-4">
              Último acceso:{' '}
              {new Date(enrollment.lastAccessedAt).toLocaleDateString('es-ES', {
                month: 'short',
                day: 'numeric',
              })}
            </p>
          )}

          {/* Action Button */}
          <Link
            to={`/education/courses/${course.slug}`}
            className={`w-full flex items-center justify-center gap-2 py-2.5 rounded-lg font-medium transition-colors ${
              isCompleted
                ? 'bg-gray-700 hover:bg-gray-600 text-white'
                : 'bg-blue-600 hover:bg-blue-500 text-white'
            }`}
          >
            <Play className="w-4 h-4" />
            {isCompleted ? 'Revisar Curso' : 'Continuar'}
          </Link>

          {/* Certificate */}
          {enrollment.certificateIssued && enrollment.certificateUrl && (
            <a
              href={enrollment.certificateUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-2 w-full flex items-center justify-center gap-2 py-2 text-sm text-yellow-400 hover:text-yellow-300"
            >
              <Award className="w-4 h-4" />
              Ver Certificado
            </a>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Mi Aprendizaje</h1>
        <p className="text-gray-400">
          Continúa donde lo dejaste y sigue progresando
        </p>
      </div>

      {/* Gamification Summary */}
      {gamificationSummary && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* XP Progress */}
          <XPProgress
            levelProgress={gamificationSummary.levelProgress}
            showDetails={false}
            size="md"
          />

          {/* Streak */}
          <StreakCounter streakStats={gamificationSummary.streak} />

          {/* Quick Stats */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-4">
            <h3 className="font-medium text-white mb-4 flex items-center gap-2">
              <Trophy className="w-5 h-5 text-yellow-400" />
              Estadísticas
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-3 bg-gray-900/50 rounded-lg">
                <div className="text-2xl font-bold text-white">
                  {gamificationSummary.stats.coursesCompleted}
                </div>
                <div className="text-xs text-gray-400">Cursos Completados</div>
              </div>
              <div className="text-center p-3 bg-gray-900/50 rounded-lg">
                <div className="text-2xl font-bold text-white">
                  {gamificationSummary.stats.lessonsCompleted}
                </div>
                <div className="text-xs text-gray-400">Lecciones</div>
              </div>
              <div className="text-center p-3 bg-gray-900/50 rounded-lg">
                <div className="text-2xl font-bold text-white">
                  {gamificationSummary.stats.quizzesPassed}
                </div>
                <div className="text-xs text-gray-400">Quizzes Pasados</div>
              </div>
              <div className="text-center p-3 bg-gray-900/50 rounded-lg">
                <div className="text-2xl font-bold text-white">
                  {gamificationSummary.stats.averageQuizScore.toFixed(0)}%
                </div>
                <div className="text-xs text-gray-400">Promedio Quiz</div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Recent Achievements */}
      {gamificationSummary?.achievements?.recent && gamificationSummary.achievements.recent.length > 0 && (
        <div>
          <h3 className="font-medium text-white mb-4 flex items-center gap-2">
            <Award className="w-5 h-5 text-purple-400" />
            Logros Recientes
          </h3>
          <div className="flex gap-4 overflow-x-auto pb-2">
            {gamificationSummary.achievements.recent.map((achievement) => (
              <div key={achievement.id} className="flex-shrink-0 w-64">
                <AchievementBadge achievement={achievement} size="sm" />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Course Tabs */}
      <div className="flex items-center gap-4 border-b border-gray-700">
        <button
          onClick={() => setActiveTab('in_progress')}
          className={`pb-3 px-1 font-medium transition-colors relative ${
            activeTab === 'in_progress'
              ? 'text-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          En Progreso ({stats.inProgress})
          {activeTab === 'in_progress' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-500" />
          )}
        </button>
        <button
          onClick={() => setActiveTab('completed')}
          className={`pb-3 px-1 font-medium transition-colors relative ${
            activeTab === 'completed'
              ? 'text-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          Completados ({stats.completed})
          {activeTab === 'completed' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-500" />
          )}
        </button>
        <button
          onClick={() => setActiveTab('all')}
          className={`pb-3 px-1 font-medium transition-colors relative ${
            activeTab === 'all'
              ? 'text-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          Todos ({stats.total})
          {activeTab === 'all' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-500" />
          )}
        </button>
      </div>

      {/* Enrollments Grid */}
      {loadingEnrollments ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
        </div>
      ) : filteredEnrollments.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredEnrollments.map((enrollment) => (
            <EnrollmentCard key={enrollment.id} enrollment={enrollment} />
          ))}
        </div>
      ) : (
        <div className="text-center py-12">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-800 mb-4">
            <BookOpen className="w-8 h-8 text-gray-500" />
          </div>
          <h3 className="text-lg font-medium text-white mb-2">
            {activeTab === 'in_progress'
              ? 'No tienes cursos en progreso'
              : activeTab === 'completed'
              ? 'Aún no has completado ningún curso'
              : 'No estás inscrito en ningún curso'}
          </h3>
          <p className="text-gray-400 mb-4">
            Explora nuestro catálogo y comienza a aprender
          </p>
          <Link
            to="/education/courses"
            className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
          >
            <BookOpen className="w-5 h-5" />
            Explorar Cursos
          </Link>
        </div>
      )}
    </div>
  );
}
