import { createFileRoute } from "@tanstack/react-router";
import {
  LayoutDashboard,
  Briefcase,
  Megaphone,
  Users,
  MessageSquare,
  Inbox,
  Search,
  MapPin,
  BarChart3,
  UserPlus,
  Home,
  Bell,
  Sparkles,
  Bed,
  Bath,
  Ruler,
  Heart,
  EyeOff,
  Plus,
  Share2,
  ChevronRight,
  SlidersHorizontal,
  MapPinned,
  Building2,
  Landmark,
  DollarSign,
  Trees,
} from "lucide-react";
import property1 from "@/assets/property-1.jpg";
import property2 from "@/assets/property-2.jpg";
import property3 from "@/assets/property-3.jpg";
import property4 from "@/assets/property-4.jpg";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Properties · Reibox Investor Portal" },
      {
        name: "description",
        content:
          "Browse underwritten on-market and off-market real estate deals with instant cash-flow analysis on the Reibox investor platform.",
      },
      { property: "og:title", content: "Properties · Reibox Investor Portal" },
      {
        property: "og:description",
        content:
          "Underwritten deals with instant cash-flow analysis for serious real estate investors.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: PropertiesPage,
});

type Property = {
  id: string;
  image: string;
  status: "For Sale" | "New" | "Off Market";
  tag?: { label: string; tone: "success" | "premium" | "warning" };
  address: string;
  city: string;
  price: number;
  beds: number;
  baths: number;
  sqft: number;
  fmr: number;
  payment: number;
  cashFlow: number;
};

const properties: Property[] = [
  {
    id: "1",
    image: property1,
    status: "For Sale",
    tag: { label: "High Yield", tone: "success" },
    address: "1982 S Benton Center Rd",
    city: "Benton Harbor, MI 49022",
    price: 325000,
    beds: 2,
    baths: 2,
    sqft: 1200,
    fmr: 1090,
    payment: 1943.38,
    cashFlow: 853.38,
  },
  {
    id: "2",
    image: property2,
    status: "For Sale",
    tag: { label: "Premium", tone: "premium" },
    address: "956 Mississippi River Blvd S",
    city: "Saint Paul, MN 55116",
    price: 2850000,
    beds: 4,
    baths: 5,
    sqft: 4079,
    fmr: 1710,
    payment: 16744.15,
    cashFlow: -15034.15,
  },
  {
    id: "3",
    image: property3,
    status: "For Sale",
    tag: { label: "Investment", tone: "warning" },
    address: "3004 Astoria Pines Cir",
    city: "Las Vegas, NV 89107",
    price: 1750000,
    beds: 3,
    baths: 4,
    sqft: 4865,
    fmr: 1420,
    payment: 9753.95,
    cashFlow: 8333.95,
  },
  {
    id: "4",
    image: property4,
    status: "New",
    tag: { label: "New Listing", tone: "success" },
    address: "25330 Park Ln",
    city: "Excelsior, MN 55331",
    price: 1176500,
    beds: 3,
    baths: 3,
    sqft: 2350,
    fmr: 1420,
    payment: 6934.02,
    cashFlow: -5514.02,
  },
];

const navSections = [
  {
    label: "Admin Panel",
    items: [
      { icon: LayoutDashboard, label: "My Dashboard" },
      { icon: Briefcase, label: "A&O Portal" },
      { icon: Megaphone, label: "Promotions" },
      { icon: Users, label: "Investors Hub" },
      { icon: MessageSquare, label: "Messaging" },
      { icon: Inbox, label: "Support Inbox", badge: "99+" },
    ],
  },
  {
    label: "Community Panel",
    items: [
      { icon: Search, label: "Deal Finder", active: true },
      { icon: MapPinned, label: "Property Lookup" },
      { icon: BarChart3, label: "Demographics" },
      { icon: UserPlus, label: "My Leads" },
      { icon: Home, label: "D4D" },
    ],
  },
];

const dealFinderSubItems = [
  { label: "Show All", active: true, count: 128 },
  { label: "Hidden Properties", count: 12 },
  { label: "Featured Properties", count: 8 },
];

const propertyFilters = [
  { icon: Home, label: "Single-Family", active: true },
  { icon: Building2, label: "Multifamily" },
  { icon: Home, label: "Mobile Homes" },
  { icon: Trees, label: "Land For Sale" },
  { icon: Landmark, label: "Owner Finance" },
  { icon: DollarSign, label: "Under $150k" },
];

function formatCurrency(n: number) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: n % 1 === 0 ? 0 : 2,
  }).format(n);
}

function PropertiesPage() {
  return (
    <div className="flex min-h-screen bg-background text-foreground">
      {/* Sidebar */}
      <aside className="hidden lg:flex w-64 shrink-0 flex-col border-r border-border bg-surface sticky top-0 h-screen">
        <div className="flex items-center gap-2.5 px-6 h-16 border-b border-border">
          <div className="grid place-items-center size-8 rounded-lg bg-primary text-primary-foreground">
            <Home className="size-4" />
          </div>
          <div className="leading-tight">
            <div className="font-serif text-lg font-bold tracking-tight">Reibox</div>
            <div className="text-[10px] uppercase tracking-widest text-muted-foreground">
              Simplify Investing
            </div>
          </div>
        </div>

        <nav className="flex-1 overflow-y-auto px-3 py-5 space-y-6">
          {navSections.map((section) => (
            <div key={section.label}>
              <div className="px-3 mb-2 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
                {section.label}
              </div>
              <ul className="space-y-0.5">
                {section.items.map((item) => {
                  const Icon = item.icon;
                  const active = "active" in item && item.active;
                  return (
                    <li key={item.label}>
                      <a
                        href="#"
                        className={`group flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                          active
                            ? "bg-accent text-foreground font-medium"
                            : "text-muted-foreground hover:bg-accent/60 hover:text-foreground"
                        }`}
                      >
                        <Icon className="size-4 shrink-0" strokeWidth={1.75} />
                        <span className="truncate">{item.label}</span>
                        {"badge" in item && item.badge && (
                          <span className="ml-auto text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-danger/10 text-danger">
                            {item.badge}
                          </span>
                        )}
                        {active && (
                          <ChevronRight className="ml-auto size-3.5" strokeWidth={2} />
                        )}
                      </a>
                      {active && (
                        <ul className="mt-1 ml-9 space-y-0.5 border-l border-border pl-3">
                          {dealFinderSubItems.map((sub) => (
                            <li key={sub.label}>
                              <a
                                href="#"
                                className={`flex items-center justify-between py-1.5 text-xs rounded-md pr-2 ${
                                  sub.active
                                    ? "text-brand font-medium"
                                    : "text-muted-foreground hover:text-foreground"
                                }`}
                              >
                                <span>{sub.label}</span>
                                <span className="text-[10px] tabular-nums text-muted-foreground">
                                  {sub.count}
                                </span>
                              </a>
                            </li>
                          ))}
                        </ul>
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </nav>

        <div className="p-4 border-t border-border">
          <div className="flex items-center gap-3">
            <div className="size-9 rounded-full bg-gradient-to-br from-brand to-primary ring-2 ring-surface" />
            <div className="min-w-0 flex-1">
              <div className="text-sm font-semibold truncate">Alex Sterling</div>
              <div className="text-[11px] text-muted-foreground">Principal Investor</div>
            </div>
          </div>
        </div>
      </aside>

      {/* Main */}
      <main className="flex-1 min-w-0">
        {/* Header */}
        <header className="sticky top-0 z-20 h-16 border-b border-border bg-background/85 backdrop-blur">
          <div className="h-full flex items-center justify-between px-6 lg:px-8 gap-4">
            <div className="relative flex-1 max-w-xl">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
              <input
                type="text"
                placeholder="Search properties, zip codes, addresses…"
                className="w-full h-10 pl-10 pr-4 rounded-lg bg-muted/70 border border-transparent focus:bg-surface focus:border-border focus:ring-2 focus:ring-brand/20 outline-none text-sm placeholder:text-muted-foreground transition-all"
              />
              <kbd className="hidden md:inline-flex absolute right-3 top-1/2 -translate-y-1/2 items-center gap-0.5 text-[10px] font-medium px-1.5 py-0.5 rounded border border-border text-muted-foreground bg-surface">
                ⌘K
              </kbd>
            </div>

            <div className="flex items-center gap-2 sm:gap-3">
              <button className="relative grid place-items-center size-9 rounded-lg hover:bg-accent text-muted-foreground hover:text-foreground transition-colors">
                <Bell className="size-4" />
                <span className="absolute top-1.5 right-1.5 size-1.5 rounded-full bg-danger" />
              </button>
              <div className="hidden sm:block h-6 w-px bg-border" />
              <div className="flex items-center gap-2.5">
                <div className="hidden sm:block text-right leading-tight">
                  <div className="text-xs font-semibold">Alex Sterling</div>
                  <div className="text-[10px] text-muted-foreground uppercase tracking-wider">
                    Pro Plan
                  </div>
                </div>
                <div className="size-9 rounded-full bg-gradient-to-br from-brand to-primary ring-2 ring-surface" />
              </div>
            </div>
          </div>
        </header>

        <div className="px-6 lg:px-8 py-8 max-w-[1600px] mx-auto space-y-8">
          {/* Page header */}
          <div className="grid grid-cols-[minmax(0,1fr)_auto] items-end gap-6 sm:flex sm:flex-wrap sm:justify-between">
            <div className="min-w-0">
              <h1 className="font-serif text-3xl sm:text-4xl font-bold tracking-tight text-balance">
                Available Opportunities
              </h1>
              <p className="mt-2 text-sm text-muted-foreground">
                Showing <span className="font-semibold text-foreground">128</span> underwritten
                deals matched to your investment criteria.
              </p>
            </div>

            {/* Tabs */}
            <div className="inline-flex p-1 rounded-lg bg-muted border border-border">
              <button className="px-4 py-1.5 text-xs font-semibold rounded-md bg-surface shadow-sm text-foreground">
                On Market Properties
              </button>
              <button className="px-4 py-1.5 text-xs font-semibold rounded-md text-muted-foreground hover:text-foreground">
                Assignment Deals
              </button>
            </div>
          </div>

          {/* Boxly banner */}
          <div className="relative overflow-hidden rounded-2xl border border-border bg-gradient-to-br from-surface via-surface to-accent/40 p-5 sm:p-6">
            <div className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-5">
              <div className="grid place-items-center size-12 rounded-xl bg-primary text-primary-foreground shrink-0">
                <Sparkles className="size-5" />
              </div>
              <div className="min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="text-sm font-semibold">Hi, I'm Boxly — your AI investing assistant</h3>
                  <span className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-success-soft text-success">
                    <span className="size-1.5 rounded-full bg-success" />
                    Live
                  </span>
                </div>
                <p className="text-sm text-muted-foreground text-pretty leading-relaxed">
                  Analyzing 3,500+ real estate data points across flip, wholesale, and buy-and-hold
                  strategies. Ask about cap rates, formulas, or deal analysis.
                </p>
              </div>
              <button className="hidden sm:inline-flex shrink-0 items-center gap-2 h-9 px-4 rounded-lg bg-primary text-primary-foreground text-xs font-semibold hover:bg-primary/90 transition-colors">
                Ask Boxly
                <ChevronRight className="size-3.5" />
              </button>
            </div>
          </div>

          {/* Filter row */}
          <div className="flex flex-wrap items-center gap-2">
            {propertyFilters.map((f) => {
              const Icon = f.icon;
              return (
                <button
                  key={f.label}
                  className={`inline-flex items-center gap-1.5 h-9 px-3.5 rounded-full border text-xs font-medium transition-all ${
                    f.active
                      ? "bg-primary text-primary-foreground border-primary"
                      : "bg-surface border-border text-foreground hover:border-foreground/30"
                  }`}
                >
                  <Icon className="size-3.5" strokeWidth={2} />
                  {f.label}
                </button>
              );
            })}
            <div className="hidden sm:block h-6 w-px bg-border mx-1" />
            <button className="inline-flex items-center gap-1.5 h-9 px-3.5 rounded-full border border-border bg-surface text-xs font-medium hover:border-foreground/30 transition-all">
              <SlidersHorizontal className="size-3.5" />
              Filter
            </button>
            <div className="ml-auto flex items-center gap-2">
              <button className="inline-flex items-center gap-2 h-9 px-4 rounded-lg border border-border bg-surface text-xs font-semibold hover:bg-accent transition-colors">
                <UserPlus className="size-3.5" />
                Skip Trace + Add Buyer
              </button>
              <button className="inline-flex items-center gap-2 h-9 px-4 rounded-lg bg-warning text-warning-foreground text-xs font-semibold hover:opacity-90 transition-opacity">
                <Users className="size-3.5" />
                Investors Hub
              </button>
            </div>
          </div>

          {/* Property grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-6">
            {properties.map((p) => (
              <PropertyCard key={p.id} property={p} />
            ))}
          </div>
        </div>
      </main>
    </div>
  );
}

function PropertyCard({ property: p }: { property: Property }) {
  const positive = p.cashFlow >= 0;

  return (
    <article className="group flex flex-col rounded-2xl bg-card border border-border overflow-hidden shadow-[var(--shadow-card)] hover:shadow-[var(--shadow-card-hover)] hover:-translate-y-0.5 transition-all duration-300">
      <div className="relative aspect-[4/3] overflow-hidden bg-muted">
        <img
          src={p.image}
          alt={p.address}
          loading="lazy"
          width={800}
          height={600}
          className="size-full object-cover group-hover:scale-[1.03] transition-transform duration-500"
        />
        <div className="absolute inset-x-0 top-0 flex items-start justify-between p-3">
          <div className="flex flex-wrap gap-1.5">
            <span className="inline-flex items-center px-2 py-1 rounded-md bg-surface/95 backdrop-blur-sm text-[10px] font-bold uppercase tracking-wider text-foreground shadow-sm">
              {p.status}
            </span>
            {p.tag && (
              <span
                className={`inline-flex items-center px-2 py-1 rounded-md text-[10px] font-bold uppercase tracking-wider shadow-sm ${
                  p.tag.tone === "success"
                    ? "bg-success text-success-foreground"
                    : p.tag.tone === "warning"
                      ? "bg-warning text-warning-foreground"
                      : "bg-primary text-primary-foreground"
                }`}
              >
                {p.tag.label}
              </span>
            )}
          </div>
          <div className="flex gap-1.5">
            <button
              aria-label="Hide"
              className="grid place-items-center size-8 rounded-full bg-surface/95 backdrop-blur-sm text-muted-foreground hover:text-foreground shadow-sm transition-colors"
            >
              <EyeOff className="size-3.5" />
            </button>
            <button
              aria-label="Favorite"
              className="grid place-items-center size-8 rounded-full bg-surface/95 backdrop-blur-sm text-muted-foreground hover:text-danger shadow-sm transition-colors"
            >
              <Heart className="size-3.5" />
            </button>
          </div>
        </div>
        <button className="absolute bottom-3 right-3 inline-flex items-center gap-1 h-8 px-2.5 rounded-full bg-surface/95 backdrop-blur-sm text-[11px] font-semibold shadow-sm hover:bg-surface transition-colors">
          <Plus className="size-3" /> Add Lead
        </button>
      </div>

      <div className="flex-1 flex flex-col p-5">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <h3 className="font-serif text-base font-bold leading-tight truncate">
              {p.address}
            </h3>
            <p className="mt-0.5 text-xs text-muted-foreground flex items-center gap-1">
              <MapPin className="size-3 shrink-0" />
              <span className="truncate">{p.city}</span>
            </p>
          </div>
          <div className="text-right shrink-0">
            <div className="text-lg font-bold tabular-nums tracking-tight">
              {formatCurrency(p.price)}
            </div>
            <div className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">
              List Price
            </div>
          </div>
        </div>

        <div className="mt-4 grid grid-cols-3 rounded-lg bg-muted/60 border border-border overflow-hidden">
          <Spec icon={Bed} label="Beds" value={p.beds} />
          <Spec icon={Bath} label="Baths" value={p.baths} border />
          <Spec icon={Ruler} label="Sq Ft" value={p.sqft.toLocaleString()} />
        </div>

        <dl className="mt-4 space-y-1.5 text-xs">
          <div className="flex items-center justify-between">
            <dt className="text-muted-foreground">FMR</dt>
            <dd className="font-semibold tabular-nums">{formatCurrency(p.fmr)}</dd>
          </div>
          <div className="flex items-center justify-between">
            <dt className="text-muted-foreground">Est. Payment</dt>
            <dd className="font-semibold tabular-nums">{formatCurrency(p.payment)}</dd>
          </div>
        </dl>

        <div
          className={`mt-4 flex items-center justify-between px-3 py-2.5 rounded-lg border ${
            positive
              ? "bg-success-soft border-success/20"
              : "bg-danger-soft border-danger/20"
          }`}
        >
          <div className="flex items-center gap-2">
            <span
              className={`size-2 rounded-full ${positive ? "bg-success" : "bg-danger"}`}
            />
            <span
              className={`text-[10px] font-bold uppercase tracking-wider ${
                positive ? "text-success" : "text-danger"
              }`}
            >
              Est Cash Flow
            </span>
          </div>
          <div
            className={`text-sm font-bold tabular-nums ${
              positive ? "text-success" : "text-danger"
            }`}
          >
            {positive ? "+" : ""}
            {formatCurrency(p.cashFlow)}
            <span className="text-[10px] font-medium opacity-70"> /mo</span>
          </div>
        </div>

        <div className="mt-4 flex gap-2">
          <button className="flex-1 h-10 rounded-lg bg-primary text-primary-foreground text-xs font-semibold hover:bg-primary/90 transition-colors">
            View Details
          </button>
          <button
            aria-label="Share"
            className="grid place-items-center size-10 rounded-lg border border-border bg-surface text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
          >
            <Share2 className="size-4" />
          </button>
        </div>
      </div>
    </article>
  );
}

function Spec({
  icon: Icon,
  label,
  value,
  border,
}: {
  icon: typeof Bed;
  label: string;
  value: string | number;
  border?: boolean;
}) {
  return (
    <div
      className={`flex flex-col items-center justify-center py-2.5 gap-0.5 ${
        border ? "border-x border-border" : ""
      }`}
    >
      <div className="flex items-center gap-1 text-muted-foreground">
        <Icon className="size-3" />
        <span className="text-[10px] font-semibold uppercase tracking-wider">{label}</span>
      </div>
      <div className="text-sm font-bold tabular-nums">{value}</div>
    </div>
  );
}
