"use client";

import { IMAGE_BASE_URL, staticIconUrl } from "@/components/main/BaseUrl";
import ReelsScrollSlot from "@/components/posts/ReelsScrollSlot";
import SendProductModal from "@/components/shops/SendProductModal";
import ShareProductModal from "@/components/shops/ShareProductModal";
import ShopProductCommentsModal from "@/components/shops/ShopProductCommentsModal";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";
import BoldIcon from "@/components/ui/BoldIcon";
import PageLoader from "@/components/ui/PageLoader";
import { REELS_SCROLL_CLASS, useReelsSnapScroll } from "@/hooks/useReelsSnapScroll";
import useAxios from "@/hooks/useAxios";
import { addToCart, isFavorite, toggleFavorite } from "@/lib/shops/localCart";
import { IShopProductListing } from "@/types/types";
import Cookies from "js-cookie";
import { trackExploreInteraction } from "@/api/trackExploreInteraction";
import Image from "next/image";
import Link from "next/link";
import { useLayoutEffect, useMemo, useRef, useState, useEffect } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type ShopReelsViewProps = {
  /** Single-shop mode: fetches that shop's products. Omit when passing `listings` directly (cross-shop mode). */
  shopId?: string;
  initialListingId: string;
  /** Cross-shop mode: a pre-fetched, already-ordered list of listings (e.g. from the discover feed). */
  listings?: IShopProductListing[];
  /** Overrides the top-right close button destination (defaults to the shop profile in single-shop mode, or the discover feed otherwise). */
  backHref?: string;
};

function cheapestPrice(listing: IShopProductListing): number | null {
  if (!listing.variants || listing.variants.length === 0) return null;
  return Math.min(...listing.variants.map((v) => v.discount_price || v.price));
}

function catalogHref(listing: IShopProductListing): string {
  const catalogId =
    typeof listing.catalogProduct === "string"
      ? listing.catalogProduct
      : listing.catalogProduct?._id;
  return `/shops/product/${catalogId}`;
}

export default function ShopReelsView({
  shopId,
  initialListingId,
  listings: providedListings,
  backHref,
}: ShopReelsViewProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const requireAuth = useRequireAuth();
  const scrollRef = useRef<HTMLDivElement>(null);
  useReelsSnapScroll(scrollRef);
  const scrolledRef = useRef(false);

  const [listings, setListings] = useState<IShopProductListing[] | null>(
    providedListings || null
  );
  const [activeIndex, setActiveIndex] = useState(0);
  const [favoriteIds, setFavoriteIds] = useState<Set<string>>(new Set());
  const [shareListing, setShareListing] = useState<IShopProductListing | null>(null);
  const [sendListing, setSendListing] = useState<IShopProductListing | null>(null);
  const [commentListingId, setCommentListingId] = useState<string | null>(null);

  useEffect(() => {
    if (providedListings) {
      setListings(providedListings);
      setFavoriteIds(
        new Set(providedListings.filter((l) => isFavorite(l._id)).map((l) => l._id))
      );
      return;
    }
    if (!shopId) return;
    request<{ docs: IShopProductListing[] }>(
      "GET",
      `/shop-products?shopId=${shopId}&limit=100`
    )
      .then((res) => {
        const docs = res?.docs || [];
        setListings(docs);
        setFavoriteIds(
          new Set(docs.filter((l) => isFavorite(l._id)).map((l) => l._id))
        );
      })
      .catch(() => setListings([]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId, providedListings]);

  const handleToggleFavorite = (listingId: string) => {
    const next = toggleFavorite(listingId);
    setFavoriteIds((prev) => {
      const nextSet = new Set(prev);
      if (next) nextSet.add(listingId);
      else nextSet.delete(listingId);
      return nextSet;
    });
    toast.success(
      next ? t("shops.addedToFavorites") : t("shops.removedFromFavorites")
    );
  };

  const handleAddToCart = (listing: IShopProductListing) => {
    const variant = listing.variants?.[0];
    if (!variant) return;
    addToCart(listing._id, variant._id, 1);
    toast.success(t("shops.addToCartSuccess"));
  };

  const initialIndex = useMemo(() => {
    if (!listings) return 0;
    const idx = listings.findIndex(
      (l) => (l.tileId || l._id) === initialListingId
    );
    return idx >= 0 ? idx : 0;
  }, [listings, initialListingId]);

  useLayoutEffect(() => {
    if (scrolledRef.current || !listings?.length || !scrollRef.current) return;
    scrollRef.current.scrollTo({
      top: initialIndex * (scrollRef.current.clientHeight || window.innerHeight),
      behavior: "auto",
    });
    setActiveIndex(initialIndex);
    scrolledRef.current = true;
  }, [listings, initialIndex]);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el || !listings?.length) return;

    const onScroll = () => {
      const step = el.clientHeight || window.innerHeight;
      const index = Math.min(
        listings.length - 1,
        Math.max(0, Math.round(el.scrollTop / step))
      );
      setActiveIndex(index);
    };

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

  useEffect(() => {
    const listing = listings?.[activeIndex];
    if (!listing) return;
    const token = Cookies.get("token") || "";
    if (!token) return;

    const ownerId =
      typeof listing.shop === "object" ? (listing.shop as { _id: string })?._id : listing.shop;
    const startedAt = Date.now();

    trackExploreInteraction(
      {
        targetType: "shop_product",
        targetId: listing._id,
        authorId: ownerId,
        contentType: "shop_product",
        action: "view",
      },
      token
    );

    return () => {
      const dwellMs = Date.now() - startedAt;
      if (dwellMs >= 2500) {
        trackExploreInteraction(
          {
            targetType: "shop_product",
            targetId: listing._id,
            authorId: ownerId,
            contentType: "shop_product",
            action: "dwell",
            dwellMs,
          },
          token
        );
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeIndex, listings]);

  if (listings === null) {
    return <PageLoader className="min-h-[100dvh] bg-black" />;
  }

  if (listings.length === 0) {
    return (
      <div className="flex min-h-[100dvh] items-center justify-center bg-black">
        <p className="text-sm text-neutral-400">{t("shops.noProductsYet")}</p>
      </div>
    );
  }

  return (
    <div className="relative min-h-[100dvh] bg-black">
      <Link
        href={backHref || (shopId ? `/shops/profile/${shopId}` : "/shops/discover")}
        aria-label={t("common.close")}
        className="absolute right-4 top-4 z-10 flex h-9 w-9 items-center justify-center rounded-full bg-black/50"
      >
        <BoldIcon name="close-circle" size={22} tinted className="text-white" />
      </Link>

      <div ref={scrollRef} className={REELS_SCROLL_CLASS}>
        {listings.map((listing, index) => {
          const primaryImage =
            listing.images?.[listing.primaryImageIndex] || listing.images?.[0];
          const price = cheapestPrice(listing);

          const favorited = favoriteIds.has(listing._id);

          return (
            <ReelsScrollSlot key={listing.tileId || listing._id} index={index} activeIndex={activeIndex}>
              <div className="relative flex h-full w-full items-center justify-center bg-black">
                {primaryImage && (
                  <Image
                    src={IMAGE_BASE_URL + primaryImage}
                    alt={listing.title}
                    fill
                    className="object-contain"
                    sizes="100vw"
                    unoptimized
                  />
                )}

                <div className="absolute bottom-36 left-3 z-30 flex flex-col items-center gap-5">
                  <button
                    type="button"
                    onClick={() => {
                      if (!requireAuth()) return;
                      setCommentListingId(listing._id);
                    }}
                    aria-label={t("posts.comments")}
                    className="flex flex-col items-center gap-1"
                  >
                    <BoldIcon
                      name="message"
                      size={26}
                      tinted
                      className="text-white brightness-125 drop-shadow-lg"
                    />
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      if (!requireAuth()) return;
                      setSendListing(listing);
                    }}
                    aria-label={t("shops.sendProductTitle")}
                    className="flex flex-col items-center gap-1"
                  >
                    <BoldIcon
                      name="send-2"
                      size={26}
                      tinted
                      className="text-white brightness-125 drop-shadow-lg"
                    />
                  </button>
                  <button
                    type="button"
                    onClick={() => setShareListing(listing)}
                    aria-label={t("shops.share.title")}
                    className="flex flex-col items-center gap-1"
                  >
                    <BoldIcon
                      name="share"
                      size={26}
                      tinted
                      className="text-white brightness-125 drop-shadow-lg"
                    />
                  </button>
                  <button
                    type="button"
                    onClick={() => handleToggleFavorite(listing._id)}
                    aria-label={
                      favorited
                        ? t("shops.removeFromFavoritesButton")
                        : t("shops.addToFavoritesButton")
                    }
                    className="flex flex-col items-center gap-1"
                  >
                    <Image
                      src={staticIconUrl("/images/icons/bookmark-post.svg")}
                      alt=""
                      width={28}
                      height={28}
                      className={favorited ? "drop-shadow-lg" : "invert brightness-125 drop-shadow-lg"}
                      unoptimized
                    />
                  </button>
                </div>

                <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-4 pb-8 text-white">
                  {listing.isTaggedPost && (
                    <span className="mb-1 inline-block rounded-full bg-white/15 px-2 py-0.5 text-[10px] font-semibold text-neutral-200">
                      {t("shops.taggedPostBadge")}
                    </span>
                  )}
                  {typeof listing.shop === "object" && listing.shop?.name && (
                    <p className="mb-1 text-xs font-semibold text-neutral-300">
                      {listing.shop.name}
                    </p>
                  )}
                  <p className="mb-1 line-clamp-1 text-base font-bold">{listing.title}</p>
                  {price != null && (
                    <p className="mb-3 text-sm text-neutral-200">
                      {t("shops.priceLabel", { amount: price.toLocaleString() })}
                    </p>
                  )}
                  <div className="flex items-center gap-2">
                    <Link
                      href={catalogHref(listing)}
                      className="inline-block rounded-3xl bg-white px-5 py-2 text-sm font-bold text-black"
                    >
                      {t("shops.viewProduct")}
                    </Link>
                    <button
                      type="button"
                      onClick={() => handleAddToCart(listing)}
                      className="inline-block rounded-3xl bg-green-500 px-5 py-2 text-sm font-bold text-white"
                    >
                      {t("shops.addToCartButton")}
                    </button>
                  </div>
                </div>
              </div>
            </ReelsScrollSlot>
          );
        })}
      </div>

      <ShareProductModal
        open={Boolean(shareListing)}
        onClose={() => setShareListing(null)}
        listingId={shareListing?._id || ""}
        title={shareListing?.title}
        image={
          shareListing?.images?.[shareListing.primaryImageIndex] ||
          shareListing?.images?.[0]
        }
      />

      {sendListing && (
        <SendProductModal
          open={Boolean(sendListing)}
          onClose={() => setSendListing(null)}
          listing={sendListing}
        />
      )}

      {commentListingId && (
        <ShopProductCommentsModal
          open={Boolean(commentListingId)}
          onClose={() => setCommentListingId(null)}
          listingId={commentListingId}
        />
      )}
    </div>
  );
}
