"use client";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { ArrowLeft } from "lucide-react";
import { HistoryContent } from "@/models/HistoryContent";
import Link from "next/link";
import { useParams } from "next/navigation";
import Image from "next/image";
import Head from "next/head";
import HistorySection from "@/components/history/HistorySection";

type HistoryPageProps = {
  slug?: string;
};

const HistoryPage = ({ slug }: HistoryPageProps) => {
  const [content, setContent] = useState<HistoryContent | null>(null);

  // Fetch all history content
  const {
    // data: allContent,
    isLoading: isLoadingAll,
    error: errorAll,
  } = useQuery<{
    data: HistoryContent[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: ["/histories"],
    enabled: !slug, // Only fetch all content when not viewing a specific article
  });

  // Fetch specific history content if slug is provided
  const {
    data: singleContent,
    isLoading: isLoadingSingle,
    error: errorSingle,
  } = useQuery<HistoryContent>({
    queryKey: [`/histories/${slug}`],
    enabled: !!slug, // Only fetch when slug is available
  });

  // Update content based on query results
  useEffect(() => {
    if (slug && singleContent) {
      setContent(singleContent);
    }
  }, [slug, singleContent]);

  const isLoading = slug ? isLoadingSingle : isLoadingAll;
  const error = slug ? errorSingle : errorAll;

  // Metadata for SEO
  const pageTitle = content
    ? `${content.title} | Badagry Museum`
    : "History of Slavery in Nigeria | Badagry Museum";

  const pageDescription = content
    ? content.metaDescription
    : "Learn about the profound impact of the transatlantic slave trade on West Africa and Nigeria's heritage at Badagry Museum.";

  const keywords = content
    ? content.keywords
    : "Badagry Museum, Nigeria slavery history, West African Slave trade, transatlantic slave trade, Point of No Return";

  return (
    <>
      <Head>
        <title>{pageTitle}</title>
        <meta name="description" content={pageDescription} />
        <meta name="keywords" content={keywords} />

        {/* Open Graph / Facebook */}
        <meta property="og:type" content="article" />
        <meta
          property="og:url"
          content={`https://badagrymuseum.org/history${slug ? `/${slug}` : ""}`}
        />
        <meta property="og:title" content={pageTitle} />
        <meta property="og:description" content={pageDescription} />
        <meta
          property="og:image"
          content={
            content?.imageUrl ||
            "https://images.unsplash.com/photo-1582034986517-30d163aa1da9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&h=600"
          }
        />

        {/* Twitter */}
        <meta property="twitter:card" content="summary_large_image" />
        <meta
          property="twitter:url"
          content={`https://badagrymuseum.org/history${slug ? `/${slug}` : ""}`}
        />
        <meta property="twitter:title" content={pageTitle} />
        <meta property="twitter:description" content={pageDescription} />
        <meta
          property="twitter:image"
          content={
            content?.imageUrl ||
            "https://images.unsplash.com/photo-1582034986517-30d163aa1da9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&h=600"
          }
        />

        {/* Schema.org markup for Google */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "Article",
            headline: content?.title || "History of Slavery in Nigeria",
            image:
              content?.imageUrl ||
              "https://images.unsplash.com/photo-1582034986517-30d163aa1da9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&h=600",
            author: {
              "@type": "Person",
              name: content?.author?.fullName || "Badagry Museum",
            },
            publisher: {
              "@type": "Organization",
              name: "Badagry Museum",
              logo: {
                "@type": "ImageObject",
                url: "https://badagrymuseum.org/logo.png",
              },
            },
            datePublished: content?.createdAt || new Date().toISOString(),
            dateModified: content?.updatedAt || new Date().toISOString(),
            description: pageDescription,
          })}
        </script>
      </Head>

      <section className="relative w-full min-h-screen bg-gray-950 text-white py-16 px-8 md:px-16 lg:px-24">
        <div className="max-w-7xl mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
            <div className="flex flex-col justify-center">
              <div className="flex items-center mb-5 md:mb-12">
                <div className="w-4 h-4 bg-red-600 mr-4"></div>
                <h1 className="text-4xl md:text-5xl font-bold sm:text-4xl lg:text-5xl font-heading tracking-wide">
                  {content ? content.title : "History of Slavery in Nigeria"}
                </h1>
              </div>
              <p className="mt-3 md:text-xl leading-relaxed max-w-2xl mx-auto text-xl text-gray-300">
                {content
                  ? content.metaDescription
                  : "Discover the profound impact of the transatlantic slave trade on West Africa and Nigeria's heritage."}
              </p>
              <div className="mt-10">
                {/* Button */}
                <Link
                  href="#discover-history"
                  className="bg-transparent border border-white text-white py-3 px-8 rounded-lg text-lg hover:bg-white hover:text-black transition duration-300"
                >
                  Discover History
                </Link>
              </div>
            </div>

            <div className="grid grid-cols-3 gap-4 items-end">
              <div className="col-span-3 sm:col-span-1 hidden lg:block"></div>
              <div className="col-span-3 sm:col-span-1 hidden lg:block"></div>
              <div className="col-span-3 sm:col-span-1 hidden lg:block">
                <div className="aspect-w-16 aspect-h-9 overflow-hidden">
                  <img
                    src="/images/IMG_0489_11zon.jpg"
                    alt="Designer working on tablet"
                    className="rounded-lg"
                  />
                </div>
              </div>
              <div className="col-span-3 sm:col-span-1 hidden lg:block">
                <div className="aspect-w-4 aspect-h-3 overflow-hidden">
                  <img
                    src="/images/IMG_0488_11zon.jpg"
                    alt="Empty classroom"
                    className="rounded-lg"
                  />
                </div>
              </div>
              <div className="col-span-3 sm:col-span-2 hidden lg:block">
                <div className="aspect-w-16 aspect-h-9 overflow-hidden">
                  <img
                    src="/images/IMG_0494_11zon.jpg"
                    alt="Person typing on laptop"
                    className="rounded-lg"
                  />
                </div>
              </div>
              <div className="col-span-1">
                <div className="aspect-w-4 aspect-h-3 overflow-hidden">
                  <img
                    src="/images/IMG_0525_11zon.jpg"
                    alt="Vintage Camera"
                    className="rounded-lg"
                  />
                </div>
              </div>
              <div className="col-span-1">
                <div className="aspect-w-4 aspect-h-3 overflow-hidden">
                  <img
                    src="/images/IMG_0495_11zon.jpg"
                    alt="Woman looking through lens"
                    className="rounded-lg"
                  />
                </div>
              </div>
              <div className="col-span-1">
                <div className="aspect-w-4 aspect-h-3 overflow-hidden">
                  <img
                    src="/images/IMG_0487_11zon.jpg"
                    alt="Abstract modern architecture"
                    className="rounded-lg"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      <section className="py-16 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {slug && (
            <div className="mb-8">
              <Link href="/history">
                <Button
                  variant="ghost"
                  className="text-primary hover:text-primary-dark"
                >
                  <ArrowLeft className="mr-2 h-4 w-4" /> Back to History
                </Button>
              </Link>
            </div>
          )}

          {isLoading ? (
            // Loading state
            <div className="space-y-8">
              {slug ? (
                // Single article loading skeleton
                <div>
                  <Skeleton className="h-80 w-full rounded-lg mb-8" />
                  <Skeleton className="h-8 w-3/4 mb-4" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-3/4 mb-8" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-full mb-2" />
                  <Skeleton className="h-4 w-1/2" />
                </div>
              ) : (
                // Multiple articles loading skeleton
                Array(3)
                  .fill(0)
                  .map((_, index) => (
                    <Card key={index} className="mb-8">
                      <CardContent className="p-6">
                        <div className="flex flex-col md:flex-row gap-8">
                          <div className="md:w-1/2">
                            <Skeleton className="h-64 w-full rounded-lg" />
                          </div>
                          <div className="md:w-1/2">
                            <Skeleton className="h-8 w-3/4 mb-4" />
                            <Skeleton className="h-4 w-full mb-2" />
                            <Skeleton className="h-4 w-full mb-2" />
                            <Skeleton className="h-4 w-full mb-2" />
                            <Skeleton className="h-4 w-3/4 mb-4" />
                            <Skeleton className="h-10 w-32" />
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))
              )}
            </div>
          ) : error ? (
            // Error state
            <div className="text-center py-8">
              <p className="text-destructive">
                Error loading history content. Please try again later.
              </p>
            </div>
          ) : (
            // Content display
            <div>
              {slug && content ? (
                // Single article view
                <article className="prose prose-lg max-w-none">
                  <img
                    src={`${content.imageUrl}`}
                    alt={content.title}
                    className="w-full h-80 object-cover rounded-lg mb-8"
                  />
                  <div dangerouslySetInnerHTML={{ __html: content.content }} />

                  <div className="mt-8 text-sm text-gray-500">
                    {content.author && (
                      <p>Written by: {content.author.fullName}</p>
                    )}
                    <p>
                      Last updated:{" "}
                      {new Date(content.updatedAt).toLocaleDateString()}
                    </p>
                  </div>
                </article>
              ) : (
                <>
                  <HistorySection hideHeader hideMoreLink />
                </>
              )}
            </div>
          )}
        </div>
      </section>
    </>
  );
};

export default HistoryPage;
