"use client";
import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import Image from "next/image";

type ArticleTag = {
  id: number;
  name: string;
};

type Article = {
  id?: number;
  title: string;
  content: string;
  tags: ArticleTag[];
  description?: string;
  date_creation: Date;
  image: {
    path: string;
  };
  author?: {
    id?: number;
    name?: string;
    email?: string;
    image?: string;
  };
};

function SkeletonArticle() {
  return (
    <main className="min-h-screen bg-white text-night animate-fade-in">
      {/* Hero Section Skeleton */}
      <div className="relative w-full h-72 sm:h-96 mb-8">
        <div className="absolute inset-0 bg-gray-200 animate-pulse rounded-lg" />
        <div className="absolute bottom-16 left-1/2 transform -translate-x-1/2 w-2/3 h-10 bg-gray-300 rounded mb-2 animate-pulse flex items-center justify-center text-2xl font-bold text-gray-400"></div>
        <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 w-1/3 h-6 bg-gray-200 rounded animate-pulse" />
      </div>
      <div className="max-w-3xl mx-auto px-4 py-12 mb-20">
        {/* Title skeleton (if no image) */}
        <div className="mb-8 flex flex-col items-center">
          <div className="w-1/3 h-6 bg-gray-200 rounded mb-2 animate-pulse" />
          <div className="w-20 h-1 bg-gradient-to-r from-blue-200 to-purple-200 rounded-full mb-4 animate-pulse" />
        </div>
        {/* Content skeleton */}
        <div className="space-y-4">
          <div className="w-full h-6 bg-gray-200 rounded animate-pulse" />
          <div className="w-5/6 h-6 bg-gray-200 rounded animate-pulse" />
          <div className="w-4/6 h-6 bg-gray-200 rounded animate-pulse" />
          <div className="w-3/6 h-6 bg-gray-200 rounded animate-pulse" />
          <div className="w-full h-6 bg-gray-200 rounded animate-pulse" />
          <div className="w-2/3 h-6 bg-gray-200 rounded animate-pulse" />
        </div>
      </div>
    </main>
  );
}

function BlogPost() {
  const searchParams = useSearchParams();
  const id = searchParams?.get("id");
  const [article, setArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || "";
    fetch(`${apiUrl}/api/articles/${id}`)
      .then(async (res) => {
        if (!res.ok) {
          setArticle(null);
          setLoading(false);
          return;
        }
        try {
          const data = await res.json();
          setArticle(data);
        } catch {
          setArticle(null);
        }
        setLoading(false);
      })
      .catch(() => {
        setArticle(null);
        setLoading(false);
      });
  }, [id]);

  if (loading) {
    return <SkeletonArticle />;
  }

  if (!article) {
    return (
      <main className="min-h-screen bg-white text-night animate-fade-in">
        {/* Hero Section Skeleton */}
        <div className="relative w-full h-72 sm:h-96 mb-8">
          <h1 className="absolute bottom-16 left-1/2 transform -translate-x-1/2 text-3xl sm:text-5xl font-bold text-gray-500 text-center drop-shadow-lg px-4">
            Article non trouvé
          </h1>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-white text-night">
      {/* Hero Section */}
      {article.image && (
        <div className="relative w-full h-72 sm:h-96">
          <Image
            src={`${process.env.NEXT_PUBLIC_API_URL}${article.image.path}`}
            alt={article.title}
            fill
            className="object-cover w-full h-full rounded-lg shadow-lg"
            style={{ objectPosition: "center" }}
            sizes="(max-width: 768px) 100vw, 700px"
            priority
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent rounded-lg" />
          <h1 className="absolute bottom-16 left-1/2 transform -translate-x-1/2 text-3xl sm:text-5xl font-bold w-full lg:max-w-240 px-[5dvw] text-white text-center drop-shadow-lg">
            {article.title}
          </h1>
          <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 text-white text-center text-base sm:text-lg opacity-90">
            {article.author && (
              <span className="font-semibold mr-2">{article.author.name}</span>
            )}
            {article.date_creation && (
              <span className="text-gray-200">
                {new Date(article.date_creation).toLocaleDateString("fr-FR", {
                  weekday: "long",
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </span>
            )}
          </div>
        </div>
      )}

      <div className="max-w-3xl mx-auto px-4 py-12 mb-20 animate-fade-in">
        {!article.image && (
          <div className="mb-8 flex flex-col items-center">
            <h1 className="text-4xl sm:text-5xl font-bold text-night mb-2 text-center leading-tight">
              {article.title}
            </h1>
            <div className="text-base sm:text-lg text-gray-500 mb-2">
              {article.author && (
                <span className="font-semibold mr-2">
                  {article.author.name}
                </span>
              )}
              {article.date_creation && (
                <span>
                  {new Date(article.date_creation).toLocaleDateString("fr-FR", {
                    weekday: "long",
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                  })}
                </span>
              )}
            </div>
            <div className="w-20 h-1 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full mb-4" />
          </div>
        )}
        <article className="prose prose-lg prose-night max-w-none text-lg leading-relaxed whitespace-pre-line">
          {article.content}
        </article>
      </div>
    </main>
  );
}

export default function BlogArticleClient() {
  return (
    <Suspense fallback={<SkeletonArticle />}>
      <BlogPost />
    </Suspense>
  );
}
