"use client";

import { useParams, useRouter } from "next/navigation";
import { Calendar, ArrowLeft, Clock, Share2 } from "lucide-react";
import { useState, useEffect } from "react";

type Article = {
  id: string;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  image: string;
  category: string;
  categoryColor: string;
  publishedAt: string | null;
};

export default function ArticleDetailPage() {
  const params = useParams();
  const router = useRouter();
  const slug = params.id as string;

  const [article, setArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [shareMessage, setShareMessage] = useState("");

  useEffect(() => {
    fetch(`/api/articles/${slug}`)
      .then((res) => {
        if (res.status === 404) { setNotFound(true); return null; }
        return res.json();
      })
      .then((data) => {
        if (data) setArticle(data);
        setLoading(false);
      })
      .catch(() => { setNotFound(true); setLoading(false); });
  }, [slug]);

  const formatDate = (dateString: string | null) => {
    if (!dateString) return "";
    return new Intl.DateTimeFormat("fr-FR", {
      day: "numeric", month: "long", year: "numeric",
    }).format(new Date(dateString));
  };

  const calculateReadingTime = (content: string) => {
    const text = content.replace(/<[^>]*>/g, "");
    return Math.ceil(text.split(/\s+/).length / 200);
  };

  const handleShare = async () => {
    try {
      if (navigator.share) {
        await navigator.share({ title: article?.title, url: window.location.href });
      } else {
        await navigator.clipboard.writeText(window.location.href);
        setShareMessage("Lien copié !");
        setTimeout(() => setShareMessage(""), 2000);
      }
    } catch {
      setShareMessage("Erreur");
      setTimeout(() => setShareMessage(""), 2000);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen">
        <div className="h-[50vh] bg-gray-200 animate-pulse" />
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 -mt-20 relative z-10">
          <div className="bg-white rounded-2xl shadow-2xl p-10 animate-pulse space-y-4">
            <div className="h-8 bg-gray-200 rounded w-3/4" />
            <div className="h-4 bg-gray-200 rounded w-1/2" />
            <div className="h-24 bg-gray-100 rounded" />
          </div>
        </div>
      </div>
    );
  }

  if (notFound || !article) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-800 mb-4">Article non trouvé</h1>
          <button onClick={() => router.push("/actualites")} className="text-[#4A7C59] hover:underline">
            Retour aux actualités
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Hero Image */}
      <section className="relative h-[50vh] sm:h-[60vh] overflow-hidden">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={article.image} alt={article.title} className="w-full h-full object-cover" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent" />

        <button
          onClick={() => router.push("/actualites")}
          className="absolute top-24 left-4 sm:left-8 z-10 flex items-center gap-2 text-white bg-black/30 hover:bg-black/50 backdrop-blur-sm px-4 py-2 rounded-lg transition-all"
        >
          <ArrowLeft size={18} />
          <span className="text-sm font-medium">Retour</span>
        </button>

        <span
          className="absolute top-24 right-4 sm:right-8 z-10 text-xs font-bold text-white px-4 py-2 rounded-lg shadow-lg"
          style={{ backgroundColor: article.categoryColor }}
        >
          {article.category}
        </span>
      </section>

      {/* Article Content */}
      <article className="relative -mt-20 z-10">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">

          {/* Title Card */}
          <div className="bg-white rounded-2xl shadow-2xl p-8 sm:p-10 mb-8">
            <h1 className="font-serif text-3xl sm:text-4xl lg:text-5xl font-bold text-[#2C3E50] leading-tight mb-6">
              {article.title}
            </h1>

            <div className="flex flex-wrap items-center justify-between gap-3 sm:gap-4 text-sm text-gray-600 pb-6 border-b border-gray-200">
              <div className="flex flex-wrap items-center gap-3 sm:gap-6">
                <span className="flex items-center gap-2">
                  <Calendar size={16} className="text-[#4A7C59]" />
                  {formatDate(article.publishedAt)}
                </span>
                <span className="flex items-center gap-2">
                  <Clock size={16} className="text-[#4A7C59]" />
                  {calculateReadingTime(article.content)} min de lecture
                </span>
              </div>
              <button
                onClick={handleShare}
                className="flex items-center gap-2 text-[#4A7C59] hover:text-[#3d6849] font-medium transition-colors relative"
              >
                <Share2 size={16} />
                <span className="hidden sm:inline">Partager</span>
                {shareMessage && (
                  <span className="absolute -top-8 right-0 bg-[#4A7C59] text-white text-xs px-3 py-1 rounded-lg whitespace-nowrap">
                    {shareMessage}
                  </span>
                )}
              </button>
            </div>

            <p className="text-lg text-gray-700 leading-relaxed mt-6 font-medium border-l-4 border-[#4A7C59] pl-6 bg-gray-50 py-4 rounded">
              {article.excerpt}
            </p>
          </div>

          {/* Article Body */}
          <div className="bg-white rounded-2xl shadow-lg overflow-hidden mb-12">
            <div className="p-8 sm:p-12">
              <div
                className="article-content"
                dangerouslySetInnerHTML={{ __html: article.content }}
              />
            </div>
          </div>

          <style jsx>{`
            .article-content { font-size: 1.0625rem; line-height: 1.8; color: #374151; }
            .article-content p { margin-bottom: 1.5rem; color: #1f2937; }
            .article-content h2 { font-family: Georgia, serif; font-size: 1.875rem; font-weight: 700; color: #2C3E50; margin-top: 3rem; margin-bottom: 1.25rem; padding-bottom: 0.75rem; border-bottom: 3px solid #4A7C59; display: inline-block; }
            .article-content h3 { font-family: Georgia, serif; font-size: 1.5rem; font-weight: 600; color: #2C3E50; margin-top: 2rem; margin-bottom: 1rem; }
            .article-content ul { margin: 1.5rem 0; padding-left: 0; list-style: none; }
            .article-content li { position: relative; padding-left: 2rem; margin-bottom: 1rem; line-height: 1.7; color: #374151; }
            .article-content li::before { content: ""; position: absolute; left: 0; top: 0.6rem; width: 0.5rem; height: 0.5rem; background: #4A7C59; border-radius: 50%; }
            .article-content strong { color: #4A7C59; font-weight: 600; }
            .article-content blockquote { margin: 2.5rem 0; padding: 1.5rem 2rem; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border-left: 4px solid #4A7C59; border-radius: 0 0.75rem 0.75rem 0; font-style: italic; color: #1f2937; }
            .article-content blockquote cite { display: block; margin-top: 1rem; font-size: 0.875rem; font-style: normal; color: #4A7C59; font-weight: 600; }
          `}</style>

          <div className="text-center pb-12">
            <button
              onClick={() => router.push("/actualites")}
              className="inline-flex items-center gap-2 text-[#4A7C59] hover:text-[#3d6849] font-semibold transition-colors"
            >
              <ArrowLeft size={18} />
              Retour aux actualités
            </button>
          </div>

        </div>
      </article>
    </>
  );
}
