"use client";

import Image from "next/image";
import Link from "next/link";
import { useInfiniteQuery } from "@tanstack/react-query";
import { Post } from "@/types/types";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import Cookies from "js-cookie";
import { useCallback, useEffect } from "react";
import PageLoader from "@/components/ui/PageLoader";
import BoldIcon from "@/components/ui/BoldIcon";
import { formatLikeDisplay } from "@/lib/formatLikeDisplay";
import ExploreAuthor from "@/components/explore/ExploreAuthor";
import { fetchBookmarkPosts } from "@/api/fetchBookmarkPosts";
import { buildPostPath } from "@/lib/postSlug";
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;

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 getPostMedia(post: Post): {
  kind: "video" | "image";
  src: string;
  poster?: string;
} | null {
  const file = post.files?.[0];
  if (!file?.path) return null;

  const src = buildStorageUrl(file.path);
  const isVideo = post.type === "video" || file.type === "video";
  const posterPath =
    post.post_images?.[0] ||
    post.files?.find((f) => f.type === "image")?.path;

  return {
    kind: isVideo ? "video" : "image",
    src,
    poster: posterPath ? buildStorageUrl(posterPath) : undefined,
  };
}

function FavoriteCard({ post }: { post: Post }) {
  const { t } = useTranslation("common");
  const media = getPostMedia(post);
  if (!media) return null;

  const aspect = hashAspect(post._id);
  const displayName =
    [post.first_name, post.last_name].filter(Boolean).join(" ") ||
    post.user_name ||
    t("common.user");

  return (
    <article className="mb-2 break-inside-avoid">
      <Link
        href={buildPostPath(post._id, post)}
        className="gentle-transition block active:scale-[0.98]"
      >
        <div
          className={`relative w-full overflow-hidden rounded-2xl bg-neutral-900 ${aspect}`}
        >
          {media.kind === "video" && media.poster ? (
            <Image
              src={media.poster}
              alt=""
              fill
              className="object-cover"
              sizes="50vw"
              unoptimized
            />
          ) : media.kind === "video" ? (
            <video
              src={media.src}
              preload="metadata"
              muted
              playsInline
              className="absolute inset-0 h-full w-full object-cover"
            />
          ) : (
            <Image
              src={media.src}
              alt=""
              fill
              className="object-cover"
              sizes="50vw"
              unoptimized
            />
          )}
          {media.kind === "video" && (
            <span className="absolute bottom-2 left-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/55 text-[10px] text-white backdrop-blur-sm">
              ▶
            </span>
          )}
        </div>
      </Link>

      <div className="flex items-center justify-between gap-2 px-0.5 py-1.5">
        <ExploreAuthor
          userId={post.user_id}
          userName={post.user_name}
          displayName={displayName}
          profileImage={post.profile_image}
        />
        <span className="flex shrink-0 items-center gap-1 text-[10px] text-neutral-500">
          <BoldIcon name="heart" size={14} tinted className="text-[#FC8EAC]" />
          {formatLikeDisplay(post.likesCount ?? 0)}
        </span>
      </div>
    </article>
  );
}

export default function FavoritesGrid() {
  const { t } = useTranslation("common");
  const token = Cookies.get("token") || "";

  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading,
    isError,
  } = useInfiniteQuery({
    queryKey: ["bookmark-posts"],
    queryFn: ({ pageParam }) =>
      fetchBookmarkPosts({ pageParam: pageParam as number, token }),
    initialPageParam: 1,
    getNextPageParam: (last) => last.nextPage,
    enabled: Boolean(token),
  });

  const posts = data?.pages.flatMap((p) => p.posts) ?? [];

  const onScroll = useCallback(() => {
    if (!hasNextPage || isFetchingNextPage) return;
    const nearBottom =
      window.innerHeight + window.scrollY >= document.body.offsetHeight - 400;
    if (nearBottom) void fetchNextPage();
  }, [fetchNextPage, hasNextPage, isFetchingNextPage]);

  useEffect(() => {
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [onScroll]);

  if (isLoading) return <PageLoader className="py-10" />;
  if (isError) {
    return (
      <p className="py-8 text-center text-sm text-neutral-500">
        {t("common.error")}
      </p>
    );
  }
  if (!posts.length) {
    return (
      <p className="py-8 text-center text-sm text-neutral-500">
        {t("settings.favorites.empty")}
      </p>
    );
  }

  return (
    <div className="columns-2 gap-2 px-1 sm:columns-3">
      {posts.map((post) => (
        <FavoriteCard key={post._id} post={post} />
      ))}
      {isFetchingNextPage ? <PageLoader className="col-span-full py-4" /> : null}
    </div>
  );
}
