"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { HistoryContent } from "@/models/HistoryContent";
import { useEffect, useState } from "react";

const PAGE_SIZE = 4;

type HistoryCardProps = {
  content: HistoryContent;
  reverse?: boolean; // Optional prop to reverse layout
  imagePosition: "left" | "right";
};

const HistoryCard = ({ content, imagePosition }: HistoryCardProps) => {
  const isLeft = imagePosition === "left";
  return (
    <article
      className={`flex flex-col lg:flex-row p-4 md:p-6 ${
        isLeft ? "lg:flex-row" : "lg:flex-row-reverse"
      } gap-10 lg:gap-16 items-center bg-white rounded-2xl shadow-sm border border-gray-100 hover:shadow-md transition-shadow duration-300`}
      aria-labelledby={`history-title-${content.slug}`}
    >
      {/* Image Section */}
      <figure className="lg:w-1/2 w-full group relative overflow-hidden rounded-xl">
        <img
          src={`${content.imageUrl}`}
          alt={content.title}
          className={`w-full aspect-video object-cover transition-transform duration-500 group-hover:scale-105`}
          loading="lazy"
        />
        <figcaption className="sr-only">{content.title}</figcaption>
      </figure>

      {/* Text Section */}
      <div className="lg:w-1/2 w-full">
        <header>
          <h3
            id={`history-title-${content.slug}`}
            className="text-2xl md:text-3xl font-heading font-bold text-neutral-900 mb-4"
          >
            {content.title}
          </h3>
        </header>

        <div className="prose prose-gray max-w-none text-gray-600 text-base leading-relaxed">
          {content.metaDescription}
        </div>

        <footer className="mt-6">
          <Link
            href={`/history/${content.slug}`}
            className="inline-flex items-center gap-2 text-primary font-semibold hover:text-primary-dark transition-colors group"
            aria-label={`Read more about ${content.title}`}
          >
            <span>Read full story</span>
            <ArrowRight className="h-4 w-4 group-hover:translate-x-1 transition-transform" />
          </Link>
        </footer>
      </div>
    </article>
  );
};

type HistorySection = {
  hideMoreLink?: boolean;
  hideHeader?: boolean;
};
const HistorySection: React.FC<HistorySection> = ({
  hideHeader = false,
  hideMoreLink = false,
}) => {
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<HistoryContent[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const {
    data: historyContent,
    isLoading,
    error,
    isFetching,
  } = useQuery<{
    data: HistoryContent[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: [`/histories?page=${page}&pageSize=${PAGE_SIZE}`],
    enabled: hasMore,
  });

  useEffect(() => {
    if (historyContent?.data?.length) {
      setItems((prev) => {
        const newItems = historyContent.data.filter(
          (item) => !prev.some((existing) => existing.id === item.id)
        );
        return [...prev, ...newItems];
      });
      setHasMore(historyContent.hasMore);
    }
  }, [historyContent]);

  const handleLoadMore = () => {
    if (hasMore) setPage((prev) => prev + 1);
  };

  return (
    <section
      id="history"
      className={`${!hideMoreLink && "py-20 md:py-28 lg:py-36"} bg-white`}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Section Header */}
        {!hideHeader && (
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-primary font-heading mb-4">
              History of Slavery in Nigeria
            </h2>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              Discover the profound impact of the transatlantic slave trade on
              West Africa and Nigeria's heritage.
            </p>
          </div>
        )}

        {/* Content List */}
        <div className="space-y-10" id="discover-history">
          {isLoading || error || items.length === 0
            ? Array(PAGE_SIZE)
                .fill(0)
                .map((_, index) => (
                  <div
                    key={index}
                    className="flex flex-col gap-8 lg:flex-row items-center"
                  >
                    <div className="w-full lg:w-1/2">
                      <Skeleton className="w-full h-[24rem] rounded-xl" />
                    </div>
                    <div className="w-full lg:w-1/2 space-y-4">
                      <Skeleton className="h-8 w-3/4" />
                      <Skeleton className="h-4 w-full" />
                      <Skeleton className="h-4 w-full" />
                      <Skeleton className="h-4 w-5/6" />
                      <Skeleton className="h-4 w-2/3" />
                    </div>
                  </div>
                ))
            : items.map((content, index) => (
                <HistoryCard
                  key={content.id + index}
                  content={content}
                  imagePosition={index % 2 === 0 ? "left" : "right"}
                />
              ))}
        </div>

        {/* Load More */}
        <div className="mt-16 text-center">
          {hasMore ? (
            <Button
              onClick={handleLoadMore}
              disabled={isFetching}
              className="bg-primary hover:bg-primary-dark text-white text-sm px-6 py-2 rounded-md transition"
            >
              {isFetching ? "Loading..." : "Load More"}
            </Button>
          ) : (
            !hideMoreLink && (
              <Link href="/history">
                <Button className="bg-primary hover:bg-primary-dark text-white text-sm px-6 py-2 rounded-md transition">
                  Explore Complete History
                </Button>
              </Link>
            )
          )}
        </div>
      </div>
    </section>
  );
};

export default HistorySection;
