"use client";

import Image from "next/image";
import { useMemo } from "react";
import { Heart } from "lucide-react";
import { useRouter } from "next/navigation";
import type { Store } from "@/types/domain";
import { useLocale } from "@/providers/locale-provider";
import { pickLocalizedText } from "@/lib/utils/i18n";
import { useAuth } from "@/providers/auth-provider";
import { useToast } from "@/providers/toast-provider";
import { getApiErrorMessage } from "@/lib/api/client";
import { useFavoritesQuery, useToggleFavoriteMutation } from "@/hooks/queries/api-hooks";

export function StoreCard({ store }: { store: Store }) {
  const { locale } = useLocale();
  const router = useRouter();
  const { isAuthenticated } = useAuth();
  const { showToast } = useToast();
  const favoritesQuery = useFavoritesQuery(isAuthenticated);
  const toggleFavoriteMutation = useToggleFavoriteMutation();
  const storeName = pickLocalizedText(store, "name_ar", "name_en", locale, locale === "ar" ? "متجر" : "Store");
  const storeDescription = pickLocalizedText(
    store,
    "description_ar",
    "description_en",
    locale,
    locale === "ar" ? "عروض وكوبونات محدثة باستمرار" : "Fresh offers and coupon codes updated frequently",
  );

  const favoriteStoreIds = useMemo(() => {
    const payload = favoritesQuery.data;
    if (!payload) {
      return new Set<number>();
    }

    if (Array.isArray(payload)) {
      const ids = payload
        .filter((item) => String(item.favoritable_type || "").toLowerCase().includes("store"))
        .map((item) => Number(item.favoritable_id))
        .filter((value) => Number.isFinite(value) && value > 0);
      return new Set(ids);
    }

    const ids = (payload.stores || []).map((item) => item.id);
    return new Set(ids);
  }, [favoritesQuery.data]);

  const isFavorite = favoriteStoreIds.has(store.id);

  return (
    <article className="relative rounded-2xl border border-[var(--border)] bg-white p-4 shadow-sm transition hover:shadow-md">
      <button
        type="button"
        className={`absolute start-3 top-3 z-10 inline-flex h-9 w-9 items-center justify-center rounded-full border transition ${
          isFavorite
            ? "border-rose-200 bg-rose-50 text-rose-600"
            : "border-slate-200 bg-white text-slate-500 hover:bg-slate-50"
        }`}
        onClick={(event) => {
          event.preventDefault();
          event.stopPropagation();

          if (!isAuthenticated) {
            router.push("/login");
            return;
          }

          void toggleFavoriteMutation
            .mutateAsync({ favoritable_type: "store", favoritable_id: store.id })
            .then((response) => {
              showToast({
                type: "success",
                title: response.is_favorited
                  ? locale === "ar" ? "تمت إضافة المتجر للمفضلة" : "Store added to favorites"
                  : locale === "ar" ? "تمت إزالة المتجر من المفضلة" : "Store removed from favorites",
              });
            })
            .catch((error: unknown) => {
              showToast({
                type: "error",
                title: locale === "ar" ? "فشل تحديث المفضلة" : "Failed to update favorites",
                description: getApiErrorMessage(error),
              });
            });
        }}
        disabled={toggleFavoriteMutation.isPending}
        aria-label={locale === "ar" ? "إضافة المتجر للمفضلة" : "Toggle store favorite"}
      >
        <Heart size={16} fill={isFavorite ? "currentColor" : "none"} />
      </button>

      <div className="flex min-h-[88px] items-center gap-4">
        <div className="flex h-16 w-16 items-center justify-center rounded-full border border-[var(--border)] bg-white">
          <Image src={store.logo || "/images/store-placeholder.svg"} alt={storeName} width={52} height={52} unoptimized className="h-[52px] w-[52px] object-contain" />
        </div>

        <div className="min-w-0 flex-1">
          <h3 className="line-clamp-1 text-[24px] font-extrabold text-slate-900 md:text-[26px]">{storeName}</h3>
          <p className="mt-1 line-clamp-2 text-[15px] leading-6 text-slate-500">{storeDescription}</p>
        </div>
      </div>
    </article>
  );
}
