'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Plus,
  Edit,
  Eye,
  EyeOff,
  Trash2,
  BookOpen,
  Search,
  RefreshCw,
} from 'lucide-react';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/EmptyState';
import type { ModuleType } from '@/types';

interface Module {
  id: string;
  name: string;
  description: string;
  type: ModuleType;
  order: number;
  isPublished: boolean;
  createdAt: string;
  updatedAt: string;
  exerciseCount?: number;
}

export default function AdminModulesPage() {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [modules, setModules] = useState<Module[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterPublished, setFilterPublished] = useState<'all' | 'published' | 'unpublished'>('all');

  useEffect(() => {
    void fetchModules();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchModules = async () => {
    try {
      setIsLoading(true);
      const data = await api.get<{ data: Module[]; meta?: { pagination?: { total: number } } }>(
        apiEndpoints.modules.list + '?isPublished=all'
      );
      const modulesList = Array.isArray(data) ? data : ((data as Record<string, unknown>)['data'] as Module[]) || [];
      setModules(modulesList);
    } catch (error) {
      toast({
        title: 'Error al cargar módulos',
        description: error instanceof Error ? error.message : 'No se pudo cargar los módulos',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleTogglePublish = (_moduleId: string, _currentStatus: boolean) => {
    toast({
      title: 'Funcionalidad pendiente',
      description: 'El endpoint para publicar/despublicar módulos aún no está implementado.',
    });
  };

  const filteredModules = modules.filter(module => {
    const matchesSearch = module.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      module.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesFilter = filterPublished === 'all' ||
      (filterPublished === 'published' && module.isPublished) ||
      (filterPublished === 'unpublished' && !module.isPublished);
    return matchesSearch && matchesFilter;
  });

  const getTypeColor = (type: ModuleType) => {
    switch (type) {
      case 'FUNDAMENTOS':
        return 'bg-blue-500/10 text-blue-600 border-blue-500/20';
      case 'SISTEMAS':
        return 'bg-green-500/10 text-green-600 border-green-500/20';
      case 'APLICACIONES':
        return 'bg-purple-500/10 text-purple-600 border-purple-500/20';
      default:
        return 'bg-gray-500/10 text-gray-600 border-gray-500/20';
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-4 w-64 mt-2" />
          </div>
          <Skeleton className="h-10 w-32" />
        </div>
        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              {[1, 2, 3, 4, 5].map(i => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Gestión de Módulos</h1>
          <p className="text-muted-foreground">Administra los módulos de la plataforma</p>
        </div>
        <Button disabled>
          <Plus className="mr-2 h-4 w-4" />
          Nuevo Módulo
        </Button>
      </div>

      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                type="text"
                placeholder="Buscar módulos..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pl-10 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              />
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant={filterPublished === 'all' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('all')}
              >
                Todos
              </Button>
              <Button
                variant={filterPublished === 'published' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('published')}
              >
                Publicados
              </Button>
              <Button
                variant={filterPublished === 'unpublished' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('unpublished')}
              >
                No publicados
              </Button>
              <Button variant="ghost" size="icon" onClick={() => void fetchModules()}>
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <BookOpen className="h-5 w-5" />
            Módulos ({filteredModules.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {filteredModules.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Orden</TableHead>
                  <TableHead>Nombre</TableHead>
                  <TableHead>Tipo</TableHead>
                  <TableHead>Estado</TableHead>
                  <TableHead>Descripción</TableHead>
                  <TableHead className="text-right">Acciones</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredModules.map((module) => (
                  <TableRow key={module.id}>
                    <TableCell className="font-medium">{module.order}</TableCell>
                    <TableCell className="font-medium">{module.name}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className={getTypeColor(module.type)}>
                        {module.type}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={module.isPublished ? 'default' : 'secondary'}>
                        {module.isPublished ? 'Publicado' : 'No publicado'}
                      </Badge>
                    </TableCell>
                    <TableCell className="max-w-xs truncate text-muted-foreground">
                      {module.description}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleTogglePublish(module.id, module.isPublished)}
                          title={module.isPublished ? 'Despublicar' : 'Publicar'}
                        >
                          {module.isPublished ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </Button>
                        <Button variant="ghost" size="icon" disabled title="Editar">
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" disabled title="Eliminar">
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <EmptyState
              icon={<BookOpen className="h-12 w-12" />}
              title="No hay módulos"
              description="No se encontraron módulos con los filtros seleccionados."
            />
          )}
        </CardContent>
      </Card>

      <Card className="border-amber-500/20 bg-amber-500/5">
        <CardContent className="p-4">
          <p className="text-sm text-amber-600">
            <strong>Nota:</strong> Las acciones CRUD de módulos requieren endpoints en el backend que aún no están implementados.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
