import Link from "next/link";
import { notFound } from "next/navigation";
import StatusBadge from "@/components/StatusBadge";
import Gallery from "@/components/Gallery";
import PropertyContactCard from "@/components/PropertyContactCard";
import { CheckIcon } from "@/components/Icons";
import { formatPrice } from "@/lib/mock-data";
import { serverExecute, serverExecuteSafe } from "@/lib/api/server";
import type { Property, Landlord, Review, Paginated } from "@/lib/types";
import ReviewsSection from "@/components/ReviewsSection";

interface ReviewSummary { average: number; total: number; starCounts: { star: number; count: number }[] }

export default async function PropertyDetailsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;

  let property: Property;
  try {
    property = await serverExecute<Property>("property.find-one", { id });
  } catch {
    notFound();
  }

  const [landlord, reviewPage, summary] = await Promise.all([
    serverExecuteSafe<Landlord>("landlord.find-one", { id: property.landlordId }),
    serverExecuteSafe<Paginated<Review>>("review.find-by-target", { targetId: id, limit: 5 }),
    serverExecuteSafe<ReviewSummary>("review.get-summary", { targetId: id }),
  ]);

  return (
    <div className="max-w-6xl mx-auto px-6 py-8">
      <div className="text-sm text-ink-soft mb-4">
        <Link href="/" className="hover:text-forest">Home</Link>
        {" / "}
        <Link href="/listings" className="hover:text-forest">{property.town}</Link>
        {" / "}
        {property.title}
      </div>

      <div className="flex flex-wrap justify-between items-start gap-5 mb-5">
        <div>
          <div className="mb-3">
            <StatusBadge
              status={property.status}
              label={property.status === "verified" ? "Verified property" : undefined}
            />
          </div>
          <h1 className="text-3xl lg:text-4xl mb-1">{property.title}, {property.address.split(",")[0]}</h1>
          <p className="text-ink-soft">{property.town}, Eastern Region</p>
        </div>
        <div className="font-mono text-xl lg:text-2xl font-semibold text-forest whitespace-nowrap">
          {formatPrice(property.price)}{" "}
          <span className="text-xs font-normal text-ink-soft uppercase">/ month</span>
        </div>
      </div>

      <Gallery images={property.images} showStamp={property.status === "verified"} />

      <div className="grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-10 items-start">
        <div>
          <section className="mb-10">
            <h2 className="text-2xl mb-3">About this property</h2>
            <p className="text-ink-soft text-[15px]">{property.description}</p>
          </section>

          <section className="mb-10">
            <h2 className="text-2xl mb-3">Amenities</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
              {property.amenities.map((amenity) => (
                <div key={amenity} className="flex items-center gap-2 text-sm bg-white border border-mist rounded-sm p-3">
                  <CheckIcon className="w-[18px] h-[18px] text-forest shrink-0" />
                  {amenity}
                </div>
              ))}
            </div>
          </section>

          <section className="mb-10">
            <h2 className="text-2xl mb-3">Property details</h2>
            <ul className="flex flex-col gap-3">
              <Fact label="House type"   value={property.type} />
              <Fact label="Bathrooms"    value={String(property.bathrooms)} />
              <Fact label="Furnishing"   value={property.furnishing} />
              <Fact label="Availability" value={property.availability} />
              {property.verifiedDate && <Fact label="Verified on" value={property.verifiedDate} />}
              <Fact label="Listing ID"   value={`VL-${property.id.slice(0, 6).toUpperCase()}`} last />
            </ul>
          </section>

          <section>
            <h2 className="text-2xl mb-3">Location</h2>
            <div className="bg-gradient-to-br from-mist to-sage border border-mist rounded-lg min-h-[220px] flex items-center justify-center">
              <span className="font-mono text-xs uppercase tracking-widest text-ink-soft">
                Map placeholder — {property.address}
              </span>
            </div>
          </section>
        </div>

        {/* Reviews */}
        <section className="mb-10">
          <ReviewsSection
            targetId={property.id}
            targetName={property.title}
            targetType="property"
            initialReviews={reviewPage?.items ?? []}
            averageRating={summary?.average ?? 0}
            showWriteReview={false}
          />
        </section>

        {/* Interactive contact card */}
        <PropertyContactCard
          landlord={landlord ?? undefined}
          propertyTitle={property.title}
          propertyId={property.id}
        />
      </div>
    </div>
  );
}

function Fact({ label, value, last }: { label: string; value: string; last?: boolean }) {
  return (
    <li className={`flex justify-between text-sm pb-3 ${last ? "" : "border-b border-mist"}`}>
      <span className="text-ink-soft">{label}</span>
      <span className="font-mono font-medium">{value}</span>
    </li>
  );
}
