import { useEffect, useRef, useState, useCallback } from "react";
import { Link } from "react-router-dom";
import { ArrowRight, ArrowLeft, MessageSquare, CheckCircle, Clock, Code, Zap, ExternalLink, Monitor, CornerDownRight, ImageIcon, PanelBottomClose, Maximize2 } from "lucide-react";
import dashboardOverview from "@/assets/dashboard-overview.png";
import dashboardProducts from "@/assets/dashboard-products.png";
import dashboardQuotes from "@/assets/dashboard-quotes.png";
import dashboardOrders from "@/assets/dashboard-orders.png";
import dashboardCustomers from "@/assets/dashboard-customers.png";
import dashboardAnalytics from "@/assets/dashboard-analytics.png";
import dashboardChatbotSettings from "@/assets/dashboard-chatbot-settings.png";
import dashboardTeam from "@/assets/dashboard-team.png";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "@/components/ui/tooltip";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { toast } from "sonner";

// ─── Admin Dashboard Images ──────────────────────────────────────────────────
const adminImages = [
  { src: dashboardOverview, alt: "Overview" },
  { src: dashboardProducts, alt: "Products" },
  { src: dashboardQuotes, alt: "Quotes" },
  { src: dashboardOrders, alt: "Orders" },
  { src: dashboardCustomers, alt: "Customers" },
  { src: dashboardAnalytics, alt: "Analytics" },
  { src: dashboardChatbotSettings, alt: "ChatBot Settings" },
  { src: dashboardTeam, alt: "Team" },
];

// ─── Live Widget Embed ────────────────────────────────────────────────────────
const collapseChatskuBubble = () => {
  // Try clicking the bubble's close/collapse button without removing anything
  const closeBtn = document.querySelector<HTMLElement>(
    '[class*="chatsku"] [class*="close"], [id*="chatsku"] [class*="close"], [class*="ciq"] [class*="close"], [aria-label*="close" i][class*="chat" i]'
  );
  if (closeBtn) {
    closeBtn.click();
    return;
  }

  // If no close button found, try to collapse by hiding the open chat panel but keep the launcher
  document.querySelectorAll<HTMLElement>(
    '[id*="chatsku-widget-bubble"], [class*="chatsku-open"], [class*="ciq-open"], [class*="chatsku-panel"], [class*="ciq-panel"]'
  ).forEach((el) => {
    el.style.display = 'none';
  });

  // Also try clicking the bubble launcher itself to toggle it closed
  const launcher = document.querySelector<HTMLElement>(
    '[id*="chatsku-launcher"], [class*="chatsku-launcher"], [id*="ciq-launcher"], [class*="ciq-launcher"], [id^="chatsku-bubble"], [class*="chatsku-bubble"]'
  );
  if (launcher) {
    launcher.click();
  }
};

const LiveWidget = ({ embedMode }: { embedMode: "inline" | "bubble" }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!containerRef.current) return;
    setLoading(true);

    // Clean up previous widget instances (prevents inline + bubble rendering together)
    document
      .querySelectorAll('script[src="https://app.chatsku.com/widget/widget.js"]')
      .forEach((existingScript) => existingScript.remove());

    const container = document.getElementById("chatsku-widget");
    if (container) container.innerHTML = "";

    collapseChatskuBubble();

    const script = document.createElement("script");
    script.src = "https://app.chatsku.com/widget/widget.js";
    script.setAttribute("data-api-key", "a9135858e5829054ecdb6a567234cf187875344f42ef54ba104400c4436f7dca");
    script.setAttribute("data-embed", embedMode);
    if (embedMode === "inline") {
      script.setAttribute("data-container", "chatsku-widget");
    }
    script.async = true;
    script.onload = () => {
      setTimeout(() => setLoading(false), 1500);
    };
    containerRef.current.appendChild(script);

    return () => {
      script.remove();
      collapseChatskuBubble();
    };
  }, [embedMode]);

  if (embedMode === "bubble") {
    return (
      <>
        <div ref={containerRef} className="hidden">
          {/* Hidden sink to ensure inline markup never becomes visible in bubble mode */}
          <div id="chatsku-widget" className="hidden" aria-hidden="true" />
        </div>
        <div className="rounded-2xl border border-border bg-card overflow-hidden shadow-2xl shadow-background glow-teal relative max-w-[520px] mx-auto">
          <div className="flex flex-col items-center justify-center gap-3 py-16 px-6 text-center">
            <PanelBottomClose className="w-10 h-10 text-primary" />
            <p className="text-foreground font-semibold text-base">Bubble mode active</p>
            <p className="text-muted-foreground text-sm max-w-xs">
              Look for the chat bubble in the bottom-right corner of this page. Click it to open the widget.
            </p>
            {loading && (
              <div className="flex items-center gap-2 mt-2">
                <div className="w-5 h-5 border-2 border-primary/30 border-t-primary rounded-full animate-spin" />
                <span className="text-xs text-muted-foreground animate-pulse">Loading bubble…</span>
              </div>
            )}
          </div>
        </div>
      </>
    );
  }

  return (
    <div ref={containerRef} className="rounded-2xl border border-border bg-card overflow-hidden shadow-2xl shadow-background glow-teal relative max-w-[520px] mx-auto">
      <div id="chatsku-widget" style={{ width: "100%", height: "calc(100vh - 260px)", minHeight: "400px", maxHeight: "600px" }} />
      {loading && (
        <div className="absolute inset-0 flex flex-col items-center justify-center bg-card z-10 gap-4">
          <div className="w-10 h-10 border-3 border-primary/30 border-t-primary rounded-full animate-spin" />
          <p className="text-sm text-muted-foreground animate-pulse">Loading chat widget…</p>
        </div>
      )}
    </div>
  );
};

// ─── Image Viewer ─────────────────────────────────────────────────────────────
const ImageViewer = ({ images }: { images: { src: string; alt: string }[] }) => {
  const [current, setCurrent] = useState(0);
  const total = images.length;

  const prev = useCallback(() => setCurrent((c) => (c - 1 + total) % total), [total]);
  const next = useCallback(() => setCurrent((c) => (c + 1) % total), [total]);

  return (
    <div className="flex flex-col gap-3">
      {/* Title */}
      <p className="text-center text-sm font-semibold text-foreground">{images[current].alt}</p>
      <div className="relative rounded-2xl border border-border overflow-hidden shadow-2xl shadow-background bg-card">
        <img
          src={images[current].src}
          alt={images[current].alt}
          className="w-full h-auto object-cover"
        />
        {total > 1 && (
          <>
            <button
              onClick={prev}
              className="absolute left-3 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-background/80 border border-border flex items-center justify-center hover:bg-background transition-colors"
              aria-label="Previous image"
            >
              <ArrowLeft className="w-4 h-4 text-foreground" />
            </button>
            <button
              onClick={next}
              className="absolute right-3 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-background/80 border border-border flex items-center justify-center hover:bg-background transition-colors"
              aria-label="Next image"
            >
              <ArrowRight className="w-4 h-4 text-foreground" />
            </button>
          </>
        )}
      </div>
      {total > 1 && (
        <div className="flex flex-wrap justify-center gap-2">
          {images.map((img, i) => (
            <button
              key={i}
              onClick={() => setCurrent(i)}
              className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
                i === current
                  ? "bg-primary text-primary-foreground border-primary"
                  : "bg-secondary/50 text-muted-foreground border-border hover:border-primary/50"
              }`}
            >
              {img.alt}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ─── Try-it button ────────────────────────────────────────────────────────────
const TryItButton = ({ term, onClick }: { term: string; onClick: (term: string) => void }) => (
  <TooltipProvider delayDuration={300}>
    <Tooltip>
      <TooltipTrigger asChild>
        <button
          onClick={() => onClick(term)}
          className="inline-flex items-center justify-center w-5 h-5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors ml-1.5 align-middle"
          aria-label={`Try "${term}" in widget`}
        >
          <CornerDownRight className="w-3 h-3" />
        </button>
      </TooltipTrigger>
      <TooltipContent side="top" className="text-xs">Try this in the widget</TooltipContent>
    </Tooltip>
  </TooltipProvider>
);

// ─── Page ─────────────────────────────────────────────────────────────────────
const Demo = () => {
  const [activeTab, setActiveTab] = useState("widget");
  const [embedMode, setEmbedMode] = useState<"inline" | "bubble">("inline");

  const injectImage = useCallback(async (imageSrc: string) => {
    setActiveTab("widget");

    // Fetch the image and convert to a File object, then inject into widget's file input
    try {
      const response = await fetch(imageSrc);
      const blob = await response.blob();
      const file = new File([blob], "search-image.png", { type: "image/png" });

      let attempts = 0;
      const maxAttempts = 10;
      const tryInject = () => {
        attempts++;
        const container = document.getElementById("chatsku-widget");
        if (!container) {
          if (attempts < maxAttempts) setTimeout(tryInject, 300);
          return;
        }
        // Look for the file input inside the widget
        const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]');
        if (fileInput) {
          const dataTransfer = new DataTransfer();
          dataTransfer.items.add(file);
          fileInput.files = dataTransfer.files;
          fileInput.dispatchEvent(new Event("change", { bubbles: true }));
          container.scrollIntoView({ behavior: "smooth", block: "center" });
        } else if (attempts < maxAttempts) {
          setTimeout(tryInject, 300);
        }
      };
      setTimeout(tryInject, 150);
    } catch {
      toast.error("Failed to load image");
    }
  }, []);

  const injectSearchTerm = useCallback((term: string) => {
    setActiveTab("widget");

    // In bubble mode, open the bubble first by clicking the launcher
    if (embedMode === "bubble") {
      const launcher = document.querySelector<HTMLElement>(
        '[id*="chatsku-launcher"], [class*="chatsku-launcher"], [id*="ciq-launcher"], [class*="ciq-launcher"], [id^="chatsku-bubble"], [class*="chatsku-bubble"], [id*="chatsku"] button, [class*="ciq-widget-launcher"]'
      );
      if (launcher) launcher.click();
    }

    // The widget uses #ciq-input as its input element.
    // Retry a few times since the widget may still be loading or showing a welcome screen.
    let attempts = 0;
    const maxAttempts = 15;
    const tryInject = () => {
      attempts++;
      // Search broadly for the input — it may be anywhere in the DOM in bubble mode
      const input = (document.getElementById("ciq-input") ||
        document.querySelector<HTMLInputElement>('[id*="chatsku"] input[type="text"], [id*="chatsku"] textarea, [class*="ciq"] input[type="text"], [class*="ciq"] textarea')) as HTMLInputElement | null;
      if (input && input.offsetParent !== null) {
        // Use native setter to bypass React/framework state tracking
        const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
          || Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set;
        if (nativeInputValueSetter) {
          nativeInputValueSetter.call(input, term);
        } else {
          input.value = term;
        }
        input.dispatchEvent(new Event("input", { bubbles: true }));
        input.dispatchEvent(new Event("change", { bubbles: true }));
        input.focus();
        input.scrollIntoView({ behavior: "smooth", block: "center" });
      } else if (attempts < maxAttempts) {
        setTimeout(tryInject, 300);
      } else {
        navigator.clipboard.writeText(term);
        toast.info("Copied to clipboard — paste it in the widget input");
      }
    };
    setTimeout(tryInject, 300);
  }, [embedMode]);

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main className="pt-20 pb-0">
        <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-16">
          {/* Mobile: compact header + prompt chips above widget */}
          <div className="lg:hidden mb-4 pt-2">
            <h1 className="font-display font-bold text-2xl text-foreground mb-1">
              See ChatSKU in action
            </h1>
            <p className="text-muted-foreground text-sm mb-3">
              Live widget on a sample industrial catalog. Try these:
            </p>
            <div className="flex flex-wrap gap-2 mb-1">
              {[
                { label: "Plexiclass", term: "Plexiclass" },
                { label: "pipes", term: "pipes" },
                { label: "Plexiglass sheets", term: "Do you have clear plexiglass acrylic sheets in 12 by 24?" },
                { label: "Safety glasses", term: "I need safety glasses that are anti-fog for my warehouse." },
                { label: "PVC pipe", term: "What schedule 80 PVC pipe do you carry in 1 inch?" },
              ].map((chip) => (
                <button
                  key={chip.label}
                  onClick={() => injectSearchTerm(chip.term)}
                  className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-medium bg-primary/10 text-primary border border-primary/20 hover:bg-primary/20 transition-colors"
                >
                  <CornerDownRight className="w-3 h-3" />
                  {chip.label}
                </button>
              ))}
            </div>
          </div>

          <div className="grid lg:grid-cols-[minmax(0,0.7fr)_minmax(0,1.3fr)] gap-8 items-start">
            {/* Left: Header content (desktop only) */}
            <div className={`hidden lg:block overflow-visible pt-4 transition-opacity duration-300 ${activeTab === "admin" ? "opacity-40 pointer-events-none" : ""}`}>
              <h1 className="font-display font-bold text-2xl sm:text-3xl text-foreground mb-2">
                See ChatSKU in action
              </h1>
              <p className="text-muted-foreground text-sm max-w-md mb-6">
                This is a live widget running on a sample industrial supplies catalog. Search for products, ask questions, and submit a quote — just like your customers would.
              </p>
              <div className="mt-6 rounded-xl border border-border bg-secondary/40 p-4 text-sm space-y-3">
                <p className="font-display font-bold text-base text-foreground">Search Tips</p>
                <div>
                  <p className="font-semibold text-foreground mb-1.5">Try searching like your customers would:</p>
                  <ul className="space-y-1 text-muted-foreground pl-4">
                    <li>
                      <span className="font-semibold text-foreground">Spelling correction:</span> Type <em>Plexiclass</em> instead of Plexiglass
                      <TryItButton term="Plexiclass" onClick={injectSearchTerm} />
                    </li>
                    <li><span className="font-semibold text-foreground">Voice Input:</span> Click the microphone and say <em>Acrylic Tubes</em> (Spoiler: this won't work without a microphone!)</li>
                    <li>
                      <span className="font-semibold text-foreground">Synonyms:</span> Type <em>pipes</em> (the demo store has only hoses)
                      <TryItButton term="pipes" onClick={injectSearchTerm} />
                    </li>
                  </ul>
                </div>
                <div>
                  <p className="font-semibold text-foreground mb-1.5">Or try natural language queries:</p>
                  <ul className="space-y-1 text-muted-foreground pl-4 italic">
                    <li>
                      Do you have clear plexiglass acrylic sheets in 12 by 24?
                      <TryItButton term="Do you have clear plexiglass acrylic sheets in 12 by 24?" onClick={injectSearchTerm} />
                    </li>
                    <li>
                      I need safety glasses that are anti-fog for my warehouse.
                      <TryItButton term="I need safety glasses that are anti-fog for my warehouse." onClick={injectSearchTerm} />
                    </li>
                    <li>
                      What schedule 80 PVC pipe do you carry in 1 inch?
                      <TryItButton term="What schedule 80 PVC pipe do you carry in 1 inch?" onClick={injectSearchTerm} />
                    </li>
                  </ul>
                </div>
              </div>

              <div className="mt-4 rounded-xl border border-border bg-secondary/40 p-4 text-sm space-y-3">
                <p className="font-display font-bold text-base text-foreground">Or click on any image to try image search</p>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    { src: "/images/demo-hoist-control.png", alt: "Hoist Control" },
                    { src: "/images/demo-hydro-pump.png", alt: "Hydraulic Pump" },
                    { src: "/images/demo-reservoir.png", alt: "Reservoir" },
                  ].map((img) => (
                    <button
                      key={img.alt}
                      onClick={() => injectImage(img.src)}
                      className="group relative rounded-lg border border-border bg-card overflow-hidden hover:border-primary/50 hover:shadow-md transition-all cursor-pointer"
                    >
                      <img src={img.src} alt={img.alt} className="w-full h-auto object-contain p-2" />
                      <div className="absolute inset-0 bg-primary/0 group-hover:bg-primary/10 transition-colors flex items-center justify-center">
                        <ImageIcon className="w-5 h-5 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              <Button asChild size="lg" className="mt-4 bg-primary text-primary-foreground hover:bg-teal-glow font-semibold glow-teal-sm px-7">
                <Link to="/signup">Start My Free Trial <ArrowRight className="w-4 h-4" /></Link>
              </Button>
            </div>

            {/* Right: Tabs (full width on mobile) */}
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full lg:col-start-2">
              <TabsList className="w-full grid grid-cols-2 bg-secondary/50 border border-border rounded-xl h-11">
                <TabsTrigger value="widget" className="rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-md flex items-center gap-2 text-sm font-semibold">
                  <MessageSquare className="w-4 h-4" />
                  Customer Chat Widget
                </TabsTrigger>
                <TabsTrigger value="admin" className="rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-md flex items-center gap-2 text-sm font-semibold">
                  <Monitor className="w-4 h-4" />
                  Admin Dashboard
                </TabsTrigger>
              </TabsList>

              <TabsContent value="widget" className="mt-4 space-y-3">
                {/* Bubble / Inline toggle */}
                <div className="flex justify-center">
                  <div className="inline-flex items-center rounded-full border border-border bg-secondary/50 p-1 gap-0.5">
                    <button
                      onClick={() => {
                        collapseChatskuBubble();
                        setEmbedMode("inline");
                      }}
                      className={`inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-semibold transition-colors ${
                        embedMode === "inline"
                          ? "bg-primary text-primary-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <Maximize2 className="w-3.5 h-3.5" />
                      Inline
                    </button>
                    <button
                      onClick={() => setEmbedMode("bubble")}
                      className={`inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-semibold transition-colors ${
                        embedMode === "bubble"
                          ? "bg-primary text-primary-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <PanelBottomClose className="w-3.5 h-3.5" />
                      Bubble
                    </button>
                  </div>
                </div>
                <LiveWidget embedMode={embedMode} />
              </TabsContent>

              <TabsContent value="admin" className="mt-4">
                <ImageViewer images={adminImages} />
                <div className="mt-4 text-center">
                  <Button asChild size="lg" className="bg-primary text-primary-foreground hover:bg-teal-glow font-semibold glow-teal-sm px-7">
                    <Link to="/demo/admin-request">
                      Request Admin Demo <ArrowRight className="w-4 h-4" />
                    </Link>
                  </Button>
                </div>
              </TabsContent>
            </Tabs>
          </div>

          {/* Mobile: image search + CTA below widget */}
          <div className="lg:hidden mt-6 space-y-4">
            <div className="rounded-xl border border-border bg-secondary/40 p-4 text-sm space-y-3">
              <p className="font-display font-bold text-base text-foreground">Try image search</p>
              <div className="grid grid-cols-3 gap-3">
                {[
                  { src: "/images/demo-hoist-control.png", alt: "Hoist Control" },
                  { src: "/images/demo-hydro-pump.png", alt: "Hydraulic Pump" },
                  { src: "/images/demo-reservoir.png", alt: "Reservoir" },
                ].map((img) => (
                  <button
                    key={img.alt}
                    onClick={() => injectImage(img.src)}
                    className="group relative rounded-lg border border-border bg-card overflow-hidden hover:border-primary/50 hover:shadow-md transition-all cursor-pointer"
                  >
                    <img src={img.src} alt={img.alt} className="w-full h-auto object-contain p-2" />
                    <div className="absolute inset-0 bg-primary/0 group-hover:bg-primary/10 transition-colors flex items-center justify-center">
                      <ImageIcon className="w-5 h-5 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
                    </div>
                  </button>
                ))}
              </div>
            </div>
            <Button asChild size="lg" className="w-full bg-primary text-primary-foreground hover:bg-teal-glow font-semibold glow-teal-sm px-7">
              <Link to="/signup">Start My Free Trial <ArrowRight className="w-4 h-4" /></Link>
            </Button>
          </div>
        </section>

        {/* Stats strip */}
        <section className="border-t border-border bg-secondary/30">
          <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div className="grid sm:grid-cols-3 gap-6 text-center mb-10">
              {[
                { icon: Clock, value: "~4 hours", label: "Average setup time" },
                { icon: Code, value: "1 line", label: "Of code to embed" },
                { icon: CheckCircle, value: "Any site", label: "Works on any website" },
              ].map(({ icon: Icon, value, label }) => (
                <div key={label} className="flex flex-col items-center gap-2">
                  <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
                    <Icon className="w-5 h-5 text-primary" />
                  </div>
                  <div className="font-display font-bold text-2xl text-foreground">{value}</div>
                  <div className="text-sm text-muted-foreground">{label}</div>
                </div>
              ))}
            </div>
            <div className="text-center">
              <h2 className="font-display font-bold text-3xl text-foreground mb-3">
                Ready to add this to your site?
              </h2>
              <p className="text-muted-foreground mb-6">Start free. Live in days, not months of dev time. No credit card required.</p>
              <div className="flex flex-wrap justify-center gap-3">
                <Button asChild size="lg" className="bg-primary text-primary-foreground hover:bg-teal-glow font-semibold glow-teal-sm px-7">
                  <Link to="/signup">Start Free <ArrowRight className="w-4 h-4" /></Link>
                </Button>
                <Button asChild size="lg" variant="outline" className="border-border hover:border-primary/50 font-semibold px-7">
                  <a href="https://calendly.com" target="_blank" rel="noopener noreferrer">Book a Demo Call</a>
                </Button>
              </div>
            </div>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
};

export default Demo;
