<script setup lang="ts">
import { useInfiniteScroll } from "@vueuse/core";
import { useCategoryQuery } from "~/queries/projects";
import type { Project, ProjectsResponse } from "~/types/projects";

const props = defineProps<{
  serviceId?: number;
}>();
const scrollTarget = ref<HTMLElement | null>(null);

const filteredProjects = ref<Project[]>([]);
const currentPage = ref(1);
const isLoadingMore = ref(false);
const hasMorePages = ref(true);
const hasInitiallyLoaded = ref(false);

const {
  data: initialData,
  isLoading,
  isPending,
} = useCategoryQuery(props.serviceId!.toString(), 1);

watch(
  initialData,
  (newData) => {
    if (newData?.data.projects) {
      const { data: projects, last_page, current_page } = newData.data.projects;
      filteredProjects.value = projects;
      currentPage.value = current_page;
      hasMorePages.value = current_page < last_page;
      hasInitiallyLoaded.value = true;
    }
  },
  { immediate: true },
);

const loadMore = async () => {
  if (isLoadingMore.value || !hasMorePages.value) return;

  const nextPage = currentPage.value + 1;
  isLoadingMore.value = true;

  try {
    const { get } = useApi();
    const response = await get<ProjectsResponse>(`projects`, {
      params: {
        page: nextPage,
        ...(props.serviceId ? { service_id: props.serviceId } : {}),
      },
    });

    const projectsData = response.data?.data.projects;

    if (projectsData?.data && projectsData.data.length > 0) {
      filteredProjects.value.push(...projectsData.data);
      currentPage.value = projectsData.current_page;
      hasMorePages.value = projectsData.current_page < projectsData.last_page;
    } else {
      hasMorePages.value = false;
    }
  } catch (error) {
    console.error("Error loading more projects:", error);
    hasMorePages.value = false;
  } finally {
    isLoadingMore.value = false;
  }
};

useInfiniteScroll(scrollTarget, loadMore, {
  distance: 300,
  canLoadMore: () => hasMorePages.value && !isLoadingMore.value,
});
</script>
<template>
  <!-- Empty state when no projects and not loading -->
  <section
    v-if="hasInitiallyLoaded && !isLoading && !filteredProjects.length"
    class="py-narrow-section"
  >
    <div class="container mx-auto px-4">
      <EmptyState class="mx-auto" />
    </div>
  </section>

  <!-- Projects section -->
  <section
    v-else-if="filteredProjects.length || isLoading"
    id="filteredProjects"
  >
    <!-- Loading state for initial load -->
    <div v-if="isLoading || isPending" class="py-narrow-section">
      <div class="container mx-auto px-4">
        <div class="flex flex-col items-center gap-[30px]">
          <Skeleton class="mx-auto h-8 w-1/3 rounded" />
          <Skeleton
            class="h-[350px] w-full rounded-xl sm:h-[572px] xl:w-[950px]"
          />
          <div class="flex w-full flex-col gap-4 px-8 xl:w-[950px]">
            <Skeleton class="mx-auto h-4 w-3/4 rounded" />
            <Skeleton class="mx-auto h-4 w-1/2 rounded" />
          </div>
          <Skeleton class="mx-auto h-10 w-28 rounded-md" />
        </div>
      </div>
    </div>

    <!-- Projects list -->
    <div v-for="(project, index) in filteredProjects" :key="project.id">
      <ProjectsProjectSection
        :project-info="project"
        :section-bg="index % 2 === 0 ? 'bg-gradient-odd' : 'bg-gradient-even'"
      />
    </div>

    <div
      v-if="isLoadingMore"
      class="py-section"
      :class="
        filteredProjects.length % 2 === 0
          ? 'bg-gradient-odd'
          : 'bg-gradient-even'
      "
    >
      <div class="container mx-auto px-4">
        <div class="flex flex-col items-center gap-[30px]">
          <Skeleton class="mx-auto h-8 w-1/3 rounded" />
          <Skeleton
            class="h-[350px] w-full rounded-xl sm:h-[572px] xl:w-[950px]"
          />
          <div class="flex w-full flex-col gap-4 px-8 xl:w-[950px]">
            <Skeleton class="mx-auto h-4 w-3/4 rounded" />
            <Skeleton class="mx-auto h-4 w-1/2 rounded" />
          </div>
          <Skeleton class="mx-auto h-10 w-28 rounded-md" />
        </div>
      </div>
    </div>

    <section
      ref="scrollTarget"
      class="py-section px-4"
      :class="
        filteredProjects.length % 2 === 0
          ? 'bg-gradient-odd'
          : 'bg-gradient-even'
      "
    >
      <SubscribeSection />
    </section>
  </section>
</template>
