/**
 * RecommendedCourses Component
 * Displays recommended courses based on user progress and interests
 */

import React from 'react';
import { Link } from 'react-router-dom';
import {
  BookOpen,
  Clock,
  Star,
  Users,
  ChevronRight,
  Sparkles,
  TrendingUp,
  Zap,
} from 'lucide-react';
import type { CourseListItem } from '../../../types/education.types';

interface RecommendedCoursesProps {
  courses: CourseListItem[];
  title?: string;
  subtitle?: string;
  reason?: 'similar' | 'popular' | 'new' | 'continue' | 'trending';
  maxItems?: number;
  layout?: 'horizontal' | 'vertical' | 'compact';
  showViewAll?: boolean;
  viewAllLink?: string;
  loading?: boolean;
}

const difficultyColors = {
  beginner: 'bg-green-500/20 text-green-400',
  intermediate: 'bg-yellow-500/20 text-yellow-400',
  advanced: 'bg-red-500/20 text-red-400',
};

const difficultyLabels = {
  beginner: 'Principiante',
  intermediate: 'Intermedio',
  advanced: 'Avanzado',
};

const reasonIcons = {
  similar: <BookOpen className="w-4 h-4" />,
  popular: <TrendingUp className="w-4 h-4" />,
  new: <Sparkles className="w-4 h-4" />,
  continue: <ChevronRight className="w-4 h-4" />,
  trending: <Zap className="w-4 h-4" />,
};

const reasonLabels = {
  similar: 'Similar a tus cursos',
  popular: 'Mas populares',
  new: 'Nuevos cursos',
  continue: 'Continua aprendiendo',
  trending: 'En tendencia',
};

const RecommendedCourses: React.FC<RecommendedCoursesProps> = ({
  courses,
  title = 'Cursos Recomendados',
  subtitle,
  reason = 'popular',
  maxItems = 4,
  layout = 'horizontal',
  showViewAll = true,
  viewAllLink = '/education/courses',
  loading = false,
}) => {
  const displayCourses = courses.slice(0, maxItems);

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

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="h-7 w-48 bg-gray-700 rounded animate-pulse" />
          <div className="h-5 w-20 bg-gray-700 rounded animate-pulse" />
        </div>
        <div className={`grid gap-4 ${layout === 'horizontal' ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4' : 'grid-cols-1'}`}>
          {[...Array(maxItems)].map((_, i) => (
            <div key={i} className="bg-gray-800 rounded-xl border border-gray-700 p-4 animate-pulse">
              <div className="aspect-video bg-gray-700 rounded-lg mb-4" />
              <div className="h-5 bg-gray-700 rounded w-3/4 mb-2" />
              <div className="h-4 bg-gray-700 rounded w-1/2" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (courses.length === 0) {
    return null;
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <span className="text-blue-400">{reasonIcons[reason]}</span>
            <h3 className="text-lg font-bold text-white">{title}</h3>
          </div>
          {subtitle && <p className="text-sm text-gray-400 mt-0.5">{subtitle}</p>}
        </div>
        {showViewAll && (
          <Link
            to={viewAllLink}
            className="flex items-center gap-1 text-sm text-blue-400 hover:text-blue-300 transition-colors"
          >
            Ver todos
            <ChevronRight className="w-4 h-4" />
          </Link>
        )}
      </div>

      {/* Reason Badge */}
      <div className="inline-flex items-center gap-2 px-3 py-1 bg-blue-500/10 border border-blue-500/20 rounded-full">
        {reasonIcons[reason]}
        <span className="text-xs text-blue-400">{reasonLabels[reason]}</span>
      </div>

      {/* Courses Grid */}
      {layout === 'compact' ? (
        <div className="space-y-2">
          {displayCourses.map((course) => (
            <CompactCourseCard key={course.id} course={course} />
          ))}
        </div>
      ) : layout === 'vertical' ? (
        <div className="space-y-4">
          {displayCourses.map((course) => (
            <VerticalCourseCard key={course.id} course={course} />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {displayCourses.map((course) => (
            <HorizontalCourseCard key={course.id} course={course} />
          ))}
        </div>
      )}
    </div>
  );
};

// Horizontal Card (Default)
const HorizontalCourseCard: React.FC<{ course: CourseListItem }> = ({ course }) => {
  const formatDuration = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    return hours > 0 ? `${hours}h` : `${minutes}m`;
  };

  return (
    <Link
      to={`/education/courses/${course.slug}`}
      className="group bg-gray-800 rounded-xl border border-gray-700 overflow-hidden hover:border-gray-600 transition-all hover:shadow-lg"
    >
      {/* 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 group-hover:scale-105 transition-transform duration-300"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <BookOpen className="w-10 h-10 text-gray-600" />
          </div>
        )}
        {course.isFree && (
          <span className="absolute top-2 right-2 px-2 py-0.5 bg-green-500 text-white text-xs font-medium rounded">
            GRATIS
          </span>
        )}
        <div className="absolute bottom-2 right-2 px-2 py-0.5 bg-black/70 text-white text-xs rounded">
          {formatDuration(course.totalDuration)}
        </div>
      </div>

      {/* Content */}
      <div className="p-4">
        <span className={`inline-block px-2 py-0.5 text-xs rounded mb-2 ${difficultyColors[course.difficultyLevel]}`}>
          {difficultyLabels[course.difficultyLevel]}
        </span>
        <h4 className="font-medium text-white line-clamp-2 mb-2 group-hover:text-blue-400 transition-colors">
          {course.title}
        </h4>
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center gap-1 text-yellow-400">
            <Star className="w-4 h-4 fill-yellow-400" />
            <span>{course.avgRating.toFixed(1)}</span>
          </div>
          <span className="text-gray-500">{course.totalLessons} lecciones</span>
        </div>
      </div>
    </Link>
  );
};

// Vertical Card (List view)
const VerticalCourseCard: React.FC<{ course: CourseListItem }> = ({ course }) => {
  const formatDuration = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (hours === 0) return `${mins} min`;
    return `${hours}h ${mins}m`;
  };

  return (
    <Link
      to={`/education/courses/${course.slug}`}
      className="group flex gap-4 p-4 bg-gray-800 rounded-xl border border-gray-700 hover:border-gray-600 transition-all"
    >
      {/* Thumbnail */}
      <div className="relative w-40 h-24 flex-shrink-0 rounded-lg overflow-hidden bg-gray-900">
        {course.thumbnailUrl ? (
          <img
            src={course.thumbnailUrl}
            alt={course.title}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <BookOpen className="w-8 h-8 text-gray-600" />
          </div>
        )}
        {course.isFree && (
          <span className="absolute top-1 left-1 px-1.5 py-0.5 bg-green-500 text-white text-xs font-medium rounded">
            GRATIS
          </span>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <h4 className="font-medium text-white line-clamp-2 group-hover:text-blue-400 transition-colors">
            {course.title}
          </h4>
          <span className={`flex-shrink-0 px-2 py-0.5 text-xs rounded ${difficultyColors[course.difficultyLevel]}`}>
            {difficultyLabels[course.difficultyLevel]}
          </span>
        </div>
        {course.shortDescription && (
          <p className="text-sm text-gray-400 line-clamp-1 mt-1">{course.shortDescription}</p>
        )}
        <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
          <div className="flex items-center gap-1">
            <Clock className="w-4 h-4" />
            {formatDuration(course.totalDuration)}
          </div>
          <div className="flex items-center gap-1">
            <BookOpen className="w-4 h-4" />
            {course.totalLessons} lecciones
          </div>
          <div className="flex items-center gap-1 text-yellow-400">
            <Star className="w-4 h-4 fill-yellow-400" />
            {course.avgRating.toFixed(1)}
          </div>
          <div className="flex items-center gap-1">
            <Users className="w-4 h-4" />
            {course.totalEnrollments.toLocaleString()}
          </div>
        </div>
      </div>
    </Link>
  );
};

// Compact Card (Sidebar)
const CompactCourseCard: React.FC<{ course: CourseListItem }> = ({ course }) => (
  <Link
    to={`/education/courses/${course.slug}`}
    className="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-700/50 transition-colors group"
  >
    {/* Thumbnail */}
    <div className="w-12 h-12 flex-shrink-0 rounded-lg overflow-hidden bg-gray-700">
      {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">
          <BookOpen className="w-5 h-5 text-gray-500" />
        </div>
      )}
    </div>

    {/* Content */}
    <div className="flex-1 min-w-0">
      <h4 className="font-medium text-sm text-white truncate group-hover:text-blue-400 transition-colors">
        {course.title}
      </h4>
      <div className="flex items-center gap-2 mt-0.5">
        <div className="flex items-center gap-0.5 text-yellow-400">
          <Star className="w-3 h-3 fill-yellow-400" />
          <span className="text-xs">{course.avgRating.toFixed(1)}</span>
        </div>
        <span className="text-xs text-gray-500">{course.totalLessons} lecciones</span>
      </div>
    </div>

    {/* Price/Free badge */}
    {course.isFree ? (
      <span className="px-2 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">
        Gratis
      </span>
    ) : course.priceUsd ? (
      <span className="text-sm font-medium text-white">
        ${course.priceUsd}
      </span>
    ) : null}
  </Link>
);

export default RecommendedCourses;
