"use client";

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import TabNavigation from "@/components/TabNavigation";
import PageTitle from "@/components/settings/PageTitle";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { IShopProductListing } from "@/types/types";
import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

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));
}

export default function ProductComparisonPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ catalogId: string }>();
  const { request } = useAxios();
  const [listings, setListings] = useState<IShopProductListing[] | null>(null);

  useEffect(() => {
    request<{ listings: IShopProductListing[] }>(
      "GET",
      `/shop-products/catalog/${params.catalogId}/listings`
    )
      .then((res) => setListings(res?.listings || []))
      .catch(() => setListings([]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params.catalogId]);

  const productName =
    listings && listings.length > 0
      ? typeof listings[0].catalogProduct === "object"
        ? listings[0].catalogProduct?.name
        : listings[0].title
      : "";

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          <PageTitle>{productName || t("shops.comparisonTitle")}</PageTitle>

        {listings === null ? (
          <p className="py-16 text-center text-sm text-neutral-500">
            {t("common.loading")}
          </p>
        ) : listings.length === 0 ? (
          <p className="py-16 text-center text-sm text-neutral-500">
            {t("shops.noListingsForProduct")}
          </p>
        ) : (
          <div className="mx-auto mt-4 flex max-w-md flex-col gap-3">
            {listings.map((listing) => {
              const shop =
                typeof listing.shop === "object" ? listing.shop : null;
              const primaryImage =
                listing.images?.[listing.primaryImageIndex] ||
                listing.images?.[0];
              const price = cheapestPrice(listing);

              return (
                <button
                  key={listing._id}
                  type="button"
                  onClick={() => router.push(`/shops/listing/${listing._id}`)}
                  className="flex w-full items-center gap-3 rounded-2xl border border-neutral-200 p-2 text-right active:scale-[0.98] dark:border-neutral-700"
                >
                  {primaryImage && (
                    <div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-xl bg-neutral-200 dark:bg-neutral-800">
                      <Image
                        src={IMAGE_BASE_URL + primaryImage}
                        alt={listing.title}
                        fill
                        className="object-cover"
                        sizes="64px"
                        unoptimized
                      />
                    </div>
                  )}
                  <div className="min-w-0 flex-1 text-right">
                    <p className="truncate text-xs font-semibold text-neutral-500">
                      {shop?.name}
                    </p>
                    {price != null && (
                      <p className="text-sm font-bold">
                        {t("shops.priceLabel", {
                          amount: price.toLocaleString(),
                        })}
                      </p>
                    )}
                  </div>
                  <span className="shrink-0 rounded-full bg-[#387E65] px-4 py-2 text-xs font-bold text-white">
                    {t("shops.viewAndBuyButton")}
                  </span>
                </button>
              );
            })}
          </div>
        )}
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/shops/discover" />
    </>
  );
}
