"use client";

import { useEffect, useState } from "react";

interface Heading {
  id: string;
  text: string;
  level: number;
}

interface TableOfContentsProps {
  lang: "ar" | "en";
}

export default function TableOfContents({ lang }: TableOfContentsProps) {
  const [headings, setHeadings] = useState<Heading[]>([]);
  const [activeId, setActiveId] = useState<string>("");
  const [isOpen, setIsOpen] = useState(true);

  const isAr = lang === "ar";
  const title = isAr ? "محتويات المقال" : "Table of Contents";
  const toggleText = isAr ? "إخفاء" : "Hide";
  const showText = isAr ? "إظهار" : "Show";

  useEffect(() => {
    const article = document.querySelector("article");
    if (!article) return;

    const headingElements = article.querySelectorAll("h2, h3, h4");
    const extractedHeadings: Heading[] = [];

    headingElements.forEach((heading, index) => {
      let id = heading.id;
      if (!id) {
        id = "heading-" + index;
        heading.id = id;
      }

      extractedHeadings.push({
        id,
        text: heading.textContent || "",
        level: parseInt(heading.tagName[1]),
      });
    });

    setHeadings(extractedHeadings);

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      {
        rootMargin: "-100px 0px -66%",
      },
    );

    headingElements.forEach((heading) => {
      observer.observe(heading);
    });

    return () => {
      headingElements.forEach((heading) => {
        observer.unobserve(heading);
      });
    };
  }, []);

  const scrollToHeading = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      const offset = 100;
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.scrollY - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth",
      });
    }
  };

  if (headings.length === 0) {
    return null;
  }

  return (
    <div className="sticky top-24 bg-white dark:bg-slate-800 rounded-2xl border-2 border-gray-200 dark:border-slate-700 shadow-xl overflow-hidden">
      <div className="bg-gradient-to-r from-brand-green to-emerald-600 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-white/20 backdrop-blur-sm rounded-lg flex items-center justify-center">
              <svg
                className="w-5 h-5 text-white"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 6h16M4 12h16M4 18h7"
                />
              </svg>
            </div>
            <h3 className="font-bold text-white text-lg">{title}</h3>
          </div>
          <button
            onClick={() => setIsOpen(!isOpen)}
            className="text-white/90 hover:text-white transition-colors text-sm font-medium flex items-center gap-1"
          >
            {isOpen ? toggleText : showText}
            <svg
              className={
                "w-4 h-4 transition-transform duration-300 " +
                (isOpen ? "rotate-180" : "")
              }
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </button>
        </div>
      </div>

      {isOpen && (
        <nav className="p-4 max-h-[500px] overflow-y-auto">
          <ul className="space-y-1">
            {headings.map((heading) => {
              const isActive = activeId === heading.id;
              const indent = (heading.level - 2) * 20;

              return (
                <li key={heading.id} style={{ paddingLeft: indent + "px" }}>
                  <button
                    onClick={() => scrollToHeading(heading.id)}
                    className={
                      "w-full text-left px-4 py-2.5 rounded-lg transition-all duration-200 group " +
                      (isActive
                        ? "bg-gradient-to-r from-brand-green to-emerald-600 text-white shadow-md scale-105"
                        : "text-gray-700 dark:text-gray-300 hover:bg-brand-green/10 hover:text-brand-green dark:hover:text-brand-green")
                    }
                  >
                    <div className="flex items-start gap-2">
                      <span
                        className={
                          "flex-shrink-0 w-1.5 h-1.5 rounded-full mt-2 transition-all duration-200 " +
                          (isActive
                            ? "bg-white"
                            : "bg-gray-400 dark:bg-gray-600 group-hover:bg-brand-green")
                        }
                      />
                      <span
                        className={
                          "text-sm leading-relaxed " +
                          (isActive ? "font-semibold" : "font-medium")
                        }
                      >
                        {heading.text}
                      </span>
                    </div>
                  </button>
                </li>
              );
            })}
          </ul>
        </nav>
      )}

      {isOpen && (
        <div className="px-6 py-3 bg-gray-50 dark:bg-slate-900/50 border-t border-gray-200 dark:border-slate-700">
          <div className="flex items-center justify-between text-xs text-gray-600 dark:text-gray-400 mb-2">
            <span className="font-medium">
              {isAr ? "تقدم القراءة" : "Reading Progress"}
            </span>
            <span className="font-bold text-brand-green">
              {headings.findIndex((h) => h.id === activeId) + 1} /{" "}
              {headings.length}
            </span>
          </div>
          <div className="h-1.5 bg-gray-200 dark:bg-slate-700 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-brand-green to-emerald-500 transition-all duration-500 ease-out"
              style={{
                width:
                  ((headings.findIndex((h) => h.id === activeId) + 1) /
                    headings.length) *
                    100 +
                  "%",
              }}
            />
          </div>
        </div>
      )}
    </div>
  );
}
