import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { createServerSupabase } from "@chowrest/db/server";
import { LeadForm } from "./lead-form";
import { PropertyMap } from "./property-map";
import { Gallery } from "./gallery";
import { Price } from "../../_currency";

const WHATSAPP_NUMBER = process.env.NEXT_PUBLIC_WHATSAPP_NUMBER ?? "66812345678";
const SITE = process.env.NEXT_PUBLIC_SITE_URL ?? "https://chowrest-property.com";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}): Promise<Metadata> {
  const { id } = await params;
  const supabase = await createServerSupabase();
  const { data } = await supabase
    .from("properties")
    .select("title, description, price, city, province, images, type")
    .eq("id", id)
    .maybeSingle();
  if (!data) return { title: "Listing not found" };
  const desc =
    data.description?.slice(0, 160) ??
    `${data.type} for sale${data.city ? ` in ${data.city}` : ""} — ฿${Number(data.price).toLocaleString()}`;
  const image = data.images?.[0];
  return {
    title: `${data.title} — Chowrest Property`,
    description: desc,
    alternates: { canonical: `${SITE}/p/${id}` },
    openGraph: {
      type: "article",
      url: `${SITE}/p/${id}`,
      title: data.title,
      description: desc,
      images: image ? [{ url: image }] : undefined,
    },
    twitter: {
      card: "summary_large_image",
      title: data.title,
      description: desc,
      images: image ? [image] : undefined,
    },
  };
}

export const dynamic = "force-dynamic";

export default async function ListingDetail({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const supabase = await createServerSupabase();
  const { data: property } = await supabase
    .from("properties")
    .select("*, profiles:agent_id (id, full_name, phone, avatar_url)")
    .eq("id", id)
    .maybeSingle();
  if (!property) notFound();

  const photos = property.images ?? [];
  const agent = (property as unknown as { profiles?: Agent | null }).profiles;
  const location = [property.address, property.city, property.province]
    .filter(Boolean)
    .join(", ");

  const waText = `Hi! I'm interested in "${property.title}" (https://chowrest-property.com/p/${property.id}). Could you share more details?`;
  const waHref = `https://wa.me/${WHATSAPP_NUMBER.replace(/\D/g, "")}?text=${encodeURIComponent(waText)}`;

  return (
    <article className="space-y-10">
      <Gallery photos={photos} title={property.title} />

      <div className="grid grid-cols-1 gap-10 md:grid-cols-3">
        <div className="md:col-span-2">
          <p className="text-sm font-medium uppercase tracking-wide text-zinc-500">
            {property.type}
            {property.featured ? " · Featured" : ""}
          </p>
          <h1 className="mt-1 text-3xl font-bold tracking-tight">
            {property.title}
          </h1>
          {location && <p className="mt-2 text-zinc-600">{location}</p>}

          <p className="mt-6 text-3xl font-semibold">
            <Price thb={property.price} />
            {property.special_deal && property.special_deal_label && (
              <span className="ml-3 align-middle text-sm font-semibold text-rose-600">
                {property.special_deal_label}
              </span>
            )}
          </p>

          <div className="mt-6 grid grid-cols-3 gap-3 text-sm">
            <Stat label="Bedrooms" value={property.bedrooms ?? "—"} />
            <Stat label="Bathrooms" value={property.bathrooms ?? "—"} />
            <Stat
              label="Area"
              value={
                property.area_sqm
                  ? `${property.area_sqm.toLocaleString()} m²`
                  : "—"
              }
            />
          </div>

          {property.description && (
            <p className="mt-6 whitespace-pre-line leading-relaxed text-zinc-700">
              {property.description}
            </p>
          )}

          {property.lat != null && property.lng != null && (
            <div className="mt-8">
              <h2 className="text-lg font-semibold">Location</h2>
              <div className="mt-3">
                <PropertyMap
                  lat={property.lat}
                  lng={property.lng}
                  title={property.title}
                />
              </div>
            </div>
          )}

          {property.amenities && property.amenities.length > 0 && (
            <div className="mt-8">
              <h2 className="text-lg font-semibold">Amenities</h2>
              <ul className="mt-3 grid grid-cols-2 gap-2 text-sm text-zinc-700 sm:grid-cols-3">
                {property.amenities.map((a) => (
                  <li
                    key={a}
                    className="rounded-md border border-zinc-200 bg-white px-3 py-1.5"
                  >
                    {a}
                  </li>
                ))}
              </ul>
            </div>
          )}

          <p className="mt-10 text-sm text-zinc-500">
            <a href="/" className="hover:text-zinc-900">
              ← Back to listings
            </a>
          </p>
        </div>

        <aside className="space-y-4">
          {agent && (
            <a
              href={`/agent/${agent.id}`}
              className="block rounded-xl border border-zinc-200 bg-white p-4 transition hover:shadow-sm"
            >
              <p className="text-xs uppercase tracking-wide text-zinc-500">
                Listing agent
              </p>
              <div className="mt-3 flex items-center gap-3">
                {agent.avatar_url ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={agent.avatar_url}
                    alt={agent.full_name ?? "Agent"}
                    className="h-10 w-10 rounded-full object-cover"
                  />
                ) : (
                  <div className="h-10 w-10 rounded-full bg-zinc-200" />
                )}
                <div>
                  <p className="text-sm font-medium">
                    {agent.full_name ?? "Agent"}
                  </p>
                  {agent.phone && (
                    <p className="text-xs text-zinc-500">{agent.phone}</p>
                  )}
                </div>
              </div>
            </a>
          )}

          <a
            href={waHref}
            target="_blank"
            rel="noopener noreferrer"
            className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-500 px-4 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-emerald-600"
          >
            <svg
              viewBox="0 0 24 24"
              width="18"
              height="18"
              aria-hidden
              fill="currentColor"
            >
              <path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.82 11.82 0 0 1 8.41 3.488 11.82 11.82 0 0 1 3.48 8.413c-.003 6.554-5.338 11.89-11.89 11.89a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634L2.9 21.116l3.754-1.923zm5.392-2.235c-.371 0-1.205-.119-2.652-.701-1.748-.781-3.012-2.395-3.119-2.535-.071-.094-.78-1.064-.78-2.029 0-.969.503-1.443.681-1.643.18-.2.388-.249.516-.249.13 0 .26.001.371.007.119.005.279-.045.435.331.169.413.575 1.426.625 1.531.05.103.087.224.018.351-.071.131-.107.213-.211.331-.107.118-.224.262-.32.351-.107.107-.218.222-.094.435.124.214.55.91 1.18 1.474.81.722 1.491.946 1.703 1.052.213.106.336.087.461-.052.124-.142.532-.62.673-.832.142-.213.282-.178.476-.107.193.071 1.226.578 1.435.683.213.106.355.16.408.249.05.087.05.508-.124.998-.178.488-1.025.929-1.435.991z" />
            </svg>
            Chat on WhatsApp
          </a>

          <div className="rounded-xl border border-zinc-200 bg-white p-4">
            <h2 className="text-base font-semibold">Request more info</h2>
            <p className="mt-1 text-sm text-zinc-500">
              We&apos;ll get back to you shortly.
            </p>
            <LeadForm
              propertyId={property.id}
              agentId={property.agent_id ?? null}
            />
          </div>
        </aside>
      </div>
    </article>
  );
}

type Agent = {
  id: string;
  full_name: string | null;
  phone: string | null;
  avatar_url: string | null;
};

function Stat({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="rounded-lg border border-zinc-200 bg-white p-3">
      <div className="text-xs uppercase tracking-wide text-zinc-500">
        {label}
      </div>
      <div className="mt-1 text-lg font-semibold">{value}</div>
    </div>
  );
}
