import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { prisma } from "@/lib/prisma";
import { PropertyCard } from "@/components/PropertyCard";
import { PropertyGallery } from "@/components/PropertyGallery";
import { SidebarEnquiryForm } from "@/components/SidebarEnquiryForm";
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]",
};

async function getProperty(id: number) {
  return prisma.property.findUnique({
    where: { id },
    include: {
      area: true,
      broker: true,
      amenities: true,
      photos: { orderBy: { sortOrder: "asc" } },
    },
  });
}

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const property = await getProperty(Number(id));
  if (!property) return {};
  return {
    title: `${property.title} | ${property.area.name} ${PROPERTY_TYPE_LABELS[property.type]} ${LISTING_TYPE_LABELS[property.listingType]} | Richland Properties`,
    description: property.summary ?? property.description.slice(0, 155),
  };
}

function toStringArray(v: unknown): string[] {
  return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
}

export default async function PropertyDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const propertyId = Number(id);
  const property = await getProperty(propertyId);
  if (!property) notFound();

  const similar = await prisma.property.findMany({
    where: { type: property.type, id: { not: property.id }, status: { in: ["ACTIVE", "UNDER_OFFER"] } },
    include: {
      area: true,
      broker: true,
      amenities: true,
      photos: { where: { isHero: true }, take: 1 },
      _count: { select: { photos: true } },
    },
    take: 3,
  });

  const quickFacts = toStringArray(property.quickFacts);
  const keySpecs = toStringArray(property.keySpecs);
  const hasMap = property.latitude != null && property.longitude != null;
  const rate = formatRate(property);

  const isSale = property.listingType === "FOR_SALE";
  const monthly = property.monthlyRent ?? (property.ratePerM2 ? property.ratePerM2 * property.sizeM2 : null);
  const headlineValue = isSale ? (property.salePrice ? formatRand(property.salePrice) : "POA") : monthly ? formatRand(monthly) : "POA";
  const headlineUnit = isSale ? VAT_LABELS[property.vatStatus] : `Per month (${VAT_LABELS[property.vatStatus]})`;

  const stats: [string, string][] = [];
  if (rate) stats.push(["Rate", rate]);
  stats.push(["Size", `${property.sizeM2.toLocaleString()} m²`]);
  if (property.parkingBays != null) stats.push(["Parking", `${property.parkingBays} bays`]);
  if (property.grade) stats.push(["Grade", `${GRADE_LABELS[property.grade]} Grade`]);
  if (property.floor) stats.push(["Unit", property.floor]);
  stats.push(["Address", property.addressLine]);
  stats.push(["Area", `${property.area.name}, ${property.area.region}`]);
  if (property.buildingName) stats.push(["Building", property.buildingName]);
  if (property.availabilityDate) {
    stats.push(["Available", new Date(property.availabilityDate).toLocaleDateString("en-ZA", { day: "numeric", month: "short", year: "numeric" })]);
  }

  return (
    <main className="mx-auto max-w-6xl px-6 py-8">
      <nav className="text-[13px] text-stone-400">
        <Link href="/properties" className="hover:text-brand">
          Listings
        </Link>{" "}
        / <span className="text-stone-600">{property.title}</span>
      </nav>

      {/* Title row */}
      <div className="mt-4 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-[32px] leading-tight text-black">{property.title}</h1>
          <div className="mt-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>
            )}
            <span className="rounded bg-[#f4f2f0] px-2 py-1 text-[12px] leading-none font-semibold text-[#666] uppercase">
              {PROPERTY_TYPE_LABELS[property.type]}
            </span>
          </div>
        </div>

        <div className="flex gap-2.5">
          {property.broker && (
            <a
              href={`tel:${property.broker.phone.replace(/\s/g, "")}`}
              className="flex h-[35px] items-center justify-center rounded-md bg-black/5 px-5 text-[14px] font-semibold text-black hover:bg-black/10"
            >
              Call
            </a>
          )}
          <a
            href="#enquire"
            className="flex h-[35px] items-center justify-center rounded-md bg-brand px-5 text-[14px] font-semibold text-white hover:bg-brand-deep"
          >
            Message
          </a>
        </div>
      </div>

      {/* Split gallery */}
      <div className="mt-6">
        <PropertyGallery photos={property.photos} title={property.title} />
      </div>

      {/* Content + sidebar */}
      <div className="mt-10 flex flex-col gap-12 lg:flex-row">
        <div className="min-w-0 flex-1">
          <h2 className="text-[24px] text-black">Listing Details</h2>

          <div className="mt-5">
            <p className="text-[40px] leading-none tabular-nums text-black">{headlineValue}</p>
            <p className="mt-1.5 text-[12px] font-medium text-[#666]">{headlineUnit}</p>
          </div>

          <table className="mt-6 w-full text-[16px]">
            <tbody>
              {stats.map(([label, value]) => (
                <tr key={label} className="border-b border-stone-100">
                  <th scope="row" className="w-40 py-3 text-left font-normal text-[#666]">
                    {label}
                  </th>
                  <td className="py-3 text-[#333]">{value}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {property.summary && <p className="mt-8 text-[16px] text-[#333]">{property.summary}</p>}
          <p className="mt-4 text-[16px] leading-relaxed text-[#666]">{property.description}</p>

          {property.amenities.length > 0 && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Facilities</h2>
              <div className="mt-4 flex flex-wrap gap-2">
                {property.amenities.map((a) => (
                  <span key={a.id} className="rounded bg-[#f4f2f0] px-3 py-2 text-[13px] font-semibold text-[#666]">
                    {a.name}
                  </span>
                ))}
              </div>
            </section>
          )}

          {quickFacts.length > 0 && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Quick Facts</h2>
              <ul className="mt-4 grid grid-cols-1 gap-x-8 gap-y-2 text-[15px] text-[#666] sm:grid-cols-2">
                {quickFacts.map((f, i) => (
                  <li key={i}>• {f}</li>
                ))}
              </ul>
            </section>
          )}

          {keySpecs.length > 0 && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Key Specs &amp; Features</h2>
              <ul className="mt-4 grid grid-cols-1 gap-x-8 gap-y-2 text-[15px] text-[#666] sm:grid-cols-2">
                {keySpecs.map((f, i) => (
                  <li key={i}>• {f}</li>
                ))}
              </ul>
            </section>
          )}

          {property.idealBusinesses && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Ideal Businesses</h2>
              <p className="mt-3 text-[15px] text-[#666]">{property.idealBusinesses}</p>
            </section>
          )}

          {property.locationHighlights && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Location Highlights</h2>
              <p className="mt-3 text-[15px] text-[#666]">{property.locationHighlights}</p>
            </section>
          )}

          {property.buildingDescription && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Building Description</h2>
              <p className="mt-3 text-[15px] text-[#666]">{property.buildingDescription}</p>
            </section>
          )}

          {hasMap && (
            <section className="mt-10">
              <h2 className="text-[24px] text-black">Location</h2>
              <a
                href={`https://www.google.com/maps?q=${property.latitude},${property.longitude}`}
                target="_blank"
                rel="noopener noreferrer"
                className="mt-4 flex h-40 items-center justify-center rounded border border-stone-200 bg-[#f4f2f0] text-sm font-medium text-brand hover:border-brand"
              >
                View on Google Maps →
              </a>
            </section>
          )}
        </div>

        {/* Sidebar */}
        <aside className="w-full shrink-0 lg:w-[320px]">
          <div className="flex flex-col gap-6 lg:sticky lg:top-24">
            {property.broker && (
              <div className="rounded border border-stone-200 bg-white p-5">
                <div className="flex items-start gap-4">
                  {property.broker.photoUrl ? (
                    <Image
                      src={property.broker.photoUrl}
                      alt={property.broker.name}
                      width={96}
                      height={96}
                      className="h-24 w-24 flex-none rounded-md object-cover"
                    />
                  ) : (
                    <span className="flex h-24 w-24 flex-none items-center justify-center rounded-md bg-brand text-xl font-bold text-white">
                      {property.broker.name.split(" ").map((w) => w[0]).join("")}
                    </span>
                  )}
                  <div className="min-w-0">
                    <h3 className="text-[18px] leading-tight font-semibold text-[#231f20]">{property.broker.name}</h3>
                    <p className="mt-1 text-[13px] text-stone-500">{property.broker.title}</p>
                  </div>
                </div>
                <p className="mt-4 text-[13px] text-stone-500">
                  {property.broker.name.split(" ")[0]} is your broker for this listing. Get in touch to arrange a viewing.
                </p>
                <dl className="mt-4 space-y-1.5 text-[13px]">
                  <div className="flex gap-2">
                    <dt className="w-16 flex-none text-stone-400">Mobile:</dt>
                    <dd>
                      <a href={`tel:${property.broker.phone.replace(/\s/g, "")}`} className="font-semibold text-brand hover:text-brand-deep">
                        {property.broker.phone}
                      </a>
                    </dd>
                  </div>
                  <div className="flex gap-2">
                    <dt className="w-16 flex-none text-stone-400">Email:</dt>
                    <dd className="min-w-0 truncate">
                      <a href={`mailto:${property.broker.email}`} className="font-semibold text-brand hover:text-brand-deep">
                        {property.broker.email}
                      </a>
                    </dd>
                  </div>
                </dl>
              </div>
            )}

            <div id="enquire" className="scroll-mt-24">
              <SidebarEnquiryForm propertyId={property.id} area={property.area.name} type={property.type} />
            </div>

            <div className="rounded border border-stone-200 bg-white p-5">
              <h2 className="text-[16px] font-semibold text-[#231f20]">Explore {property.area.name}</h2>
              <p className="mt-2 text-[13px] text-stone-500">See other available space in this area.</p>
              <Link
                href={`/area-guides/${encodeURIComponent(property.area.name)}`}
                className="mt-3 inline-block text-[14px] font-semibold text-brand hover:text-brand-deep"
              >
                View area guide →
              </Link>
            </div>
          </div>
        </aside>
      </div>

      {similar.length > 0 && (
        <section className="mt-16 border-t border-stone-200 pt-10">
          <h2 className="text-[24px] text-black">Similar properties</h2>
          <div className="mt-6 flex flex-col gap-6">
            {similar.map((p) => (
              <PropertyCard key={p.id} property={p} />
            ))}
          </div>
        </section>
      )}
    </main>
  );
}
