"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import { IMAGE_BASE_URL, staticIconUrl } from "@/components/main/BaseUrl";
import ShareShopModal from "@/components/shops/ShareShopModal";
import ShopProductListRow from "@/components/shops/ShopProductListRow";
import BoldIcon from "@/components/ui/BoldIcon";
import TabNavigation from "@/components/TabNavigation";
import useAxios from "@/hooks/useAxios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { saveShopWizardId } from "@/hooks/useShopWizardId";
import { cn } from "@/lib/utils";
import { IShopProductListing } from "@/types/types";
import Image from "next/image";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

type ShopHeader = {
  _id: string;
  name: string;
  logo?: string | null;
};

export default function ShopProductsPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ shopId: string }>();
  const shopId = params.shopId;
  const { request } = useAxios();
  const [shop, setShop] = useState<ShopHeader | null>(null);
  const [search, setSearch] = useState("");
  const [onlyInStock, setOnlyInStock] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);

  useEffect(() => {
    request<{ shop: ShopHeader }>("GET", `/shops/${shopId}`)
      .then((res) => setShop(res?.shop || null))
      .catch(() => setShop(null));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId]);

  const { data, isLoading } = useInfiniteScroll({
    endpoint: "/shop-products",
    queryKey: ["shop-products", shopId],
    params: { shopId },
  });

  const listings: IShopProductListing[] =
    data?.pages.flatMap((page) => page.docs || []) || [];

  const filteredListings = useMemo(() => {
    let result = listings;
    const query = search.trim();
    if (query) {
      result = result.filter((listing) => listing.title.includes(query));
    }
    if (onlyInStock) {
      result = result.filter((listing) =>
        listing.variants?.some((v) => v.stock > 0)
      );
    }
    return result;
  }, [listings, search, onlyInStock]);

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => setShowShareModal(true)}
                aria-label={t("shops.share.title")}
                className="flex h-8 w-8 shrink-0 items-center justify-center"
              >
                <BoldIcon name="share" size={18} tinted />
              </button>
              {shopId && (
                <Link
                  href={`/shops/profile/${shopId}`}
                  aria-label={t("shops.viewPublicProfile")}
                  className="flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-neutral-100 dark:bg-neutral-800"
                >
                  {shop?.logo ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={IMAGE_BASE_URL + shop.logo}
                      alt={shop.name}
                      className="h-full w-full object-cover"
                    />
                  ) : (
                    <Image
                      src={staticIconUrl("/images/icons/vuesax/bold/shop.svg")}
                      width={16}
                      height={16}
                      alt=""
                      className="dark:invert"
                    />
                  )}
                </Link>
              )}
            </div>

            <span className="truncate text-sm font-semibold">{shop?.name}</span>
          </div>

          <h1 className="my-6 text-center text-2xl font-bold">
            {t("shops.myProductsTitle")}
          </h1>

          <div className="mx-auto w-full max-w-md">
            <div className="flex items-center gap-2">
              <div className="relative flex-1">
                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={t("shops.searchProductPlaceholder")}
                  className="w-full rounded-full border border-neutral-200 bg-white py-2.5 pl-4 pr-10 text-sm outline-none dark:border-neutral-700 dark:bg-neutral-900"
                />
                <BoldIcon
                  name="search-normal"
                  size={18}
                  tinted
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 text-neutral-400"
                />
              </div>
              <button
                type="button"
                onClick={() => setOnlyInStock((v) => !v)}
                aria-label={t("shops.inStock")}
                className={cn(
                  "flex h-11 w-11 shrink-0 items-center justify-center rounded-full border",
                  onlyInStock
                    ? "border-pink-500 bg-pink-500 text-white"
                    : "border-neutral-200 text-neutral-500 dark:border-neutral-700"
                )}
              >
                <BoldIcon name="filter" size={18} tinted />
              </button>
            </div>

            <div className="mt-4 flex flex-col gap-2.5">
              {isLoading ? (
                <p className="py-10 text-center text-sm text-neutral-500">
                  {t("common.loading")}
                </p>
              ) : filteredListings.length === 0 ? (
                <p className="py-10 text-center text-sm text-neutral-500">
                  {t("shops.noProductsYet")}
                </p>
              ) : (
                filteredListings.map((listing) => (
                  <ShopProductListRow key={listing._id} listing={listing} shopId={shopId} />
                ))
              )}
            </div>

            <div className="mx-auto mt-6 flex w-full max-w-xs gap-2">
              <RoundedButton
                type="button"
                variant="primary"
                onClick={() => router.push(`/shops/${shopId}/products/new/name`)}
                className="flex h-11 flex-1 items-center justify-center gap-2"
              >
                <BoldIcon name="add" size={18} tinted className="text-white" />
                {t("shops.addProductNew")}
              </RoundedButton>
              <RoundedButton
                type="button"
                onClick={() => {
                  saveShopWizardId(shopId);
                  router.push("/shops/new/name?edit=1");
                }}
                className="flex h-11 flex-1 items-center justify-center gap-2"
              >
                {t("shops.editShopButton")}
              </RoundedButton>
            </div>
          </div>
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/settings" />

      {shop && (
        <ShareShopModal
          open={showShareModal}
          onClose={() => setShowShareModal(false)}
          shopId={shop._id}
          shopName={shop.name}
          shopLogo={shop.logo}
        />
      )}
    </>
  );
}
