'use client';

import { useEffect, useState } from 'react';
import { Search, SlidersHorizontal, BookOpen } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { EmptyState } from '@/components/ui/EmptyState';
import { ModuleCard } from '@/components/modules/ModuleCard';
import { useModuleStore } from '@/store/useModuleStore';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import type { Module, Progress } from '@/types';
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

export default function ModulesPage() {
  const { toast } = useToast();
  const { modules, setModules, progress, setProgress } = useModuleStore();
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
  const [filterStatus, setFilterStatus] = useState<'all' | 'in-progress' | 'completed'>('all');

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);

        // Fetch modules
        const modulesData = await api.get<Module[]>(apiEndpoints.modules.list);
        setModules(modulesData);

        // Fetch progress
        try {
          const progressResponse = await api.get<{
            totalPoints: number;
            totalExercisesCompleted: number;
            modules: Progress[];
          }>(apiEndpoints.progress.overview);
          setProgress(progressResponse.modules || []);
        } catch (error) {
          console.info('No progress data yet');
        }
      } catch (error) {
        toast({
          title: 'Error al cargar módulos',
          description: error instanceof Error ? error.message : 'No se pudieron cargar los módulos',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };

    void fetchData();
    if (modules.length === 0) {
      void fetchData();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const moduleTypes = Array.from(new Set(modules.map((m) => m.type)));

  const getModuleProgress = (moduleId: string) => {
    return progress.find((p) => p.moduleId === moduleId);
  };

  const filteredModules = modules.filter((module) => {
    // Search filter
    const matchesSearch =
      module.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      module.description.toLowerCase().includes(searchQuery.toLowerCase());

    // Type filter
    const matchesType =
      selectedTypes.length === 0 || selectedTypes.includes(module.type);

    // Status filter
    const moduleProgress = getModuleProgress(module.id);
    const matchesStatus =
      filterStatus === 'all' ||
      (filterStatus === 'in-progress' && moduleProgress?.isStarted && !moduleProgress?.isCompleted) ||
      (filterStatus === 'completed' && moduleProgress?.isCompleted);

    return matchesSearch && matchesType && matchesStatus;
  });

  const toggleTypeFilter = (type: string) => {
    setSelectedTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
  };

  const getStatusCount = (status: 'all' | 'in-progress' | 'completed') => {
    if (status === 'all') return modules.length;
    return modules.filter((m) => {
      const p = getModuleProgress(m.id);
      return status === 'in-progress' ? p?.isStarted && !p?.isCompleted : p?.isCompleted;
    }).length;
  };

  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          <p className="text-sm text-muted-foreground">Cargando módulos...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Módulos</h1>
        <p className="text-muted-foreground">
          Explora todos los módulos de Álgebra Lineal
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Total de módulos</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{modules.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">En progreso</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {modules.filter((m) => {
                const p = getModuleProgress(m.id);
                return p?.isStarted && !p?.isCompleted;
              }).length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Completados</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {modules.filter((m) => getModuleProgress(m.id)?.isCompleted).length}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Search and Filters */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            type="search"
            placeholder="Buscar módulos..."
            className="pl-10"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        <div className="flex items-center gap-2">
          {/* Status Filter */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <SlidersHorizontal className="mr-2 h-4 w-4" />
                Estado
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-48">
              <DropdownMenuLabel>Filtrar por estado</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuCheckboxItem
                checked={filterStatus === 'all'}
                onCheckedChange={() => setFilterStatus('all')}
              >
                Todos ({getStatusCount('all')})
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={filterStatus === 'in-progress'}
                onCheckedChange={() => setFilterStatus('in-progress')}
              >
                En progreso ({getStatusCount('in-progress')})
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={filterStatus === 'completed'}
                onCheckedChange={() => setFilterStatus('completed')}
              >
                Completados ({getStatusCount('completed')})
              </DropdownMenuCheckboxItem>
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Type Filter */}
          {moduleTypes.length > 0 && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm">
                  <BookOpen className="mr-2 h-4 w-4" />
                  Tipo
                  {selectedTypes.length > 0 && (
                    <span className="ml-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
                      {selectedTypes.length}
                    </span>
                  )}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuLabel>Filtrar por tipo</DropdownMenuLabel>
                <DropdownMenuSeparator />
                {moduleTypes.map((type) => (
                  <DropdownMenuCheckboxItem
                    key={type}
                    checked={selectedTypes.includes(type)}
                    onCheckedChange={() => toggleTypeFilter(type)}
                  >
                    {type}
                  </DropdownMenuCheckboxItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {(selectedTypes.length > 0 || filterStatus !== 'all') && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setSelectedTypes([]);
                setFilterStatus('all');
              }}
            >
              Limpiar filtros
            </Button>
          )}
        </div>
      </div>

      {/* Modules Grid */}
      {filteredModules.length > 0 ? (
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {filteredModules.map((module) => {
            const moduleProgress = getModuleProgress(module.id);
            return (
              <ModuleCard
                key={module.id}
                module={module}
                {...(moduleProgress !== undefined && { progress: moduleProgress })}
              />
            );
          })}
        </div>
      ) : (
        <Card>
          <CardContent>
            <EmptyState
              icon={<BookOpen className="h-12 w-12" />}
              title={
                searchQuery || selectedTypes.length > 0 || filterStatus !== 'all'
                  ? 'No se encontraron módulos'
                  : 'No hay módulos disponibles'
              }
              description={
                searchQuery || selectedTypes.length > 0 || filterStatus !== 'all'
                  ? 'Intenta con otros filtros de búsqueda'
                  : 'Los módulos estarán disponibles pronto.'
              }
              action={
                searchQuery || selectedTypes.length > 0 || filterStatus !== 'all'
                  ? {
                      label: 'Limpiar filtros',
                      onClick: () => {
                        setSearchQuery('');
                        setSelectedTypes([]);
                        setFilterStatus('all');
                      },
                    }
                  : undefined
              }
            />
          </CardContent>
        </Card>
      )}
    </div>
  );
}
