"use client";

import { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import { Post } from "@/types/types";
import { getPostMedia } from "@/lib/explore/postMedia";
import ExploreVideoThumb from "@/components/explore/ExploreVideoThumb";
import { buildPostPath } from "@/lib/postSlug";
import { cacheReelsSeedPost } from "@/lib/reelsSeedPost";
import { useTranslation } from "react-i18next";

const ASPECT_RATIOS = [
  "aspect-[2/3]",
  "aspect-[3/4]",
  "aspect-[4/5]",
  "aspect-[5/6]",
  "aspect-square",
  "aspect-[3/5]",
] as const;
const SKELETON_COUNT = 8;

function hashAspect(postId: string): (typeof ASPECT_RATIOS)[number] {
  let hash = 0;
  for (let i = 0; i < postId.length; i++) {
    hash = (hash + postId.charCodeAt(i)) % ASPECT_RATIOS.length;
  }
  return ASPECT_RATIOS[hash];
}

function ArchiveCardSkeleton({ seed }: { seed: number }) {
  const aspect = ASPECT_RATIOS[seed % ASPECT_RATIOS.length];
  return (
    <div className={`mb-2 w-full break-inside-avoid overflow-hidden rounded-2xl bg-neutral-200 dark:bg-neutral-800 ${aspect} animate-pulse`} />
  );
}

function ArchivePage() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const user = useUser();
  const router = useRouter();
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [fetchingMore, setFetchingMore] = useState(false);

  const loadPage = useCallback(
    async (pageNum: number) => {
      const res = await request<{ posts: Post[]; totalPages: number }>(
        "GET",
        `/account/archived-posts?page=${pageNum}&limit=12`,
        null,
        { noToast: true }
      );
      return res;
    },
    [request]
  );

  useEffect(() => {
    setLoading(true);
    loadPage(1)
      .then((res) => {
        setPosts(res?.posts || []);
        setHasMore((res?.totalPages || 1) > 1);
        setPage(1);
      })
      .catch(() => setPosts([]))
      .finally(() => setLoading(false));
  }, [loadPage]);

  const fetchMore = useCallback(() => {
    if (fetchingMore || !hasMore) return;
    setFetchingMore(true);
    const nextPage = page + 1;
    loadPage(nextPage)
      .then((res) => {
        setPosts((prev) => [...prev, ...(res?.posts || [])]);
        setHasMore(nextPage < (res?.totalPages || 1));
        setPage(nextPage);
      })
      .catch(() => setHasMore(false))
      .finally(() => setFetchingMore(false));
  }, [fetchingMore, hasMore, page, loadPage]);

  useEffect(() => {
    const handleScroll = () => {
      if (
        window.innerHeight + window.scrollY >=
        document.body.offsetHeight - 800
      ) {
        fetchMore();
      }
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [fetchMore]);

  const openPost = (post: Post) => {
    const withAuthor: Post = {
      ...post,
      user_name: user?.user_name || post.user_name,
      first_name: user?.first_name || post.first_name,
      last_name: user?.last_name || post.last_name,
      profile_image: user?.profile_image || post.profile_image,
    };
    cacheReelsSeedPost(withAuthor);
    router.push(buildPostPath(post._id, withAuthor));
  };

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.edit.nav.archive")}</PageTitle>
        <div className="my-6">
          {loading ? (
            <div className="columns-2 gap-2">
              {Array.from({ length: SKELETON_COUNT }).map((_, i) => (
                <ArchiveCardSkeleton key={i} seed={i} />
              ))}
            </div>
          ) : posts.length === 0 ? (
            <p className="py-16 text-center text-sm text-neutral-500">
              {t("models.nothingFound")}
            </p>
          ) : (
            <div className="columns-2 gap-2">
              {posts.map((post) => {
                const media = getPostMedia(post);
                if (!media) return null;
                const aspect = hashAspect(post._id);
                return (
                  <button
                    key={post._id}
                    type="button"
                    onClick={() => openPost(post)}
                    className={`gentle-transition relative mb-2 block w-full overflow-hidden rounded-2xl bg-neutral-200 text-right dark:bg-neutral-900 active:scale-[0.98] ${aspect}`}
                  >
                    {media.kind === "video" ? (
                      <ExploreVideoThumb src={media.src} poster={media.poster} />
                    ) : (
                      <Image
                        src={media.src}
                        alt=""
                        fill
                        className="object-cover"
                        sizes="50vw"
                        unoptimized
                      />
                    )}
                  </button>
                );
              })}
              {fetchingMore
                ? Array.from({ length: 4 }).map((_, i) => (
                    <ArchiveCardSkeleton key={`more-${i}`} seed={i} />
                  ))
                : null}
            </div>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ArchivePage;
