import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { MapPin, Phone, Search, Navigation } from "lucide-react";
import { PageHero } from "@/components/PageHero";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/find-dealer")({
  head: () => ({
    meta: [
      { title: "Find a Dealer — Classic Paints Distributor Locator" },
      { name: "description", content: "Find your nearest Classic Paints dealer across Bangladesh. Search by city, district or area to locate authorised distributors." },
      { property: "og:title", content: "Find a Classic Paints Dealer" },
      { property: "og:description", content: "Locate authorised Classic Paints distributors near you across Bangladesh." },
    ],
  }),
  component: FindDealerPage,
});

type Dealer = {
  id: string;
  name: string;
  area: string;
  city: string;
  division: string;
  phone: string;
  address: string;
  type: "Flagship" | "Authorised" | "Pro Centre";
};

const dealers: Dealer[] = [
  { id: "d1", name: "Classic Paints — Gulshan Flagship", area: "Gulshan", city: "Dhaka", division: "Dhaka", phone: "+880 1700 111 222", address: "Plot 12, Road 7, Gulshan-1, Dhaka 1212", type: "Flagship" },
  { id: "d2", name: "Rangmela Paint House", area: "Dhanmondi", city: "Dhaka", division: "Dhaka", phone: "+880 1700 222 333", address: "House 45, Road 27, Dhanmondi, Dhaka 1209", type: "Authorised" },
  { id: "d3", name: "Uttara Colour Hub", area: "Uttara", city: "Dhaka", division: "Dhaka", phone: "+880 1700 333 444", address: "Sector 7, Uttara, Dhaka 1230", type: "Pro Centre" },
  { id: "d4", name: "Mirpur Paint Centre", area: "Mirpur", city: "Dhaka", division: "Dhaka", phone: "+880 1700 444 555", address: "Section 10, Mirpur, Dhaka 1216", type: "Authorised" },
  { id: "d5", name: "Chittagong Pro Centre", area: "Agrabad", city: "Chattogram", division: "Chattogram", phone: "+880 1700 555 666", address: "Sheikh Mujib Road, Agrabad, Chattogram", type: "Pro Centre" },
  { id: "d6", name: "Port City Paints", area: "GEC", city: "Chattogram", division: "Chattogram", phone: "+880 1700 666 777", address: "GEC Circle, Chattogram 4000", type: "Authorised" },
  { id: "d7", name: "Sylhet Colour Studio", area: "Zindabazar", city: "Sylhet", division: "Sylhet", phone: "+880 1700 777 888", address: "Zindabazar Main Road, Sylhet 3100", type: "Authorised" },
  { id: "d8", name: "Rajshahi Paint Mart", area: "Shaheb Bazar", city: "Rajshahi", division: "Rajshahi", phone: "+880 1700 888 999", address: "Shaheb Bazar, Rajshahi 6100", type: "Authorised" },
  { id: "d9", name: "Khulna Paint House", area: "Sonadanga", city: "Khulna", division: "Khulna", phone: "+880 1700 999 000", address: "Sonadanga, Khulna 9100", type: "Authorised" },
  { id: "d10", name: "Bogura Colour Centre", area: "Sat Mata", city: "Bogura", division: "Rajshahi", phone: "+880 1701 111 222", address: "Sat Mata, Bogura 5800", type: "Authorised" },
  { id: "d11", name: "Cumilla Paint Bazaar", area: "Kandirpar", city: "Cumilla", division: "Chattogram", phone: "+880 1701 222 333", address: "Kandirpar, Cumilla 3500", type: "Authorised" },
  { id: "d12", name: "Mymensingh Colour Studio", area: "Town Hall", city: "Mymensingh", division: "Mymensingh", phone: "+880 1701 333 444", address: "Town Hall Road, Mymensingh 2200", type: "Pro Centre" },
];

const divisions = ["All", "Dhaka", "Chattogram", "Sylhet", "Rajshahi", "Khulna", "Mymensingh"] as const;
const typeOptions = ["All", "Flagship", "Authorised", "Pro Centre"] as const;

function FindDealerPage() {
  const [query, setQuery] = useState("");
  const [division, setDivision] = useState<(typeof divisions)[number]>("All");
  const [type, setType] = useState<(typeof typeOptions)[number]>("All");
  const [active, setActive] = useState<string | null>(dealers[0].id);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return dealers.filter((d) => {
      const matchQ = !q || [d.name, d.area, d.city, d.address].some((v) => v.toLowerCase().includes(q));
      const matchD = division === "All" || d.division === division;
      const matchT = type === "All" || d.type === type;
      return matchQ && matchD && matchT;
    });
  }, [query, division, type]);

  const activeDealer = filtered.find((d) => d.id === active) ?? filtered[0];

  return (
    <>
      <PageHero
        eyebrow="Dealer Locator"
        title={<>Find a <span className="text-brand-red">Classic Paints</span> dealer near you</>}
        description="Search 300+ authorised dealers, flagship stores and Pro Centres across Bangladesh."
      />

      <section className="pb-24">
        <div className="container-regent">
          <div className="grid sm:grid-cols-[1fr_auto_auto] gap-3 mb-6">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search by city, area or store name"
                className="pl-10"
              />
            </div>
            <select
              value={division}
              onChange={(e) => setDivision(e.target.value as typeof division)}
              className="h-10 px-3 bg-card border border-border text-sm"
            >
              {divisions.map((d) => <option key={d} value={d}>{d === "All" ? "All divisions" : d}</option>)}
            </select>
            <select
              value={type}
              onChange={(e) => setType(e.target.value as typeof type)}
              className="h-10 px-3 bg-card border border-border text-sm"
            >
              {typeOptions.map((t) => <option key={t} value={t}>{t === "All" ? "All types" : t}</option>)}
            </select>
          </div>

          <div className="grid lg:grid-cols-[380px_1fr] gap-6">
            {/* List */}
            <div className="border border-border bg-card max-h-[620px] overflow-y-auto">
              {filtered.length === 0 && (
                <div className="p-8 text-center text-sm text-muted-foreground">No dealers match your search.</div>
              )}
              {filtered.map((d) => (
                <button
                  key={d.id}
                  onClick={() => setActive(d.id)}
                  className={`w-full text-left p-5 border-b border-border last:border-b-0 transition-colors ${
                    activeDealer?.id === d.id ? "bg-brand-red/10 border-l-2 border-l-brand-red" : "hover:bg-secondary/40"
                  }`}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="text-sm font-medium">{d.name}</div>
                      <div className="text-xs text-muted-foreground mt-0.5">{d.area}, {d.city}</div>
                    </div>
                    <span className="text-[9px] uppercase tracking-wider-x border border-border px-2 py-0.5">{d.type}</span>
                  </div>
                </button>
              ))}
            </div>

            {/* Map placeholder + details */}
            <div className="space-y-4">
              <div className="relative aspect-[4/3] lg:aspect-auto lg:h-[420px] border border-border overflow-hidden bg-secondary/30">
                {/* Decorative SVG map of Bangladesh */}
                <svg viewBox="0 0 600 600" className="absolute inset-0 w-full h-full opacity-50" xmlns="http://www.w3.org/2000/svg">
                  <defs>
                    <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                      <path d="M40 0H0V40" fill="none" stroke="currentColor" strokeOpacity="0.1" />
                    </pattern>
                  </defs>
                  <rect width="600" height="600" fill="url(#grid)" />
                  <path
                    d="M250 80 Q300 100 320 140 Q360 170 350 220 Q380 260 360 320 Q400 360 380 420 Q360 470 300 500 Q240 520 200 480 Q160 440 180 380 Q150 340 180 290 Q160 240 200 200 Q220 140 250 80 Z"
                    fill="currentColor"
                    fillOpacity="0.08"
                    stroke="currentColor"
                    strokeOpacity="0.3"
                    strokeWidth="1.5"
                  />
                </svg>
                {/* Pins */}
                {filtered.map((d, i) => {
                  const x = 20 + ((i * 13) % 70);
                  const y = 15 + ((i * 17) % 70);
                  const isActive = d.id === activeDealer?.id;
                  return (
                    <button
                      key={d.id}
                      onClick={() => setActive(d.id)}
                      className="absolute -translate-x-1/2 -translate-y-full"
                      style={{ left: `${x}%`, top: `${y}%` }}
                      aria-label={d.name}
                    >
                      <MapPin
                        className={`transition-all ${isActive ? "h-9 w-9 text-brand-red drop-shadow-[0_4px_8px_rgba(220,38,38,0.5)]" : "h-6 w-6 text-foreground/60 hover:text-brand-red"}`}
                        fill={isActive ? "currentColor" : "none"}
                      />
                    </button>
                  );
                })}
                <div className="absolute top-3 left-3 text-[10px] uppercase tracking-wider-x bg-background/80 backdrop-blur-md border border-border px-2 py-1">
                  Map preview — interactive
                </div>
              </div>

              {activeDealer && (
                <div className="border border-border bg-card p-6">
                  <div className="flex items-start justify-between gap-4 mb-4">
                    <div>
                      <div className="text-[10px] uppercase tracking-wider-x text-brand-red mb-1">{activeDealer.type}</div>
                      <h2 className="text-lg md:text-xl uppercase tracking-editorial extralight">{activeDealer.name}</h2>
                    </div>
                  </div>
                  <div className="space-y-2 text-sm text-muted-foreground">
                    <div className="flex gap-3"><MapPin className="h-4 w-4 mt-0.5 shrink-0 text-brand-red" /><span>{activeDealer.address}</span></div>
                    <div className="flex gap-3"><Phone className="h-4 w-4 mt-0.5 shrink-0 text-brand-red" /><a href={`tel:${activeDealer.phone.replace(/\s/g, "")}`} className="hover:text-foreground">{activeDealer.phone}</a></div>
                  </div>
                  <div className="flex flex-wrap gap-2 mt-5">
                    <Button asChild size="sm" className="bg-brand-red text-white hover:bg-brand-red/90">
                      <a href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(activeDealer.name + " " + activeDealer.address)}`} target="_blank" rel="noopener noreferrer">
                        <Navigation className="h-4 w-4 mr-1.5" />Get directions
                      </a>
                    </Button>
                    <Button asChild variant="outline" size="sm">
                      <a href={`tel:${activeDealer.phone.replace(/\s/g, "")}`}><Phone className="h-4 w-4 mr-1.5" />Call dealer</a>
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
