/**
 * Courses Page
 * Displays course catalog with filters and search
 */

import React, { useEffect, useState } from 'react';
import { Search, Filter, X, Loader2 } from 'lucide-react';
import { useEducationStore } from '../../../stores/educationStore';
import { CourseCard } from '../../../components/education';
import type { DifficultyLevel, CourseFilters } from '../../../types/education.types';

const difficultyOptions: { value: DifficultyLevel | ''; label: string }[] = [
  { value: '', label: 'Todos los niveles' },
  { value: 'beginner', label: 'Principiante' },
  { value: 'intermediate', label: 'Intermedio' },
  { value: 'advanced', label: 'Avanzado' },
];

const sortOptions = [
  { value: 'newest', label: 'Más recientes' },
  { value: 'popular', label: 'Más populares' },
  { value: 'rating', label: 'Mejor valorados' },
  { value: 'price_asc', label: 'Precio: menor a mayor' },
  { value: 'price_desc', label: 'Precio: mayor a menor' },
];

export default function Courses() {
  const {
    courses,
    categories,
    totalCourses,
    currentPage,
    pageSize,
    loadingCourses,
    loadingCategories,
    fetchCourses,
    fetchCategories,
    setFilters,
    filters,
  } = useEducationStore();

  const [searchTerm, setSearchTerm] = useState('');
  const [selectedLevel, setSelectedLevel] = useState<DifficultyLevel | ''>('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [sortBy, setSortBy] = useState<CourseFilters['sortBy']>('newest');
  const [showFreeOnly, setShowFreeOnly] = useState(false);

  // Load initial data
  useEffect(() => {
    fetchCategories();
    fetchCourses();
  }, [fetchCategories, fetchCourses]);

  // Apply filters when they change
  useEffect(() => {
    const newFilters: CourseFilters = {
      search: searchTerm || undefined,
      level: selectedLevel || undefined,
      categoryId: selectedCategory || undefined,
      sortBy,
      isFree: showFreeOnly || undefined,
      page: 1,
      pageSize: 12,
    };
    setFilters(newFilters);
    fetchCourses(newFilters);
  }, [searchTerm, selectedLevel, selectedCategory, sortBy, showFreeOnly, setFilters, fetchCourses]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchCourses({ ...filters, search: searchTerm, page: 1 });
  };

  const handlePageChange = (page: number) => {
    fetchCourses({ ...filters, page });
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedLevel('');
    setSelectedCategory('');
    setSortBy('newest');
    setShowFreeOnly(false);
  };

  const hasActiveFilters =
    searchTerm || selectedLevel || selectedCategory || showFreeOnly || sortBy !== 'newest';

  const totalPages = Math.ceil(totalCourses / pageSize);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Cursos de Trading</h1>
        <p className="text-gray-400">
          Aprende trading con contenido generado por IA y expertos del mercado
        </p>
      </div>

      {/* Search and Filters */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-4">
        <form onSubmit={handleSearch} className="flex flex-col lg:flex-row gap-4">
          {/* Search Input */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Buscar cursos..."
              className="w-full pl-10 pr-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
            />
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-3">
            {/* Category */}
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none"
            >
              <option value="">Todas las categorías</option>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>
                  {cat.name}
                </option>
              ))}
            </select>

            {/* Level */}
            <select
              value={selectedLevel}
              onChange={(e) => setSelectedLevel(e.target.value as DifficultyLevel | '')}
              className="px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none"
            >
              {difficultyOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>

            {/* Sort */}
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as CourseFilters['sortBy'])}
              className="px-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:border-blue-500 focus:outline-none"
            >
              {sortOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>

            {/* Free Only Toggle */}
            <button
              type="button"
              onClick={() => setShowFreeOnly(!showFreeOnly)}
              className={`px-4 py-2.5 rounded-lg border font-medium transition-colors ${
                showFreeOnly
                  ? 'bg-green-500/20 border-green-500/50 text-green-400'
                  : 'bg-gray-900 border-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              Gratis
            </button>

            {/* Clear Filters */}
            {hasActiveFilters && (
              <button
                type="button"
                onClick={clearFilters}
                className="px-4 py-2.5 text-gray-400 hover:text-white flex items-center gap-2"
              >
                <X className="w-4 h-4" />
                Limpiar
              </button>
            )}
          </div>
        </form>

        {/* Results Count */}
        <div className="mt-4 flex items-center justify-between text-sm text-gray-400">
          <span>
            {loadingCourses ? 'Buscando...' : `${totalCourses} cursos encontrados`}
          </span>
          {hasActiveFilters && (
            <span className="flex items-center gap-1">
              <Filter className="w-4 h-4" />
              Filtros activos
            </span>
          )}
        </div>
      </div>

      {/* Course Grid */}
      {loadingCourses ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
        </div>
      ) : courses.length > 0 ? (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {courses.map((course) => (
              <CourseCard key={course.id} course={course} />
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2">
              <button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage <= 1}
                className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Anterior
              </button>

              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum: number;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }

                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`w-10 h-10 rounded-lg font-medium transition-colors ${
                        currentPage === pageNum
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-800 text-gray-400 hover:text-white'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
              </div>

              <button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage >= totalPages}
                className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Siguiente
              </button>
            </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">
            <Search className="w-8 h-8 text-gray-500" />
          </div>
          <h3 className="text-lg font-medium text-white mb-2">
            No se encontraron cursos
          </h3>
          <p className="text-gray-400 mb-4">
            Intenta ajustar tus filtros o buscar con otros términos
          </p>
          {hasActiveFilters && (
            <button
              onClick={clearFilters}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
            >
              Limpiar filtros
            </button>
          )}
        </div>
      )}
    </div>
  );
}
