"use client";

import { UnifiedMediaCard } from "./UnifiedMediaCard";
import { UnifiedMediaCardSkeleton } from "./UnifiedMediaCardSkeleton";
import { UnifiedErrorDisplay } from "./UnifiedErrorDisplay";
import { useMovieBoxHomepage, type MovieBoxOperatingItem } from "@/hooks/useMovieBox";

function MovieBoxSectionSkeleton() {
  return (
    <section className="space-y-4">
      <div className="h-7 md:h-8 w-48 bg-muted/50 rounded animate-pulse" />
      <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8 gap-3 md:gap-4">
        {Array.from({ length: 12 }).map((_, i) => (
          <UnifiedMediaCardSkeleton key={i} />
        ))}
      </div>
    </section>
  );
}

function getMovieSections(operatingList: MovieBoxOperatingItem[] = []) {
  return operatingList
    .filter((item) => item.type === "SUBJECTS_MOVIE" && Array.isArray(item.subjects))
    .map((item) => ({
      title: item.title || "Rekomendasi",
      subjects: item.subjects || [],
    }))
    .filter((section) => section.subjects.length > 0);
}

export function MovieBoxHome() {
  const { data, isLoading, error, refetch } = useMovieBoxHomepage();

  if (isLoading) {
    return (
      <div className="space-y-8">
        <MovieBoxSectionSkeleton />
        <MovieBoxSectionSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <UnifiedErrorDisplay
        title="Gagal Memuat MovieBox"
        message="Tidak dapat mengambil data MovieBox."
        onRetry={() => refetch()}
      />
    );
  }

  const sections = getMovieSections(data?.operatingList || []);

  if (sections.length === 0) {
    return (
      <div className="text-center py-20 text-muted-foreground">
        Tidak ada konten MovieBox saat ini.
      </div>
    );
  }

  return (
    <div className="space-y-10 pb-12">
      {sections.map((section, sectionIndex) => (
        <section key={`${section.title}-${sectionIndex}`}>
          <h2 className="font-display font-bold text-xl md:text-2xl text-foreground mb-4">
            {section.title}
          </h2>

          <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8 gap-3 md:gap-4">
            {section.subjects
              .filter((subject) => subject?.hasResource && subject?.cover?.url)
              .slice(0, 16)
              .map((subject, index) => (
                <UnifiedMediaCard
                  key={`${subject.subjectId}-${index}`}
                  index={index}
                  title={subject.title}
                  cover={subject.cover?.url || ""}
                  link={`/detail/moviebox/${subject.subjectId}`}
                  topLeftBadge={subject.corner ? { text: subject.corner, color: "#E52E2E" } : null}
                />
              ))}
          </div>
        </section>
      ))}
    </div>
  );
}
