import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { ArrowLeft, BedDouble, Building2, CalendarCheck, Check, MapPin, Tag } from "lucide-react";
import { getProperty, properties } from "@/lib/properties";
import { LeadForm } from "@/components/lead-form";
import { PropertyCard } from "@/components/property-card";

export const Route = createFileRoute("/properties/$slug")({
  loader: ({ params }) => {
    const p = getProperty(params.slug);
    if (!p) throw notFound();
    return { property: p };
  },
  head: ({ loaderData, params }) => {
    const p = loaderData?.property;
    const title = p ? `${p.name} in ${p.location} — from ${p.priceFrom} | Zamelect` : "Property";
    const description = p
      ? `${p.name} by ${p.developer} in ${p.location}. ${p.bedrooms}, ${p.type.toLowerCase()}, ${p.status}. From ${p.priceFrom}. Book a private viewing with Zamelect Properties.`
      : "Zamelect property";
    return {
      meta: [
        { title },
        { name: "description", content: description },
        { property: "og:title", content: title },
        { property: "og:description", content: description },
        { property: "og:type", content: "product" },
        { property: "og:url", content: `/properties/${params.slug}` },
        ...(p ? [{ property: "og:image", content: p.image }] : []),
      ],
      links: [{ rel: "canonical", href: `/properties/${params.slug}` }],
      scripts: p
        ? [
            {
              type: "application/ld+json",
              children: JSON.stringify({
                "@context": "https://schema.org",
                "@type": "Product",
                name: p.name,
                description: p.tagline,
                brand: p.developer,
                image: p.image,
                offers: {
                  "@type": "Offer",
                  priceCurrency: "AED",
                  price: p.priceFrom.replace(/[^0-9]/g, "") + "000",
                  availability: "https://schema.org/InStock",
                },
              }),
            },
          ]
        : undefined,
    };
  },
  component: PropertyPage,
  notFoundComponent: () => (
    <div className="pt-40 pb-24 container-luxe text-center">
      <h1 className="font-display text-4xl">Property not found</h1>
      <Link to="/properties" className="mt-6 inline-block underline">
        Back to properties
      </Link>
    </div>
  ),
  errorComponent: ({ error }) => (
    <div className="pt-40 pb-24 container-luxe text-center">
      <p>{error.message}</p>
    </div>
  ),
});

function PropertyPage() {
  const { property } = Route.useLoaderData();
  const related = properties.filter((p) => p.slug !== property.slug).slice(0, 3);

  return (
    <div className="pt-24 pb-24">
      <div className="container-luxe">
        <Link
          to="/properties"
          className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
        >
          <ArrowLeft className="h-4 w-4" /> All properties
        </Link>
      </div>

      <div className="mt-6 relative">
        <img
          src={property.image}
          alt={`${property.name} in ${property.location}`}
          width={1600}
          height={900}
          className="h-[52svh] w-full object-cover"
        />
      </div>

      <div className="container-luxe -mt-24 relative">
        <div className="rounded-3xl border border-border bg-background p-8 sm:p-12 shadow-luxe">
          <div className="grid gap-10 lg:grid-cols-[1.4fr_1fr]">
            <div>
              <div className="flex flex-wrap items-center gap-2 text-[0.7rem] uppercase tracking-[0.18em]">
                <span className="rounded-full bg-gold/20 px-3 py-1 text-gold">{property.status}</span>
                <span className="text-muted-foreground">{property.developer}</span>
              </div>
              <h1 className="mt-4 font-display text-4xl font-semibold leading-tight sm:text-5xl">
                {property.name}
              </h1>
              <p className="mt-3 flex items-center gap-2 text-muted-foreground">
                <MapPin className="h-4 w-4" /> {property.location}, Dubai
              </p>

              <p className="mt-6 text-lg text-foreground/85">{property.tagline}</p>

              <div className="mt-10 grid grid-cols-2 gap-6 sm:grid-cols-4 border-y border-border py-6">
                <Stat icon={Tag} label="From" value={property.priceFrom} />
                <Stat icon={BedDouble} label="Bedrooms" value={property.bedrooms} />
                <Stat icon={Building2} label="Type" value={property.type} />
                <Stat icon={CalendarCheck} label="Handover" value={property.handover} />
              </div>

              <div className="mt-10">
                <h2 className="font-display text-2xl font-semibold">Highlights</h2>
                <ul className="mt-5 grid gap-3 sm:grid-cols-2">
                  {property.highlights.map((h: string) => (
                    <li key={h} className="flex items-start gap-3 text-sm">
                      <span className="mt-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-gold/20 text-gold">
                        <Check className="h-3 w-3" />
                      </span>
                      {h}
                    </li>
                  ))}
                </ul>
              </div>

              <div className="mt-10">
                <h2 className="font-display text-2xl font-semibold">About this property</h2>
                <p className="mt-4 text-muted-foreground leading-relaxed">
                  {property.name} is a {property.status.toLowerCase()} {property.type.toLowerCase()}
                  {" "}development by {property.developer}, located in the sought-after {property.location}
                  {" "}district of Dubai. With handover scheduled for {property.handover}, this project
                  {" "}offers a compelling combination of location, developer track record and
                  {" "}investment upside. Speak with a Zamelect advisor for the latest availability,
                  {" "}payment plans and floor plates.
                </p>
              </div>
            </div>

            <aside className="rounded-2xl bg-secondary p-6 sm:p-8 h-fit lg:sticky lg:top-28">
              <h3 className="font-display text-xl font-semibold">Request details & payment plan</h3>
              <p className="mt-2 text-sm text-muted-foreground">
                Receive floor plans, brochure and payment schedule within one business hour.
              </p>
              <div className="mt-6">
                <LeadForm compact defaultInterest={`${property.name} — ${property.location}`} />
              </div>
            </aside>
          </div>
        </div>

        <section className="mt-24">
          <h2 className="font-display text-3xl font-semibold">You might also like</h2>
          <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {related.map((p) => (
              <PropertyCard key={p.slug} property={p} />
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}

function Stat({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
}) {
  return (
    <div>
      <div className="flex items-center gap-2 text-[0.7rem] uppercase tracking-[0.18em] text-muted-foreground">
        <Icon className="h-3.5 w-3.5" /> {label}
      </div>
      <div className="mt-2 font-display text-lg font-semibold">{value}</div>
    </div>
  );
}
