"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState, type MouseEvent } from "react";
import { useLocale, useTranslations } from "next-intl";
import { useToggleFavorite } from "@/lib/clientQueries";
import { useSession } from "@/auth/session-provider";

interface HorseCardProps {
  horse: {
    id: string | number;
    title: string;
    type: string;
    img: string;
    price: number;
    breed?: string;
    age?: string;
    city?: string;
    country?: string;
    gender?: string;
    height?: number;
    hasHealthCert?: boolean;
    coat?: string;
    saleType?: string;
  };
  sarIcon: string;
  basePath?: string;
}
const DEFAULT_SAR_ICON = "/Riyal.svg";
const HORSE_FALLBACK_IMAGE = "/images/unnamed.jpg";

export default function HorseCard({
  horse,
  sarIcon,
  basePath = "horses",
}: HorseCardProps) {
  const router = useRouter();
  const locale = useLocale();
  const [isFavorite, setIsFavorite] = useState(false);
  const t = useTranslations("HORSE_CARD");
  const toggleFav = useToggleFavorite();
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const normalizeIconSrc = (value?: string) => {
    if (!value) return DEFAULT_SAR_ICON;
    if (value.startsWith("http://") || value.startsWith("https://")) return value;
    return value.startsWith("/") ? value : `/${value}`;
  };
  const [priceIconSrc, setPriceIconSrc] = useState<string>(
    normalizeIconSrc(sarIcon)
  );

  useEffect(() => {
    setPriceIconSrc(normalizeIconSrc(sarIcon));
  }, [sarIcon]);

  const handleCardClick = () => {
    router.push(`/${basePath}/${encodeURIComponent(String(horse.id))}`);
  };

  const toggleFavorite = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    const next = !isFavorite;
    setIsFavorite(next);
    toggleFav.mutate({ id: String(horse.id), type: "offer" });
  };

  const formatPrice = (price: number) => {
    return Number.isFinite(price) ? price.toLocaleString("en-US") : "0";
  };

  const details = [
    horse.age ? t("age_years", { value: horse.age }) : null,
    horse.gender ? t("gender", { value: horse.gender }) : null,
    horse.coat ? t("coat", { value: horse.coat }) : null,
    horse.height !== undefined && horse.height !== null
      ? t("height_cm", { value: horse.height })
      : null,
  ].filter(Boolean) as string[];
    const session = useSession();

   const canShowFavorite = Boolean(session?.access_token);


  const FavoriteIcon = () => (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      className={`h-5 w-5 ${isFavorite ? "fill-current text-red-500" : ""}`}
      viewBox="0 0 24 24"
      fill={isFavorite ? "currentColor" : "none"}
      stroke="currentColor"
      strokeWidth="1.5"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.125 9 12 9 12s9-4.875 9-12z"
      />
    </svg>
  );

  return (
    <article
      className="group bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 relative cursor-pointer border border-slate-200 md:h-full flex flex-col"
      onClick={handleCardClick}
      dir={isRtl ? "rtl" : "ltr"}
    >
      <div className="h-1.5 w-full bg-[#0f5132]" />

      <div className="relative overflow-hidden h-56">
        <Image
          src={horse.img || HORSE_FALLBACK_IMAGE}
          alt={horse.title}
          fill
          sizes="(max-width: 768px) 100vw, 33vw"
          className="object-cover transition-transform duration-500 group-hover:scale-105"
        />

        {canShowFavorite && (
          <button
            type="button"
            className={`absolute top-3 z-10 h-10 w-10 rounded-full border border-slate-200 bg-white/95 grid place-items-center text-slate-600 shadow-sm transition-all duration-200 hover:shadow-md ${
              isRtl ? "left-3" : "right-3"
            }`}
            onClick={toggleFavorite}
            aria-label={
              isFavorite
                ? t("remove_favorite", { defaultValue: "إزالة من المفضلة" })
                : t("add_favorite", { defaultValue: "إضافة إلى المفضلة" })
            }
            title={
              isFavorite
                ? t("remove_favorite", { defaultValue: "إزالة من المفضلة" })
                : t("add_favorite", { defaultValue: "إضافة إلى المفضلة" })
            }
          >
            <FavoriteIcon />
          </button>
        )} 
      </div>

      <div className="p-4 text-start flex flex-col gap-3 flex-1">
        <div className="flex items-start justify-between gap-2">
          <h3
            className="font-bold text-base text-[#0f5132] leading-snug line-clamp-2"
            title={horse.title}
          >
            {horse.title}
          </h3>
          <span className="inline-flex items-center px-2.5 py-1 rounded-full border text-xs font-semibold whitespace-nowrap bg-emerald-50 text-emerald-700 border-emerald-200">
            {horse.type || "—"}
          </span>
        </div>

        <div className="flex flex-wrap items-center gap-2 text-xs"></div>

        <div className="text-xs text-slate-500 truncate">
          {horse.country || "—"}، {horse.city || "—"}
        </div>

        <div className="flex flex-wrap gap-2 text-xs text-slate-700">
          {horse.breed ? (
            <span className="rounded-lg bg-slate-100 px-2.5 py-1">
              {horse.breed}
            </span>
          ) : null}

          {details.map((label, index) => (
            <span
              key={`${label}-${index}`}
              className="rounded-lg bg-slate-100 px-2.5 py-1"
            >
              {label}
            </span>
          ))}
        </div>

        <div className="mt-auto flex items-center justify-between gap-3">
          <button
            type="button"
            className="inline-flex items-center rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-100"
            onClick={(e) => {
              e.stopPropagation();
              handleCardClick();
            }}
          >
            {t("details", { defaultValue: "تفاصيل الإعلان" })}
          </button>

          <div className="inline-flex items-center gap-1.5 text-sm font-bold text-[#0f5132]">
            {formatPrice(horse.price)}
            <Image
              src={priceIconSrc}
              width={16}
              height={16}
              alt={t("sar_alt", { defaultValue: "ريال سعودي" })}
              onError={() => {
                if (priceIconSrc !== DEFAULT_SAR_ICON) {
                  setPriceIconSrc(DEFAULT_SAR_ICON);
                }
              }}
            />
          </div>
        </div>
      </div>
    </article>
  );
}
