"use client";

import { useState } from "react";
import type { PropertyCardProps } from "@chowrest/ui";
import { useCurrency } from "./_currency";

export function PropertyCardLive(props: PropertyCardProps) {
  const { format } = useCurrency();
  const {
    title,
    price,
    type,
    bedrooms,
    bathrooms,
    areaSqm,
    city,
    province,
    imageUrl,
    href,
    featured,
    specialDealLabel,
  } = props;

  // Some Supabase image URLs 404 (object missing in storage). Fall through
  // to the same "No photo" state as listings with no imageUrl at all,
  // rather than rendering a broken-image icon or a generic stock photo.
  const [imgFailed, setImgFailed] = useState(false);
  const showImage = !!imageUrl && !imgFailed;

  const location = [city, province].filter(Boolean).join(", ");
  const badge =
    specialDealLabel || (featured ? "Featured" : null) || (type ? type : null);
  const Wrapper: "a" | "div" = href ? "a" : "div";

  return (
    <Wrapper
      href={href}
      className="group block overflow-hidden rounded-[14px] border border-border bg-surface transition duration-300 hover:-translate-y-1 hover:border-accent"
    >
      <div className="relative aspect-[16/10] overflow-hidden bg-border">
        {showImage ? (
          /* eslint-disable-next-line @next/next/no-img-element */
          <img
            src={imageUrl}
            alt={title}
            onError={() => setImgFailed(true)}
            className="h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-105"
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center text-[13px] uppercase tracking-[0.12em] text-text-muted">
            No photo
          </div>
        )}
        {badge && (
          <span className="absolute left-4 top-4 rounded-full bg-text/85 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.1em] text-bg backdrop-blur">
            {badge}
          </span>
        )}
      </div>
      <div className="px-6 pb-6 pt-5">
        <div className="font-serif text-[28px] font-normal leading-none mb-2.5">
          {format(price)}
        </div>
        <div className="text-[15px] font-medium text-text mb-1">{title}</div>
        {location && (
          <div className="text-[13px] text-text-muted mb-3.5">{location}</div>
        )}
        <div className="flex gap-3.5 border-t border-border pt-3.5 text-[13px] text-text-muted">
          {bedrooms != null && <span>{bedrooms} bed</span>}
          {bathrooms != null && <span>{bathrooms} bath</span>}
          {areaSqm != null && (
            <span>{areaSqm.toLocaleString()} sqm</span>
          )}
        </div>
      </div>
    </Wrapper>
  );
}
