"use client";

import React, { useEffect, useState } from "react";
import { useParams, notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, BookOpen, Home } from "lucide-react";

// Mapping des fichiers markdown
const DOC_FILES = {
  "readme": "README.md",
  "user-guide": "USER_GUIDE.md",
  "correlation-guide": "CORRELATION_GUIDE.md",
  "regression-guide": "REGRESSION_GUIDE.md",
  "outlier-guide": "OUTLIER_GUIDE.md",
};

export default function DocsPage() {
  const params = useParams();
  const slug = params.slug as string[];
  const [content, setContent] = useState<string>("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadDoc = async () => {
      try {
        const docName = slug[0]?.toLowerCase();
        const fileName = DOC_FILES[docName as keyof typeof DOC_FILES] || `${docName}.md`;

        const response = await fetch(`/docs/${fileName}`);
        if (!response.ok) {
          throw new Error("Document non trouvé");
        }

        const text = await response.text();
        setContent(text);
      } catch (e: any) {
        setError(e.message);
      } finally {
        setLoading(false);
      }
    };

    loadDoc();
  }, [slug]);

  // Gérer l'ancre (hash) pour faire défiler jusqu'à la section
  useEffect(() => {
    if (typeof window !== "undefined" && window.location.hash && content) {
      setTimeout(() => {
        const hash = window.location.hash.replace("#", "");
        let element = document.getElementById(hash);

        if (!element) {
          const headings = document.querySelectorAll("h2, h3");
          for (const heading of headings) {
            const text = heading.textContent || "";
            const slug = text
              .toLowerCase()
              .normalize("NFD")
              .replace(/[\u0300-\u036f]/g, "")
              .replace(/[^a-z0-9\s-]/g, "")
              .trim()
              .replace(/\s+/g, "-");
            if (slug === hash) {
              element = heading as HTMLElement;
              break;
            }
          }
        }

        if (element) {
          element.scrollIntoView({ behavior: "smooth", block: "start" });
        }
      }, 300);
    }
  }, [content]);

  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mx-auto mb-4" />
          <p className="text-slate-500">Chargement de la documentation...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return notFound();
  }

  // Convertisseur Markdown robuste
  const parseMarkdown = (md: string): string => {
    const lines = md.split('\n');
    const output: string[] = [];
    let inCodeBlock = false;
    let codeBlockContent: string[] = [];
    let codeBlockLang = '';
    let inTable = false;
    let tableHeader: string[] = [];
    let tableRows: string[][] = [];
    let inList = false;
    let listType: 'ul' | 'ol' = 'ul';
    let listItems: string[] = [];

    const flushList = () => {
      if (inList && listItems.length > 0) {
        const tag = listType;
        const className = listType === 'ul' ? 'list-disc' : 'list-decimal';
        output.push(`<ul class="my-4 ml-6 space-y-2 ${className}">${listItems.join('')}</ul>`);
        listItems = [];
      }
      inList = false;
    };

    const flushTable = () => {
      if (inTable && tableHeader.length > 0) {
        let tableHtml = '<div class="overflow-x-auto my-6 rounded-lg border border-slate-300"><table class="min-w-full border-collapse">';
        tableHtml += '<thead class="bg-slate-50"><tr>';
        tableHeader.forEach(cell => {
          tableHtml += `<th class="px-4 py-2 text-left font-semibold text-slate-900 border-b border-slate-300">${parseInline(cell)}</th>`;
        });
        tableHtml += '</tr></thead><tbody>';
        tableRows.forEach(row => {
          tableHtml += '<tr class="hover:bg-slate-50">';
          row.forEach(cell => {
            tableHtml += `<td class="px-4 py-2 text-slate-700 border-b border-slate-200">${parseInline(cell)}</td>`;
          });
          tableHtml += '</tr>';
        });
        tableHtml += '</tbody></table></div>';
        output.push(tableHtml);
        tableHeader = [];
        tableRows = [];
      }
      inTable = false;
    };

    const parseInline = (text: string): string => {
      let result = text;

      // Code inline - doit être fait AVANT le bold pour éviter les conflits
      result = result.replace(/`([^`]+)`/g, '<code class="bg-slate-100 text-rose-600 px-1.5 py-0.5 rounded text-sm font-mono">$1</code>');

      // Bold et italic combiné
      result = result.replace(/\*\*\*([^*]+)\*\*\*/g, '<strong><em>$1</em></strong>');

      // Bold
      result = result.replace(/\*\*([^*]+)\*\*/g, '<strong class="font-semibold text-slate-900">$1</strong>');

      // Italic - utiliser une approche plus simple pour éviter les lookbehind
      // Remplacer *text* par <em> seulement si pas déjà dans <strong>
      result = result.replace(/\*([^*]+)\*/g, '<em>$1</em>');

      // Conserver les emojis et caractères spéciaux
      result = result.replace(/✅/g, '✅');
      result = result.replace(/❌/g, '❌');
      result = result.replace(/⚠️/g, '⚠️');
      result = result.replace(/📊/g, '📊');
      result = result.replace(/📈/g, '📈');
      result = result.replace(/🔍/g, '🔍');
      result = result.replace(/🎯/g, '🎯');
      result = result.replace(/⭐/g, '⭐');
      result = result.replace(/📐/g, '📐');
      result = result.replace(/💡/g, '💡');
      result = result.replace(/🎓/g, '🎓');
      result = result.replace(/🔴/g, '🔴');
      result = result.replace(/🟣/g, '🟣');

      // Liens
      result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
        if (url.startsWith('#')) {
          return `<a href="${url}" class="text-indigo-600 hover:text-indigo-700 underline">${text}</a>`;
        } else if (url.endsWith('.md')) {
          const docName = url.replace('.md', '').replace('docs/', '').toLowerCase();
          const mappedName = Object.keys(DOC_FILES).find(
            key => DOC_FILES[key as keyof typeof DOC_FILES] === url.replace('docs/', '')
          ) || docName;
          return `<a href="/docs/${mappedName}" class="text-indigo-600 hover:text-indigo-700 underline">${text}</a>`;
        } else {
          return `<a href="${url}" class="text-indigo-600 hover:text-indigo-700 underline" target="_blank" rel="noopener noreferrer">${text}</a>`;
        }
      });

      // Math inline
      result = result.replace(/\$([^$]+)\$/g, '<span class="font-mono text-sm bg-slate-100 px-1 rounded">$1</span>');

      return result;
    };

    const createId = (text: string): string => {
      return text
        .toLowerCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-z0-9\s-]/g, '')
        .trim()
        .replace(/\s+/g, '-');
    };

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];

      // Code blocks
      if (line.startsWith('```')) {
        if (inCodeBlock) {
          // End code block
          const code = codeBlockContent.join('\n');
          const escaped = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
          output.push(`<pre class="bg-slate-800 text-slate-100 p-4 rounded-lg overflow-x-auto my-4 text-sm"><code>${escaped}</code></pre>`);
          codeBlockContent = [];
          inCodeBlock = false;
        } else {
          // Start code block
          flushList();
          flushTable();
          codeBlockLang = line.slice(3).trim();
          inCodeBlock = true;
        }
        continue;
      }

      if (inCodeBlock) {
        codeBlockContent.push(line);
        continue;
      }

      // Table separator
      if (inTable && line.trim().startsWith('|---')) {
        continue; // Skip separator line
      }

      // Table rows
      if (line.trim().startsWith('|') && line.trim().endsWith('|')) {
        if (!inTable) {
          flushList();
          inTable = true;
        }
        const cells = line.split('|').slice(1, -1).map(c => c.trim());
        if (tableHeader.length === 0) {
          tableHeader = cells;
        } else {
          tableRows.push(cells);
        }
        continue;
      }

      // Not in table anymore
      if (inTable) {
        flushTable();
      }

      // Headers
      const h1Match = line.match(/^#\s+(.+)$/);
      if (h1Match) {
        flushList();
        const text = parseInline(h1Match[1]);
        const id = createId(h1Match[1]);
        output.push(`<h1 id="${id}" class="text-4xl font-bold text-slate-900 mt-8 mb-6">${text}</h1>`);
        continue;
      }

      const h2Match = line.match(/^##\s+(.+)$/);
      if (h2Match) {
        flushList();
        const text = parseInline(h2Match[1]);
        const id = createId(h2Match[1]);
        output.push(`<h2 id="${id}" class="text-2xl font-bold text-slate-900 mt-10 mb-6 pb-2 border-b border-slate-200">${text}</h2>`);
        continue;
      }

      const h3Match = line.match(/^###\s+(.+)$/);
      if (h3Match) {
        flushList();
        const text = parseInline(h3Match[1]);
        const id = createId(h3Match[1]);
        output.push(`<h3 id="${id}" class="text-xl font-bold text-slate-800 mt-8 mb-4">${text}</h3>`);
        continue;
      }

      // Horizontal rule
      if (line.trim() === '---' || line.trim() === '***') {
        flushList();
        output.push('<hr class="my-8 border-slate-200" />');
        continue;
      }

      // Blockquote
      if (line.trim().startsWith('>')) {
        flushList();
        const text = parseInline(line.trim().slice(1).trim());
        output.push(`<blockquote class="border-l-4 border-indigo-400 pl-4 py-2 my-4 bg-indigo-50 text-slate-700 italic">${text}</blockquote>`);
        continue;
      }

      // List items starting with emojis (✅, ❌, etc.) - doit être AVANT les listes normales
      const emojiListMatch = line.match(/^[\s]*(✅|❌|⚠️|📊|📈|🔍|🎯|⭐|📐|💡|🎓|🔴|🟣)\s+(.+)$/);
      if (emojiListMatch) {
        if (!inList || listType !== 'ul') {
          flushList();
          inList = true;
          listType = 'ul';
        }
        listItems.push(`<li class="text-slate-700 flex items-start gap-2"><span>${emojiListMatch[1]}</span><span>${parseInline(emojiListMatch[2])}</span></li>`);
        continue;
      }

      // Unordered list
      const ulMatch = line.match(/^[\s]*[-*]\s+(.+)$/);
      if (ulMatch) {
        if (!inList || listType !== 'ul') {
          flushList();
          inList = true;
          listType = 'ul';
        }
        listItems.push(`<li class="text-slate-700">${parseInline(ulMatch[1])}</li>`);
        continue;
      }

      // Ordered list
      const olMatch = line.match(/^[\s]*(\d+)\.\s+(.+)$/);
      if (olMatch) {
        if (!inList || listType !== 'ol') {
          flushList();
          inList = true;
          listType = 'ol';
        }
        listItems.push(`<li class="text-slate-700">${parseInline(olMatch[2])}</li>`);
        continue;
      }

      // Not a list item
      if (inList) {
        flushList();
      }

      // Empty line
      if (line.trim() === '') {
        output.push('');
        continue;
      }

      // Regular paragraph
      output.push(`<p class="my-4 text-slate-700 leading-relaxed">${parseInline(line)}</p>`);
    }

    // Flush remaining content
    flushList();
    flushTable();

    // Math blocks
    let result = output.join('\n');
    result = result.replace(/\$\$([^$]+)\$\$/g, (match, math) => {
      return `<div class="my-4 p-4 bg-slate-50 rounded-lg overflow-x-auto"><span class="font-mono text-sm">${math.trim()}</span></div>`;
    });

    return result;
  };

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 sticky top-0 z-50 shadow-sm">
        <div className="max-w-4xl mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link
              href="/"
              className="flex items-center gap-2 text-slate-600 hover:text-indigo-600 transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
              Retour
            </Link>
            <div className="h-6 w-px bg-slate-200" />
            <div className="flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-indigo-600" />
              <span className="font-semibold text-slate-900">Documentation</span>
            </div>
          </div>
          <Link
            href="/"
            className="flex items-center gap-2 text-sm text-slate-500 hover:text-indigo-600 transition-colors"
          >
            <Home className="w-4 h-4" />
            Accueil
          </Link>
        </div>
      </header>

      {/* Content */}
      <main className="max-w-4xl mx-auto px-6 py-12">
        <article
          className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8 md:p-12 prose prose-slate max-w-none"
          dangerouslySetInnerHTML={{ __html: parseMarkdown(content) }}
        />

        {/* Footer */}
        <div className="mt-8 text-center">
          <Link
            href="/"
            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-semibold rounded-xl hover:from-indigo-700 hover:to-purple-700 transition-all shadow-md hover:shadow-lg"
          >
            <Home className="w-4 h-4" />
            Retour à l'application
          </Link>
        </div>
      </main>
    </div>
  );
}
