/**
 * Public property detail page.
 *
 * Serves as the landing page for property links shared via WhatsApp.
 * Bilingual (en/ar) based on the [lang] route segment.
 */

import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { prisma } from "@/lib/db";
import type { Lang } from "@/lib/config";
import { getCanonicalUrl, getAlternateUrls } from "@/lib/url";

// ─── Types ───────────────────────────────────────────────────────────

interface Props {
  params: { lang: Lang; id: string };
}

// ─── Metadata ────────────────────────────────────────────────────────

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const property = await prisma.property.findUnique({
    where: { id: params.id },
    select: {
      titleEn: true,
      titleAr: true,
      descriptionEn: true,
      descriptionAr: true,
    },
  });

  if (!property) return { title: "Property Not Found" };

  const isAr = params.lang === "ar";
  const title = isAr ? property.titleAr || property.titleEn : property.titleEn;
  const description = isAr
    ? property.descriptionAr || property.descriptionEn || ""
    : property.descriptionEn || "";

  return {
    title: `${title} | Mawidi`,
    description: description.slice(0, 160),
    alternates: {
      languages: getAlternateUrls(`/properties/${params.id}`),
      canonical: getCanonicalUrl(params.lang, `/properties/${params.id}`),
    },
  };
}

// ─── Page ────────────────────────────────────────────────────────────

export default async function PropertyDetailPage({ params }: Props) {
  const { lang, id } = params;
  const isAr = lang === "ar";

  const property = await prisma.property.findUnique({
    where: { id },
    include: {
      images: { orderBy: { sortOrder: "asc" }, take: 10 },
    },
  });

  if (!property || property.status === "OFF_MARKET") {
    notFound();
  }

  const title = isAr ? property.titleAr || property.titleEn : property.titleEn;
  const description = isAr
    ? property.descriptionAr || property.descriptionEn
    : property.descriptionEn || property.descriptionAr;

  const price = property.price
    ? `${Number(property.price).toLocaleString()} ${property.currency}`
    : isAr
      ? "السعر عند الطلب"
      : "Price on request";

  const listingLabel = isAr
    ? property.listingType === "RENT"
      ? "للإيجار"
      : "للبيع"
    : property.listingType === "RENT"
      ? "For Rent"
      : "For Sale";

  const labels = {
    bedrooms: isAr ? "غرف النوم" : "Bedrooms",
    bathrooms: isAr ? "الحمامات" : "Bathrooms",
    area: isAr ? "المساحة" : "Area",
    district: isAr ? "المنطقة" : "District",
    city: isAr ? "المدينة" : "City",
    type: isAr ? "النوع" : "Type",
    furnishing: isAr ? "التأثيث" : "Furnishing",
    reference: isAr ? "الرقم المرجعي" : "Reference",
    description: isAr ? "الوصف" : "Description",
    contactUs: isAr ? "تواصل معنا" : "Contact Us",
    bookViewing: isAr ? "احجز معاينة" : "Book a Viewing",
    notFound: isAr ? "العقار غير موجود" : "Property not found",
  };

  return (
    <main dir={isAr ? "rtl" : "ltr"} className="min-h-screen bg-gray-50">
      {/* Hero / Image Gallery */}
      {property.images.length > 0 ? (
        <div className="relative w-full h-64 sm:h-80 md:h-96 bg-gray-200 overflow-hidden">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={property.images[0].url}
            alt={title}
            className="w-full h-full object-cover"
          />
          {property.images.length > 1 && (
            <div className="absolute bottom-3 right-3 bg-black/60 text-white text-xs px-2 py-1 rounded">
              +{property.images.length - 1}
            </div>
          )}
        </div>
      ) : (
        <div className="w-full h-48 bg-gray-200 flex items-center justify-center text-gray-400 text-lg">
          {isAr ? "لا توجد صور" : "No images"}
        </div>
      )}

      {/* Content */}
      <div className="max-w-4xl mx-auto px-4 py-8">
        {/* Title + Price + Badge */}
        <div className="flex flex-wrap items-start justify-between gap-4 mb-6">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">
              {title}
            </h1>
            {property.district && (
              <p className="text-gray-500 mt-1">
                {property.district}, {property.city}
              </p>
            )}
          </div>
          <div className="text-right">
            <p className="text-2xl font-bold text-blue-600">{price}</p>
            <span className="inline-block mt-1 text-xs font-semibold px-3 py-1 rounded-full bg-blue-100 text-blue-700">
              {listingLabel}
            </span>
          </div>
        </div>

        {/* Key Specs Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-8">
          {property.bedrooms != null && (
            <SpecCard
              label={labels.bedrooms}
              value={String(property.bedrooms)}
            />
          )}
          {property.bathrooms != null && (
            <SpecCard
              label={labels.bathrooms}
              value={String(property.bathrooms)}
            />
          )}
          {property.builtUpArea != null && (
            <SpecCard
              label={labels.area}
              value={`${Number(property.builtUpArea)} sqm`}
            />
          )}
          <SpecCard
            label={labels.type}
            value={property.propertyType.replace(/_/g, " ")}
          />
        </div>

        {/* Details Table */}
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-8">
          <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-3 text-sm">
            {property.district && (
              <DetailRow label={labels.district} value={property.district} />
            )}
            <DetailRow label={labels.city} value={property.city} />
            <DetailRow
              label={labels.furnishing}
              value={property.furnishing.replace(/_/g, " ")}
            />
            {property.referenceNumber && (
              <DetailRow
                label={labels.reference}
                value={property.referenceNumber}
              />
            )}
          </dl>
        </div>

        {/* Description */}
        {description && (
          <div className="bg-white rounded-lg shadow-sm border p-6 mb-8">
            <h2 className="text-lg font-semibold mb-3">{labels.description}</h2>
            <p className="text-gray-700 whitespace-pre-line leading-relaxed">
              {description}
            </p>
          </div>
        )}

        {/* CTA */}
        <div className="text-center py-6">
          <a
            href={`https://wa.me/447450018521?text=${encodeURIComponent(
              isAr
                ? `مرحبا، أبي أستفسر عن العقار: ${title} (${property.referenceNumber || property.id})`
                : `Hi, I'd like to inquire about: ${title} (${property.referenceNumber || property.id})`,
            )}`}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 text-white font-semibold px-8 py-3 rounded-lg transition-colors"
          >
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
              <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z" />
              <path d="M12 0C5.373 0 0 5.373 0 12c0 2.625.846 5.059 2.284 7.034L.789 23.492a.5.5 0 00.611.611l4.458-1.495A11.944 11.944 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 22c-2.347 0-4.518-.801-6.24-2.144l-.436-.348-2.672.896.896-2.672-.348-.436A9.956 9.956 0 012 12C2 6.486 6.486 2 12 2s10 4.486 10 10-4.486 10-10 10z" />
            </svg>
            {labels.bookViewing}
          </a>
        </div>
      </div>
    </main>
  );
}

// ─── Sub-components ──────────────────────────────────────────────────

function SpecCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-white rounded-lg shadow-sm border p-4 text-center">
      <p className="text-xl font-bold text-gray-900">{value}</p>
      <p className="text-xs text-gray-500 mt-1">{label}</p>
    </div>
  );
}

function DetailRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex justify-between border-b border-gray-100 pb-2">
      <dt className="text-gray-500">{label}</dt>
      <dd className="font-medium text-gray-900">{value}</dd>
    </div>
  );
}
