"use client";

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import { IMAGE_BASE_URL, staticIconUrl } from "@/components/main/BaseUrl";
import ProductImageLightbox from "@/components/shops/ProductImageLightbox";
import BoldIcon from "@/components/ui/BoldIcon";
import TabNavigation from "@/components/TabNavigation";
import useAxios from "@/hooks/useAxios";
import { addToCart, isFavorite, toggleFavorite } from "@/lib/shops/localCart";
import { cn } from "@/lib/utils";
import { IShopProductListing, IShopProductVariant } from "@/types/types";
import Cookies from "js-cookie";
import { trackExploreInteraction } from "@/api/trackExploreInteraction";
import Image from "next/image";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type ShippingMethod = { method: string; cost: number; enabled: boolean };
type ShopHeader = {
  _id: string;
  name: string;
  logo?: string | null;
  shipping_methods?: ShippingMethod[];
};

function uniqueValues(values: (string | null | undefined)[]): string[] {
  return Array.from(new Set(values.filter((v): v is string => Boolean(v))));
}

function SpecRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex w-full items-center gap-2 rounded-3xl border border-neutral-200 px-4 py-3 dark:border-neutral-700">
      <span className="shrink-0 text-sm font-bold">{label}</span>
      <div className="flex flex-1 flex-wrap items-center justify-end gap-2 text-right">
        {children}
      </div>
      <BoldIcon name="arrow-down" size={16} tinted className="shrink-0 text-neutral-400" />
    </div>
  );
}

export default function ListingDetailClient() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ listingId: string }>();
  const { request, loading } = useAxios();

  const [listing, setListing] = useState<IShopProductListing | null>(null);
  const [selectedColor, setSelectedColor] = useState<string | null>(null);
  const [selectedSize, setSelectedSize] = useState<string | null>(null);
  const [selectedWeight, setSelectedWeight] = useState<string | null>(null);
  const [shippingMethod, setShippingMethod] = useState<string>("");
  const [quantity, setQuantity] = useState(1);
  const [activeImageIndex, setActiveImageIndex] = useState(0);
  const [descriptionExpanded, setDescriptionExpanded] = useState(false);
  const [showAddressModal, setShowAddressModal] = useState(false);
  const [showLightbox, setShowLightbox] = useState(false);
  const [favorite, setFavorite] = useState(false);

  useEffect(() => {
    request<{ listing: IShopProductListing }>("GET", `/shop-products/${params.listingId}`).then(
      (res) => {
        const data = res?.listing || null;
        setListing(data);
        const firstVariant = data?.variants?.[0];
        if (firstVariant) {
          setSelectedColor(firstVariant.color || null);
          setSelectedSize(firstVariant.size || null);
          setSelectedWeight(firstVariant.weight || null);
        }
        if (data) setFavorite(isFavorite(data._id));
      }
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params.listingId]);

  const shopInfo: ShopHeader | null =
    listing && typeof listing.shop === "object" ? (listing.shop as ShopHeader) : null;

  useEffect(() => {
    if (!listing?._id) return;
    const token = Cookies.get("token") || "";
    if (!token) return;
    const ownerId = shopInfo?._id || (typeof listing.shop === "string" ? listing.shop : undefined);
    trackExploreInteraction(
      {
        targetType: "shop_product",
        targetId: listing._id,
        authorId: ownerId,
        contentType: "shop_product",
        action: "view",
      },
      token
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listing?._id]);

  const colors = useMemo(
    () => uniqueValues(listing?.variants.map((v) => v.color) || []),
    [listing]
  );
  const sizes = useMemo(() => {
    if (!listing) return [];
    const relevant = listing.variants.filter(
      (v) => colors.length === 0 || v.color === selectedColor
    );
    return uniqueValues(relevant.map((v) => v.size));
  }, [listing, colors, selectedColor]);
  const weights = useMemo(() => {
    if (!listing) return [];
    const relevant = listing.variants.filter(
      (v) =>
        (colors.length === 0 || v.color === selectedColor) &&
        (sizes.length === 0 || v.size === selectedSize)
    );
    return uniqueValues(relevant.map((v) => v.weight));
  }, [listing, colors, sizes, selectedColor, selectedSize]);

  useEffect(() => {
    if (sizes.length > 0 && (!selectedSize || !sizes.includes(selectedSize))) {
      setSelectedSize(sizes[0]);
    }
  }, [sizes, selectedSize]);

  useEffect(() => {
    if (weights.length > 0 && (!selectedWeight || !weights.includes(selectedWeight))) {
      setSelectedWeight(weights[0]);
    }
  }, [weights, selectedWeight]);

  const matchedVariant: IShopProductVariant | null = useMemo(() => {
    if (!listing) return null;
    return (
      listing.variants.find(
        (v) =>
          (colors.length === 0 || v.color === selectedColor) &&
          (sizes.length === 0 || v.size === selectedSize) &&
          (weights.length === 0 || v.weight === selectedWeight)
      ) ||
      listing.variants[0] ||
      null
    );
  }, [listing, colors, sizes, weights, selectedColor, selectedSize, selectedWeight]);

  useEffect(() => {
    setQuantity(1);
  }, [matchedVariant?._id]);

  const enabledShippingMethods = shopInfo?.shipping_methods?.filter((m) => m.enabled) || [];

  const categoryLine = listing
    ? [listing.category, listing.sub_category, listing.sub_sub_category]
        .filter(Boolean)
        .join(" / ")
    : "";

  const discountPercent =
    matchedVariant?.discount_price && matchedVariant.discount_price < matchedVariant.price
      ? Math.round(
          ((matchedVariant.price - matchedVariant.discount_price) / matchedVariant.price) * 100
        )
      : null;

  const handleImageScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const el = event.currentTarget;
    const index = Math.round(el.scrollLeft / el.clientWidth);
    setActiveImageIndex(index);
  };

  const handleBuy = async () => {
    if (!listing || !matchedVariant) return;
    if (enabledShippingMethods.length > 0 && !shippingMethod) {
      toast.error(t("shops.shippingMethodRequired"));
      return;
    }
    try {
      const response = await request<{ order: { _id: string } }>("POST", "/orders/draft", {
        listingId: listing._id,
        variantId: matchedVariant._id,
        quantity,
        shippingMethod: shippingMethod || undefined,
      });
      if (response?.order?._id) {
        router.push(`/shops/checkout/${response.order._id}`);
      }
    } catch (err: unknown) {
      const data = (err as { response?: { data?: { code?: string; message?: string } } })
        ?.response?.data;
      if (data?.code === "ADDRESS_REQUIRED") {
        setShowAddressModal(true);
        return;
      }
      toast.error(data?.message || t("shops.unknownError"));
    }
  };

  const handleAddToCart = () => {
    if (!listing || !matchedVariant) return;
    addToCart(listing._id, matchedVariant._id, quantity);
    toast.success(t("shops.addToCartSuccess"));
  };

  const handleToggleFavorite = () => {
    if (!listing) return;
    const next = toggleFavorite(listing._id);
    setFavorite(next);
    toast.success(next ? t("shops.addedToFavorites") : t("shops.removedFromFavorites"));
  };

  if (!listing) return null;

  const images = listing.images || [];

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          {shopInfo?._id ? (
            <Link
              href={`/shops/profile/${shopInfo._id}`}
              className="flex items-center justify-end gap-2"
            >
              <span className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full bg-neutral-100 dark:bg-neutral-800">
                {shopInfo?.logo ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={IMAGE_BASE_URL + shopInfo.logo}
                    alt={shopInfo.name}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <Image
                    src={staticIconUrl("/images/icons/vuesax/bold/shop.svg")}
                    width={18}
                    height={18}
                    alt=""
                    className="dark:invert"
                  />
                )}
              </span>
              <span className="text-sm font-bold">{shopInfo?.name}</span>
            </Link>
          ) : null}

          <div className="mx-auto mt-4 flex w-full max-w-md flex-col gap-4 rounded-3xl border border-neutral-200 p-4 dark:border-neutral-700">
            <div className="flex items-center justify-between gap-2">
              <h1 className="text-right text-xl font-bold">{listing.title}</h1>
              {discountPercent != null && (
                <span className="relative flex h-11 w-11 shrink-0 items-center justify-center">
                  <span className="absolute inset-0 rounded-lg bg-red-500" />
                  <span className="absolute inset-0 rotate-[22.5deg] rounded-lg bg-red-500" />
                  <span className="relative z-10 text-sm font-extrabold text-white">
                    {t("shops.discountPercentBadge", { percent: discountPercent })}
                  </span>
                </span>
              )}
            </div>

            {images.length > 0 && (
              <div className="relative">
                <div
                  onScroll={handleImageScroll}
                  className="flex w-full snap-x snap-mandatory gap-0 overflow-x-auto rounded-2xl [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
                >
                  {images.map((img) => (
                    <button
                      key={img}
                      type="button"
                      onClick={() => setShowLightbox(true)}
                      className="relative aspect-[4/3] w-full shrink-0 snap-center overflow-hidden bg-neutral-200 dark:bg-neutral-800"
                    >
                      <Image
                        src={IMAGE_BASE_URL + img}
                        alt={listing.title}
                        fill
                        className="object-cover"
                        sizes="400px"
                        unoptimized
                      />
                    </button>
                  ))}
                </div>
                {images.length > 1 && (
                  <span className="absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-bold text-white">
                    {activeImageIndex + 1}/{images.length}
                  </span>
                )}
              </div>
            )}

            <p className="text-sm font-bold">{t("shops.specsTitle")}</p>

            {categoryLine && (
              <SpecRow label={t("shops.categorySpecLabel")}>
                <span className="text-xs">{categoryLine}</span>
              </SpecRow>
            )}

            {colors.length > 0 && (
              <SpecRow label={t("shops.colorLabel")}>
                {colors.map((color) => (
                  <button
                    key={color}
                    type="button"
                    onClick={() => setSelectedColor(color)}
                    className={cn(
                      "rounded-full border px-2.5 py-1 text-xs",
                      selectedColor === color
                        ? "border-pink-500 bg-pink-500 text-white"
                        : "border-neutral-300 dark:border-neutral-600"
                    )}
                  >
                    {color}
                  </button>
                ))}
              </SpecRow>
            )}

            {sizes.length > 0 && (
              <SpecRow label={t("shops.sizeLabel")}>
                {sizes.map((size) => (
                  <button
                    key={size}
                    type="button"
                    onClick={() => setSelectedSize(size)}
                    className={cn(
                      "rounded-full border px-2.5 py-1 text-xs",
                      selectedSize === size
                        ? "border-pink-500 bg-pink-500 text-white"
                        : "border-neutral-300 dark:border-neutral-600"
                    )}
                  >
                    {size}
                  </button>
                ))}
              </SpecRow>
            )}

            {weights.length > 0 && (
              <SpecRow label={t("shops.weightLabel")}>
                {weights.map((weight) => (
                  <button
                    key={weight}
                    type="button"
                    onClick={() => setSelectedWeight(weight)}
                    className={cn(
                      "rounded-full border px-2.5 py-1 text-xs",
                      selectedWeight === weight
                        ? "border-pink-500 bg-pink-500 text-white"
                        : "border-neutral-300 dark:border-neutral-600"
                    )}
                  >
                    {weight}
                  </button>
                ))}
              </SpecRow>
            )}

            {enabledShippingMethods.length > 0 && (
              <SpecRow
                label={`${t("shops.shippingTitle")} *`}
              >
                {enabledShippingMethods.map((m) => (
                  <button
                    key={m.method}
                    type="button"
                    onClick={() => setShippingMethod(m.method)}
                    className={cn(
                      "rounded-full border px-2.5 py-1 text-xs",
                      shippingMethod === m.method
                        ? "border-pink-500 bg-pink-500 text-white"
                        : "border-neutral-300 dark:border-neutral-600"
                    )}
                  >
                    {t(`shops.shippingMethods.${m.method}`)}
                  </button>
                ))}
              </SpecRow>
            )}

            {listing.description && (
              <SpecRow label={t("shops.descriptionLabel")}>
                <span className="text-xs leading-relaxed">
                  {descriptionExpanded || listing.description.length <= 50
                    ? listing.description
                    : `${listing.description.slice(0, 50)}...`}
                  {listing.description.length > 50 && (
                    <button
                      type="button"
                      onClick={() => setDescriptionExpanded((v) => !v)}
                      className="mr-1 font-bold text-pink-500"
                    >
                      {descriptionExpanded ? t("shops.showLess") : t("shops.showMore")}
                    </button>
                  )}
                </span>
              </SpecRow>
            )}

            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => void handleBuy()}
                disabled={loading || !matchedVariant}
                className="flex-1 rounded-3xl bg-green-600 py-2.5 text-center text-sm font-bold text-white disabled:opacity-50"
              >
                {t("shops.placeOrderButton")}
              </button>
              <button
                type="button"
                onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-green-600 text-lg font-bold text-white"
              >
                −
              </button>
              <span className="w-8 shrink-0 text-center text-sm font-bold">{quantity}</span>
              <button
                type="button"
                onClick={() =>
                  setQuantity((q) =>
                    matchedVariant ? Math.min(matchedVariant.stock, q + 1) : q + 1
                  )
                }
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-green-600 text-lg font-bold text-white"
              >
                +
              </button>
            </div>

            {matchedVariant && (
              <SpecRow label={t("shops.priceSpecLabel")}>
                {matchedVariant.discount_price ? (
                  <span className="flex items-center gap-2">
                    <span className="text-xs text-neutral-400 line-through">
                      {(matchedVariant.price * quantity).toLocaleString()} {t("settings.toman")}
                    </span>
                    <span className="text-sm font-bold text-red-500">
                      {(matchedVariant.discount_price * quantity).toLocaleString()} {t("settings.toman")}
                    </span>
                  </span>
                ) : (
                  <span className="text-sm font-bold">
                    {(matchedVariant.price * quantity).toLocaleString()} {t("settings.toman")}
                  </span>
                )}
              </SpecRow>
            )}
          </div>

          <div className="mx-auto mb-6 mt-8 flex w-full max-w-md gap-3">
            <button
              type="button"
              onClick={handleAddToCart}
              className="flex-1 rounded-3xl bg-green-600 py-3 text-sm font-bold text-white"
            >
              {t("shops.addToCartButton")}
            </button>
            <button
              type="button"
              onClick={handleToggleFavorite}
              className="flex-1 rounded-3xl bg-sky-500 py-3 text-sm font-bold text-white"
            >
              {favorite ? t("shops.removeFromFavoritesButton") : t("shops.addToFavoritesButton")}
            </button>
          </div>
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/settings" />

      {showAddressModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-sm rounded-2xl bg-white p-6 text-center dark:bg-neutral-900">
            <p className="mb-4 text-sm">{t("shops.addressRequiredHint")}</p>
            <button
              type="button"
              onClick={() => router.push("/settings/edit/location")}
              className="w-full rounded-3xl bg-pink-500 py-2.5 text-sm font-bold text-white"
            >
              {t("shops.goToLocationSettings")}
            </button>
            <button
              type="button"
              className="mt-3 block w-full text-xs text-neutral-500"
              onClick={() => setShowAddressModal(false)}
            >
              {t("auth.skip")}
            </button>
          </div>
        </div>
      )}

      <ProductImageLightbox
        images={images}
        initialIndex={activeImageIndex}
        alt={listing.title}
        open={showLightbox}
        onClose={() => setShowLightbox(false)}
      />
    </>
  );
}
