"use client";

import { useEffect, useState } from "react";
import { AiImage } from "@/components/AiImage";
import {
  categoryImageUrl,
  fetchPublicCategories,
  type Category,
} from "@/lib/categories-api";
import { aiImage } from "@/lib/pollinations";

export function CruiseTypes() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    let active = true;
    (async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetchPublicCategories();
        if (!active) return;
        setCategories(res.data || []);
      } catch (err) {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Failed to load categories");
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  return (
    <section className="pb-10 sm:pb-12">
      <div className="container-page">
        <div className="mb-5 max-w-2xl sm:mb-6">
          <h2 className="font-[family-name:var(--font-display)] text-2xl font-semibold text-brand sm:text-3xl">
            Choose the type of cruise tour you desire
          </h2>
          <p className="mt-2 text-sm text-muted sm:text-base">
            No matter who you are, we offer a cruise that suits you.
          </p>
        </div>

        {loading && (
          <p className="py-8 text-sm text-muted">Loading categories…</p>
        )}
        {!loading && error && (
          <p className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
            {error}
          </p>
        )}

        {!loading && !error && (
          <div className="flex gap-3 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] md:grid md:grid-cols-5 md:gap-4 md:overflow-visible [&::-webkit-scrollbar]:hidden">
            {categories.map((category, index) => {
              const href = `/cruise-tours?type=${encodeURIComponent(category.title)}`;
              const src = category.image
                ? categoryImageUrl(category.image)
                : aiImage(`${category.title} cruise Ha Long Bay Vietnam`, {
                    width: 500,
                    height: 700,
                    seed: 40 + index,
                  });

              return (
                <a
                  key={category.id}
                  href={href}
                  title={category.description || category.title}
                  className="group relative h-[14rem] w-[11rem] shrink-0 overflow-hidden rounded-xl sm:h-[16rem] sm:w-[12.5rem] md:h-[18rem] md:w-auto"
                >
                  <AiImage
                    src={src}
                    alt={category.title}
                    className="h-full w-full transition duration-700 group-hover:scale-105"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
                  <h3 className="absolute bottom-4 left-4 text-lg font-bold text-white">
                    {category.title}
                  </h3>
                </a>
              );
            })}
            {categories.length === 0 && (
              <p className="py-8 text-sm text-muted">No categories available.</p>
            )}
          </div>
        )}
      </div>
    </section>
  );
}
