import { useState, useEffect } from 'react';
import { Link, useParams } from 'react-router-dom';
import { ChevronLeft, ChevronRight, BookOpen, Loader2, AlertTriangle } from 'lucide-react';
import ReactMarkdown from 'react-markdown';

const ManualViewer = () => {
  const { path } = useParams();
  const [content, setContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // El path viene del router (ej: 'parte-1/bloque-1/1.1.1').
  // En este proyecto, los MD están en public/manual
  const filePath = path ? `/manual/${path}.md` : null;

  useEffect(() => {
    if (!filePath) {
      setError('No se ha especificado un capítulo');
      setLoading(false);
      return;
    }

    const loadMarkdown = async () => {
      setLoading(true);
      try {
        const response = await fetch(filePath);
        if (!response.ok) {
          throw new Error('No se pudo cargar el capítulo del manual');
        }
        const text = await response.text();
        setContent(text);
        setError(null);
      } catch (err) {
        console.error('Error loading manual:', err);
        setError(err instanceof Error ? err.message : 'Error cargando manual');
      } finally {
        setLoading(false);
      }
    };

    loadMarkdown();
  }, [filePath]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !content) {
    return (
      <div className="text-center py-12 space-y-4">
        <AlertTriangle className="w-12 h-12 mx-auto text-destructive/50" />
        <h3 className="text-lg font-medium">Error al cargar</h3>
        <p className="text-muted-foreground">{error}</p>
        <Link to="/manual" className="inline-block text-primary hover:underline">
          Volver al índice
        </Link>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Back Button */}
      <div className="flex items-center gap-2">
        <Link to="/manual" className="p-2 hover:bg-muted rounded-full transition-colors">
          <ChevronLeft className="w-6 h-6" />
        </Link>
        <div className="text-xs text-muted-foreground uppercase tracking-wider font-semibold">
          Manual Digital TES
        </div>
      </div>

      {/* Contenido Markdown */}
      <div className="bg-card border border-border rounded-xl p-6 sm:p-10 shadow-sm">
        <article className="prose prose-slate dark:prose-invert max-w-none 
          prose-headings:font-bold prose-headings:text-foreground
          prose-p:text-muted-foreground prose-li:text-muted-foreground
          prose-strong:text-foreground prose-code:text-primary">
          <ReactMarkdown>{content}</ReactMarkdown>
        </article>
      </div>

      {/* Footer Nav (Placeholder - en una impl real usaríamos un índice JSON) */}
      <div className="flex justify-between items-center pt-8">
        <Link to="/manual" className="text-sm text-muted-foreground hover:text-primary transition-colors">
          ← Menú del Manual
        </Link>
        <button 
          onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
          className="text-sm text-muted-foreground hover:text-primary transition-colors"
        >
          Subir ↑
        </button>
      </div>
    </div>
  );
};

export default ManualViewer;