import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { PropertyCard } from "@/components/PropertyCard";
import { PROPERTIES, LOCATIONS } from "@/lib/properties";
import { PageHeader } from "./about";

export const Route = createFileRoute("/residential")({
  head: () => ({
    meta: [
      { title: "Luxury Residential Properties in Pune — Apartments, Villas & Penthouses" },
      { name: "description", content: "Browse premium 2/3/4 BHK apartments, luxury villas and penthouses in Baner, Balewadi, Bavdhan, Wakad and Hinjewadi." },
    ],
  }),
  component: () => <PropertyListing kind="Residential" />,
});

export function PropertyListing({ kind }: { kind: "Residential" | "Commercial" }) {
  const [loc, setLoc] = useState("All");
  const [budget, setBudget] = useState("All");
  const [type, setType] = useState("All");

  // Memoize the base list so downstream useMemo has a stable dependency
  const all = useMemo(() => PROPERTIES.filter((p) => p.type === kind), [kind]);
  const types = useMemo(() => ["All", ...Array.from(new Set(all.map((p) => p.category)))], [all]);

  const filtered = useMemo(() => {
    return all.filter((p) => {
      if (loc !== "All" && p.location !== loc) return false;
      if (type !== "All" && p.category !== type) return false;
      if (budget === "u100" && p.budget >= 100) return false;
      if (budget === "100-200" && (p.budget < 100 || p.budget > 200)) return false;
      if (budget === "200-400" && (p.budget < 200 || p.budget > 400)) return false;
      if (budget === "400+" && p.budget < 400) return false;
      return true;
    });
  }, [all, loc, type, budget]);

  // Reset filters when kind changes to prevent stale filter state hiding all cards
  const [prevKind, setPrevKind] = useState(kind);
  if (prevKind !== kind) {
    setPrevKind(kind);
    setLoc("All");
    setBudget("All");
    setType("All");
  }

  return (
    <div>
      <PageHeader title={`${kind} Properties`} subtitle={kind === "Residential" ? "Premium homes for families who value craftsmanship, location and community." : "Investment-grade office and retail spaces in Pune's growth corridors."} />

      <section className="container mx-auto px-5 -mt-8 relative z-10">
        <div className="bg-card border border-gold/30 rounded-2xl shadow-luxury p-5 grid grid-cols-1 md:grid-cols-3 gap-3">
          <Select label="Location" value={loc} onChange={setLoc} options={["All", ...LOCATIONS]} />
          <Select label="Property Type" value={type} onChange={setType} options={types} />
          <Select label="Budget" value={budget} onChange={setBudget} options={[
            { v: "All", l: "Any budget" },
            { v: "u100", l: "Under ₹1 Cr" },
            { v: "100-200", l: "₹1 Cr – ₹2 Cr" },
            { v: "200-400", l: "₹2 Cr – ₹4 Cr" },
            { v: "400+", l: "₹4 Cr+" },
          ]} />
        </div>
      </section>

      <section className="container mx-auto px-5 py-16">
        <div className="flex items-center justify-between mb-6">
          <p className="text-sm text-muted-foreground">{filtered.length} {filtered.length === 1 ? "property" : "properties"} available</p>
        </div>
        {filtered.length === 0 ? (
          <div className="text-center py-20 text-muted-foreground">No properties match your filters. Try widening your search.</div>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {filtered.map((p) => <PropertyCard key={p.id} p={p} />)}
          </div>
        )}
      </section>
    </div>
  );
}

type Opt = string | { v: string; l: string };
function Select({ label, value, onChange, options }: { label: string; value: string; onChange: (v: string) => void; options: Opt[] }) {
  return (
    <div>
      <label className="text-[10px] uppercase tracking-widest text-muted-foreground">{label}</label>
      <select value={value} onChange={(e) => onChange(e.target.value)} className="w-full mt-1 bg-background border border-input rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-gold">
        {options.map((o) => {
          const v = typeof o === "string" ? o : o.v;
          const l = typeof o === "string" ? o : o.l;
          return <option key={v} value={v}>{l}</option>;
        })}
      </select>
    </div>
  );
}
