"use client";

import { IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import BlogCard from "./blog-card";

interface RelatedPost {
  category: string;
  categorySlug: string;
  date: string;
  description: string;
  image?: string;
  slug: string;
  title: string;
}

interface RelatedPostsProps {
  locale: string;
  posts: RelatedPost[];
}

export function RelatedPosts({ posts, locale }: RelatedPostsProps) {
  const t = useTranslations("blog");
  const [currentIndex, setCurrentIndex] = useState(0);
  const [perPage, setPerPage] = useState(2);

  useEffect(() => {
    const mql = window.matchMedia("(min-width: 640px)");
    const handler = (e: MediaQueryListEvent | MediaQueryList) =>
      setPerPage(e.matches ? 2 : 1);
    handler(mql);
    mql.addEventListener("change", handler);
    return () => mql.removeEventListener("change", handler);
  }, []);

  useEffect(() => {
    if (currentIndex > posts.length - perPage) {
      setCurrentIndex(Math.max(0, posts.length - perPage));
    }
  }, [perPage, posts.length, currentIndex]);

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

  const maxIndex = Math.max(0, posts.length - perPage);
  const canPrev = currentIndex > 0;
  const canNext = currentIndex < maxIndex;

  function prev() {
    setCurrentIndex((i) => Math.max(0, i - 1));
  }

  function next() {
    setCurrentIndex((i) => Math.min(maxIndex, i + 1));
  }

  const visiblePosts = posts.slice(currentIndex, currentIndex + perPage);

  return (
    <section className="mt-16 border-white/10 border-t pt-12">
      <div className="mb-8 flex items-center justify-between">
        <h2 className="font-bold text-2xl text-white">{t("relatedPosts")}</h2>
        {posts.length > perPage && (
          <div className="flex gap-2">
            <button
              aria-label="Previous"
              className="cursor-pointer rounded-full border border-white/10 p-2 text-neutral-400 transition-all hover:border-[#fd105e]/40 hover:text-white disabled:cursor-default disabled:opacity-30"
              disabled={!canPrev}
              onClick={prev}
              type="button"
            >
              <IconChevronLeft size={18} stroke={2} />
            </button>
            <button
              aria-label="Next"
              className="cursor-pointer rounded-full border border-white/10 p-2 text-neutral-400 transition-all hover:border-[#fd105e]/40 hover:text-white disabled:cursor-default disabled:opacity-30"
              disabled={!canNext}
              onClick={next}
              type="button"
            >
              <IconChevronRight size={18} stroke={2} />
            </button>
          </div>
        )}
      </div>
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
        {visiblePosts.map((post) => (
          <BlogCard
            category={post.category}
            categorySlug={post.categorySlug}
            date={post.date}
            description={post.description}
            headingLevel="h3"
            image={post.image}
            key={post.slug}
            locale={locale}
            slug={post.slug}
            title={post.title}
          />
        ))}
      </div>
    </section>
  );
}
