"use client";

import React from "react";
import Link from "next/link";
import { MainMapsetCard } from "./main-mapset-card";
import { useQuery } from "@tanstack/react-query";
import mapsetApi from "@/shared/services/mapset";
import { Button } from "@/shared/components/button/button";
import { MainMapsetCardSkeleton } from "./_components/main-mapset-card-skeleton";
import { ErrorState } from "@/shared/components/error-state";

export function CatalogSection() {
  const {
    data: mapsets,
    isLoading,
    isError,
    error,
    isSuccess,
    refetch,
    isFetching,
  } = useQuery({
    queryKey: ["mapsets-catalog"],
    queryFn: () =>
      mapsetApi
        .getMapsets(
          {
            limit: 5,
            filter: JSON.stringify([
              "is_active=true",
              "status_validation=approved",
            ]),
          },
          { skipAuth: true },
        )
        .then((res) => {
          return res.items;
        }),
    staleTime: 5000,
    retry: 1,
  });

  const showSkeleton = isLoading || (isFetching && !isSuccess);

  return (
    <>
      <section id="catalog" className="font-onest @container container mt-24">
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <div className="h-8 w-1 rounded-full bg-blue-500"></div>
            <h2 className="font-onest text-dark-500 ms-3 text-[28px] font-bold">
              Katalog Mapset
            </h2>
          </div>
          <Link href="/maps?open-catalog=true">
            <Button variant={"dangerOutlined"}>Lihat Semua</Button>
          </Link>
        </div>
        <p className="text-md text-gray-600">
          Koleksi lengkap peta dan data geospasial Jawa Timur
        </p>

        {(() => {
          if (showSkeleton) {
            return (
              <div className="mx-auto mt-6 grid grid-cols-1 items-center justify-center gap-6 @xl:grid-cols-2 @6xl:grid-cols-4">
                {[...Array(4)].map((_, i) => (
                  <MainMapsetCardSkeleton key={i} />
                ))}
              </div>
            );
          }

          if (isError) {
            return <ErrorState message={error?.message} onRetry={refetch} />;
          }

          if (isSuccess && (!mapsets || mapsets.length === 0)) {
            return (
              <div className="mt-6 rounded-xl border border-zinc-200 bg-white p-6 text-zinc-600">
                Belum ada mapset untuk ditampilkan.
              </div>
            );
          }

          if (isSuccess && mapsets && mapsets.length > 0) {
            return (
              <div className="mx-auto mt-6 grid grid-cols-1 items-center justify-center gap-6 @xl:grid-cols-2 @6xl:grid-cols-4">
                {mapsets.slice(0, 4).map((mapset) => (
                  <MainMapsetCard key={mapset.id} mapset={mapset} />
                ))}
              </div>
            );
          }
        })()}
      </section>
    </>
  );
}
