import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useRef, useState } from "react";
import { Download, Share2, Heart, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import { PageHero } from "@/components/PageHero";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/visualizer")({
  head: () => ({
    meta: [
      { title: "Color Visualizer — Preview Classic Paints on Your Walls" },
      { name: "description", content: "Try Classic Paints shades on living room, bedroom, kitchen and exterior walls. Save and share your favorite combinations." },
      { property: "og:title", content: "Classic Paints Color Visualizer" },
      { property: "og:description", content: "Preview premium Classic Paints shades on real room scenes. Save and share your look." },
    ],
  }),
  component: VisualizerPage,
});

type Shade = { name: string; code: string; hex: string };

const palette: Record<string, Shade[]> = {
  Neutrals: [
    { name: "Pearl Mist", code: "CP-N01", hex: "#EDE7DD" },
    { name: "Warm Linen", code: "CP-N02", hex: "#E0D4BE" },
    { name: "Stone Beige", code: "CP-N03", hex: "#C8B79A" },
    { name: "Soft Taupe", code: "CP-N04", hex: "#A8987F" },
    { name: "Charcoal", code: "CP-N05", hex: "#3F3D3A" },
  ],
  Reds: [
    { name: "Classic Red", code: "CP-R01", hex: "#C9302C" },
    { name: "Terracotta", code: "CP-R02", hex: "#B5523B" },
    { name: "Rose Dust", code: "CP-R03", hex: "#D8A39A" },
    { name: "Maroon", code: "CP-R04", hex: "#6E1F1F" },
  ],
  Blues: [
    { name: "Sky Whisper", code: "CP-B01", hex: "#BFD6E4" },
    { name: "Coastal Blue", code: "CP-B02", hex: "#6FA8C7" },
    { name: "Royal Indigo", code: "CP-B03", hex: "#28528C" },
    { name: "Midnight", code: "CP-B04", hex: "#1B2A41" },
  ],
  Greens: [
    { name: "Sage", code: "CP-G01", hex: "#B5C3A8" },
    { name: "Olive", code: "CP-G02", hex: "#7A8B5C" },
    { name: "Forest", code: "CP-G03", hex: "#2F5D43" },
    { name: "Mint Cool", code: "CP-G04", hex: "#C7E0D4" },
  ],
  Warms: [
    { name: "Sun Mango", code: "CP-Y01", hex: "#F2B441" },
    { name: "Saffron", code: "CP-Y02", hex: "#E08A2B" },
    { name: "Peach Glow", code: "CP-Y03", hex: "#F4C6A2" },
    { name: "Mocha", code: "CP-Y04", hex: "#7A4E2D" },
  ],
};

const rooms = [
  { id: "living", label: "Living Room" },
  { id: "bedroom", label: "Bedroom" },
  { id: "kitchen", label: "Kitchen" },
  { id: "exterior", label: "Exterior" },
] as const;

type RoomId = (typeof rooms)[number]["id"];

function VisualizerPage() {
  const [room, setRoom] = useState<RoomId>("living");
  const [shade, setShade] = useState<Shade>(palette.Neutrals[1]);
  const [accent, setAccent] = useState<Shade>(palette.Blues[2]);
  const [saved, setSaved] = useState<Array<{ room: RoomId; wall: Shade; trim: Shade }>>([]);
  const svgRef = useRef<SVGSVGElement>(null);

  const allShades = useMemo(() => Object.entries(palette), []);

  const handleSave = () => {
    setSaved((s) => [{ room, wall: shade, trim: accent }, ...s].slice(0, 6));
    toast.success(`Saved: ${shade.name} + ${accent.name}`);
  };

  const handleShare = async () => {
    const text = `My Classic Paints look — ${shade.name} (${shade.code}) walls with ${accent.name} (${accent.code}) trim in the ${rooms.find((r) => r.id === room)?.label}.`;
    try {
      if (navigator.share) await navigator.share({ title: "Classic Paints", text });
      else { await navigator.clipboard.writeText(text); toast.success("Copied to clipboard"); }
    } catch { /* user cancelled */ }
  };

  const handleDownload = () => {
    const svg = svgRef.current;
    if (!svg) return;
    const xml = new XMLSerializer().serializeToString(svg);
    const blob = new Blob([xml], { type: "image/svg+xml" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `classic-paints-${room}-${shade.code}.svg`;
    a.click();
    URL.revokeObjectURL(url);
    toast.success("Downloaded preview");
  };

  return (
    <>
      <PageHero
        eyebrow="Color Visualizer"
        title={<>See your space in <span className="text-brand-red">Classic</span> color</>}
        description="Pick a room scene, try our curated shades on the walls and trim, then save or share your favorite combinations."
      />

      <section className="pb-24">
        <div className="container-regent grid lg:grid-cols-[1fr_360px] gap-8">
          {/* Preview */}
          <div className="space-y-4">
            <div className="flex flex-wrap gap-2">
              {rooms.map((r) => (
                <button
                  key={r.id}
                  onClick={() => setRoom(r.id)}
                  className={`px-4 py-2 text-[11px] uppercase tracking-wider-x border transition-colors ${
                    room === r.id ? "border-brand-red text-brand-red" : "border-border text-foreground/70 hover:border-foreground/40"
                  }`}
                >
                  {r.label}
                </button>
              ))}
            </div>

            <div className="relative border border-border bg-card overflow-hidden">
              <RoomScene ref={svgRef} room={room} wall={shade.hex} trim={accent.hex} />
              <div className="absolute bottom-0 inset-x-0 p-4 flex flex-wrap items-center justify-between gap-3 bg-background/60 backdrop-blur-md border-t border-border">
                <div className="flex items-center gap-4 text-xs">
                  <div className="flex items-center gap-2"><span className="h-5 w-5 border border-border" style={{ background: shade.hex }} /><span>{shade.name} <span className="text-muted-foreground">({shade.code})</span></span></div>
                  <div className="flex items-center gap-2"><span className="h-5 w-5 border border-border" style={{ background: accent.hex }} /><span>{accent.name} <span className="text-muted-foreground">({accent.code})</span></span></div>
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={handleSave}><Heart className="h-4 w-4 mr-1.5" />Save</Button>
                  <Button size="sm" variant="outline" onClick={handleShare}><Share2 className="h-4 w-4 mr-1.5" />Share</Button>
                  <Button size="sm" className="bg-brand-red text-white hover:bg-brand-red/90" onClick={handleDownload}><Download className="h-4 w-4 mr-1.5" />Download</Button>
                </div>
              </div>
            </div>

            {saved.length > 0 && (
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h2 className="text-xs uppercase tracking-wider-x text-muted-foreground">Saved looks</h2>
                  <button onClick={() => setSaved([])} className="text-xs text-muted-foreground hover:text-brand-red inline-flex items-center gap-1"><RotateCcw className="h-3 w-3" />Clear</button>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {saved.map((s, i) => (
                    <button
                      key={i}
                      onClick={() => { setRoom(s.room); setShade(s.wall); setAccent(s.trim); }}
                      className="group border border-border bg-card hover:border-brand-red transition-colors text-left"
                    >
                      <div className="flex h-16">
                        <div className="flex-1" style={{ background: s.wall.hex }} />
                        <div className="w-1/3" style={{ background: s.trim.hex }} />
                      </div>
                      <div className="p-2 text-[10px] uppercase tracking-wider-x">
                        <div>{rooms.find((r) => r.id === s.room)?.label}</div>
                        <div className="text-muted-foreground">{s.wall.code} / {s.trim.code}</div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Palette */}
          <aside className="space-y-6">
            <Picker label="Wall colour" allShades={allShades} active={shade} onSelect={setShade} />
            <Picker label="Trim / Accent" allShades={allShades} active={accent} onSelect={setAccent} />
          </aside>
        </div>
      </section>
    </>
  );
}

function Picker({
  label, allShades, active, onSelect,
}: { label: string; allShades: [string, Shade[]][]; active: Shade; onSelect: (s: Shade) => void }) {
  return (
    <div className="border border-border bg-card p-5">
      <h3 className="text-[11px] uppercase tracking-wider-x text-muted-foreground mb-4">{label}</h3>
      <div className="space-y-4">
        {allShades.map(([group, shades]) => (
          <div key={group}>
            <div className="text-[10px] uppercase tracking-wider-x text-foreground/60 mb-2">{group}</div>
            <div className="grid grid-cols-5 gap-2">
              {shades.map((s) => (
                <button
                  key={s.code}
                  onClick={() => onSelect(s)}
                  title={`${s.name} — ${s.code}`}
                  className={`aspect-square border transition-transform hover:scale-105 ${active.code === s.code ? "ring-2 ring-brand-red border-brand-red" : "border-border"}`}
                  style={{ background: s.hex }}
                  aria-label={s.name}
                />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ------- Room scenes (inline SVG) ------- */
function RoomScene({ room, wall, trim, ref }: { room: RoomId; wall: string; trim: string; ref?: React.Ref<SVGSVGElement> }) {
  const common = "w-full h-[420px] md:h-[520px]";
  if (room === "living") return (
      <svg ref={ref} viewBox="0 0 800 520" className={common} xmlns="http://www.w3.org/2000/svg">
        <rect width="800" height="520" fill={wall} />
        <rect x="0" y="380" width="800" height="140" fill="#2a2520" />
        <rect x="0" y="376" width="800" height="6" fill={trim} />
        {/* window */}
        <rect x="80" y="90" width="200" height="200" fill="#cfe2f0" stroke={trim} strokeWidth="8" />
        <line x1="180" y1="90" x2="180" y2="290" stroke={trim} strokeWidth="6" />
        <line x1="80" y1="190" x2="280" y2="190" stroke={trim} strokeWidth="6" />
        {/* sofa */}
        <rect x="380" y="300" width="340" height="90" rx="8" fill="#3a2f28" />
        <rect x="380" y="280" width="340" height="40" rx="8" fill="#4b3d33" />
        {/* cushion */}
        <rect x="410" y="270" width="70" height="60" rx="6" fill={trim} opacity="0.85" />
        <rect x="500" y="270" width="70" height="60" rx="6" fill="#d8c9b3" />
        {/* lamp */}
        <rect x="320" y="240" width="6" height="140" fill="#1a1a1a" />
        <polygon points="290,180 360,180 350,240 300,240" fill={trim} opacity="0.9" />
        {/* frame */}
        <rect x="500" y="120" width="160" height="110" fill="#1c1c1c" stroke={trim} strokeWidth="5" />
      </svg>
    );
  if (room === "bedroom") return (
    <svg ref={ref} viewBox="0 0 800 520" className={common} xmlns="http://www.w3.org/2000/svg">
      <rect width="800" height="520" fill={wall} />
      <rect x="0" y="400" width="800" height="120" fill="#241c17" />
      <rect x="0" y="396" width="800" height="6" fill={trim} />
      <rect x="220" y="160" width="360" height="160" rx="8" fill={trim} opacity="0.85" />
      <rect x="180" y="320" width="440" height="90" rx="6" fill="#efe6d7" />
      <rect x="180" y="320" width="440" height="20" fill="#d8c9b3" />
      <rect x="220" y="290" width="160" height="50" rx="8" fill="#ffffff" />
      <rect x="420" y="290" width="160" height="50" rx="8" fill="#ffffff" />
      <circle cx="120" cy="320" r="22" fill={trim} />
      <circle cx="680" cy="320" r="22" fill={trim} />
    </svg>
  );
  if (room === "kitchen") return (
    <svg ref={ref} viewBox="0 0 800 520" className={common} xmlns="http://www.w3.org/2000/svg">
      <rect width="800" height="520" fill={wall} />
      <rect x="0" y="410" width="800" height="110" fill="#1f1a16" />
      <rect x="80" y="120" width="640" height="120" fill={trim} opacity="0.9" />
      <line x1="240" y1="120" x2="240" y2="240" stroke="#1a1a1a" strokeWidth="3" />
      <line x1="400" y1="120" x2="400" y2="240" stroke="#1a1a1a" strokeWidth="3" />
      <line x1="560" y1="120" x2="560" y2="240" stroke="#1a1a1a" strokeWidth="3" />
      <rect x="60" y="320" width="680" height="20" fill="#dcd2c1" />
      <rect x="60" y="340" width="680" height="80" fill="#2b231d" />
      <rect x="340" y="340" width="120" height="80" fill="#111" />
      <circle cx="370" cy="380" r="10" fill="#444" />
      <circle cx="430" cy="380" r="10" fill="#444" />
    </svg>
  );
  return (
    <svg ref={ref} viewBox="0 0 800 520" className={common} xmlns="http://www.w3.org/2000/svg">
      <rect width="800" height="200" fill="#cfe2f0" />
      <rect y="450" width="800" height="70" fill="#3b3a36" />
      <polygon points="120,200 400,80 680,200" fill={trim} />
      <rect x="120" y="200" width="560" height="260" fill={wall} />
      <rect x="360" y="320" width="80" height="140" fill="#2b1d12" />
      <rect x="360" y="320" width="80" height="140" fill="none" stroke={trim} strokeWidth="6" />
      <rect x="180" y="240" width="120" height="100" fill="#cfe2f0" stroke={trim} strokeWidth="6" />
      <rect x="500" y="240" width="120" height="100" fill="#cfe2f0" stroke={trim} strokeWidth="6" />
      <line x1="240" y1="240" x2="240" y2="340" stroke={trim} strokeWidth="4" />
      <line x1="560" y1="240" x2="560" y2="340" stroke={trim} strokeWidth="4" />
    </svg>
  );
}

