"use client";

import Image from "next/image";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useRef } from "react";
import { MAGAZINE_ELMI_CATEGORY_URL } from "@/features/magazine/constants";
import { useMagazinePosts } from "@/features/magazine/hooks/use-magazine-posts";
import { panelDict } from "@/features/panel/dict";

function scrollByCard(container: HTMLDivElement | null, direction: 1 | -1) {
  if (!container) {
    return;
  }

  const amount = Math.min(container.clientWidth * 0.85, 280);
  container.scrollBy({ left: direction * amount, behavior: "smooth" });
}

export function DashboardMagazineCarousel() {
  const { data: posts = [], isLoading, isError } = useMagazinePosts();
  const scrollRef = useRef<HTMLDivElement>(null);

  if (isError) {
    return null;
  }

  if (isLoading) {
    return (
      <section className="space-y-3">
        <div className="flex items-center justify-between px-1">
          <h2 className="text-base font-bold text-foreground sm:text-lg">
            {panelDict.magazineTitle}
          </h2>
        </div>
        <div className="flex gap-3 overflow-hidden px-1">
          {Array.from({ length: 3 }).map((_, index) => (
            <div
              key={index}
              className="h-56 w-[78%] shrink-0 animate-pulse rounded-3xl bg-card shadow-soft-sm sm:w-64"
            />
          ))}
        </div>
      </section>
    );
  }

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

  return (
    <section className="space-y-3">
      <div className="flex items-center justify-between gap-3 px-1">
        <div className="min-w-0">
          <h2 className="text-base font-bold text-foreground sm:text-lg">
            {panelDict.magazineTitle}
          </h2>
          <p className="mt-0.5 text-xs text-muted-foreground sm:text-sm">
            {panelDict.magazineSubtitle}
          </p>
        </div>

        <div className="flex shrink-0 items-center gap-2">
          <button
            type="button"
            aria-label={panelDict.magazinePrev}
            onClick={() => scrollByCard(scrollRef.current, 1)}
            className="hidden size-9 items-center justify-center rounded-full bg-card text-muted-foreground shadow-soft-sm transition-colors hover:bg-accent hover:text-accent-foreground sm:inline-flex"
          >
            <ChevronRight className="size-4" />
          </button>
          <button
            type="button"
            aria-label={panelDict.magazineNext}
            onClick={() => scrollByCard(scrollRef.current, -1)}
            className="hidden size-9 items-center justify-center rounded-full bg-card text-muted-foreground shadow-soft-sm transition-colors hover:bg-accent hover:text-accent-foreground sm:inline-flex"
          >
            <ChevronLeft className="size-4" />
          </button>
          <a
            href={MAGAZINE_ELMI_CATEGORY_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs font-medium text-primary"
          >
            {panelDict.magazineViewAll}
          </a>
        </div>
      </div>

      <div className="w-full min-w-0 max-w-full overflow-x-clip">
        <div
          ref={scrollRef}
          dir="rtl"
          className="flex gap-3 overflow-x-auto overscroll-x-contain pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
        >
        {posts.map((post) => (
          <a
            key={post.id}
            href={post.link}
            target="_blank"
            rel="noopener noreferrer"
            className="group flex w-[78%] shrink-0 flex-col overflow-hidden rounded-3xl bg-card shadow-soft-sm transition-transform hover:scale-[1.01] active:scale-[0.99] sm:w-64"
          >
            <div className="relative aspect-[16/10] overflow-hidden bg-muted">
              {post.imageUrl ? (
                <Image
                  src={post.imageUrl}
                  alt=""
                  fill
                  unoptimized
                  className="object-cover transition-transform duration-300 group-hover:scale-105"
                  sizes="(max-width: 640px) 78vw, 256px"
                />
              ) : (
                <div className="flex size-full items-center justify-center text-xs text-muted-foreground">
                  {panelDict.magazineNoImage}
                </div>
              )}
            </div>

            <div className="flex flex-1 flex-col gap-1.5 p-4">
              <h3 className="line-clamp-2 text-sm font-bold leading-6 text-card-foreground">
                {post.title}
              </h3>
              {post.excerpt ? (
                <p className="line-clamp-2 text-xs leading-5 text-muted-foreground">
                  {post.excerpt}
                </p>
              ) : null}
            </div>
          </a>
        ))}
        </div>
      </div>
    </section>
  );
}
