import Link from "next/link";
import Image from "next/image";
import {
  PROPERTY_TYPE_LABELS,
  LISTING_TYPE_LABELS,
  GRADE_LABELS,
  VAT_LABELS,
  formatRand,
  formatRate,
} from "@/lib/labels";

const LISTING_TYPE_COLOR: Record<string, string> = {
  TO_LET: "bg-[#bf2842]",
  FOR_SALE: "bg-brand",
  SERVICED: "bg-[#231f20]",
};

export type CardProperty = {
  id: number;
  title: string;
  type: string;
  listingType: string;
  grade: string | null;
  floor?: string | null;
  sizeM2: number;
  ratePerM2: number | null;
  monthlyRent: number | null;
  salePrice: number | null;
  parkingBays?: number | null;
  vatStatus: string;
  status: string;
  summary?: string | null;
  description?: string;
  area: { name: string; region: string };
  broker: { name: string; title: string; phone: string; photoUrl?: string | null } | null;
  amenities?: { id: number; name: string }[];
  photos: { url: string }[];
  _count?: { photos: number };
};

function initials(name: string) {
  return name
    .split(" ")
    .map((w) => w[0])
    .join("");
}

/** Headline figure split into value and unit so each carries its own weight. */
function headline(p: CardProperty) {
  const vat = VAT_LABELS[p.vatStatus];
  if (p.listingType === "FOR_SALE") {
    return p.salePrice ? { value: formatRand(p.salePrice), unit: vat } : { value: "POA", unit: "" };
  }
  const monthly = p.monthlyRent ?? (p.ratePerM2 ? p.ratePerM2 * p.sizeM2 : null);
  return monthly ? { value: formatRand(monthly), unit: `${vat} /mo` } : { value: "POA", unit: "" };
}

export function PropertyCard({ property }: { property: CardProperty }) {
  const hero = property.photos[0]?.url;
  const photoCount = property._count?.photos ?? property.photos.length;
  const amenities = (property.amenities ?? []).slice(0, 6);
  const rate = formatRate(property);
  const blurb = property.summary ?? property.description;
  const price = headline(property);

  return (
    <article className="flex flex-col overflow-hidden rounded border border-stone-200 bg-white transition hover:shadow-md sm:flex-row">
      {/* Image column: 38% of the row on desktop, full-bleed height. */}
      <Link
        href={`/properties/${property.id}`}
        aria-label={property.title}
        className="relative aspect-[438/200] w-full shrink-0 self-stretch bg-stone-100 sm:aspect-auto sm:w-[38%]"
      >
        {hero ? (
          <Image src={hero} alt={property.title} fill className="object-cover" sizes="(max-width: 640px) 100vw, 400px" />
        ) : (
          <div
            className="absolute inset-0"
            style={{
              backgroundImage: "repeating-linear-gradient(45deg, transparent 0 10px, rgba(57,133,176,0.12) 10px 11px)",
            }}
          />
        )}

        <div className="absolute top-2.5 left-2.5 flex gap-1.5">
          <span
            className={`rounded px-2 py-1 text-[12px] leading-none font-bold tracking-wide text-white uppercase ${LISTING_TYPE_COLOR[property.listingType]}`}
          >
            {LISTING_TYPE_LABELS[property.listingType]}
          </span>
          {property.grade && (
            <span className="rounded bg-[#231f20] px-2 py-1 text-[12px] leading-none font-bold tracking-wide text-white uppercase">
              {GRADE_LABELS[property.grade]} Grade
            </span>
          )}
        </div>

        {photoCount > 1 && (
          <span className="absolute right-2.5 bottom-2.5 flex items-center gap-1.5 rounded bg-black/55 px-2 py-1 text-[12px] font-medium tabular-nums text-white">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3Z" />
              <circle cx="12" cy="13" r="3" />
            </svg>
            1 / {photoCount}
          </span>
        )}
      </Link>

      {/* Detail column */}
      <div className="flex flex-1 flex-col px-6 pt-6 pb-4">
        <p className="text-[11px] font-semibold tracking-wide text-[#bf2842] uppercase">
          {property.floor ? property.floor : PROPERTY_TYPE_LABELS[property.type]}
        </p>

        <h3 className="mt-1 text-[20px] leading-snug text-black">
          <Link href={`/properties/${property.id}`} className="hover:text-brand">
            {property.title}
          </Link>
        </h3>

        <p className="mt-1 text-[13px] text-stone-500">
          {property.area.name}, {property.area.region}
        </p>

        {amenities.length > 0 && (
          <div className="mt-3 flex flex-wrap gap-1.5">
            {amenities.map((a) => (
              <span
                key={a.id}
                className="rounded bg-[#f4f2f0] px-2 py-1.5 text-[9px] leading-none font-semibold text-[#666]"
              >
                {a.name}
              </span>
            ))}
          </div>
        )}

        {blurb && <p className="mt-3 line-clamp-2 text-[14px] text-[#666]">{blurb}</p>}

        <div className="mt-3 flex items-baseline gap-1.5">
          <span className="text-[24px] leading-none tabular-nums text-black">{price.value}</span>
          {price.unit && <span className="text-[12px] font-medium text-[#666]">{price.unit}</span>}
        </div>

        <div className="mt-2 flex flex-wrap gap-x-6 gap-y-1 text-[14px] font-semibold tabular-nums text-black">
          {rate && <span>Rate: {rate}</span>}
          <span>Size: {property.sizeM2.toLocaleString()} m²</span>
          {property.parkingBays != null && <span>Parkings: {property.parkingBays}</span>}
        </div>

        <div className="mt-auto flex flex-wrap items-center justify-between gap-3 pt-4">
          {property.broker ? (
            <div className="flex items-center gap-2.5">
              {property.broker.photoUrl ? (
                <Image
                  src={property.broker.photoUrl}
                  alt={property.broker.name}
                  width={36}
                  height={36}
                  className="h-9 w-9 flex-none rounded-full object-cover"
                />
              ) : (
                <span className="flex h-9 w-9 flex-none items-center justify-center rounded-full bg-brand text-xs font-bold text-white">
                  {initials(property.broker.name)}
                </span>
              )}
              <div className="text-[13px] leading-tight">
                <p className="font-semibold text-[#231f20]">{property.broker.name}</p>
                <p className="text-[12px] text-stone-400">{property.broker.title}</p>
              </div>
            </div>
          ) : (
            <span />
          )}

          <div className="flex gap-2.5">
            {property.broker && (
              <a
                href={`tel:${property.broker.phone.replace(/\s/g, "")}`}
                className="flex h-[35px] w-[115px] items-center justify-center rounded-md bg-black/5 text-[14px] font-semibold tracking-wide text-black uppercase hover:bg-black/10"
              >
                Call now
              </a>
            )}
            <Link
              href={`/contact?propertyId=${property.id}`}
              className="flex h-[35px] w-[115px] items-center justify-center rounded-md bg-brand text-[14px] font-semibold tracking-wide text-white uppercase hover:bg-brand-deep"
            >
              Enquire
            </Link>
          </div>
        </div>
      </div>
    </article>
  );
}
