"use client";

import { useEffect, useMemo, useState } from "react";

interface Board {
  id: string;
  name: string;
  publicKey: string;
  brand?: { color?: string; position?: "br" | "bl" | "tr" | "tl"; emoji?: string } | null;
}

const PRESET_COLORS = [
  { name: "Emerald", v: "#10b981" },
  { name: "Sky", v: "#0ea5e9" },
  { name: "Indigo", v: "#6366f1" },
  { name: "Violet", v: "#8b5cf6" },
  { name: "Pink", v: "#ec4899" },
  { name: "Rose", v: "#f43f5e" },
  { name: "Orange", v: "#f97316" },
  { name: "Amber", v: "#f59e0b" },
  { name: "Black", v: "#0a0a0a" },
];

const POSITIONS = [
  { key: "br", label: "Bottom-Right" },
  { key: "bl", label: "Bottom-Left" },
  { key: "tr", label: "Top-Right" },
  { key: "tl", label: "Top-Left" },
] as const;

const EMOJIS = ["💬", "👋", "✨", "🐛", "💡", "📨", "🙏", "🔥", "📣"];

export function EmbedCustomizer({ board }: { board: Board }) {
  const initial = board.brand || {};
  const [color, setColor] = useState<string>(initial.color || "#10b981");
  const [position, setPosition] = useState<"br" | "bl" | "tr" | "tl">(initial.position || "br");
  const [emoji, setEmoji] = useState<string>(initial.emoji || "💬");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [copied, setCopied] = useState<string | null>(null);

  const snippet = useMemo(() => {
    return `<script\n  src="https://inbox.mindie.dev/widget.js"\n  data-board="${board.publicKey}"\n  async></script>`;
  }, [board.publicKey]);

  const reactSnippet = useMemo(() => {
    return `// pages/_app.tsx or app/layout.tsx
<Script
  src="https://inbox.mindie.dev/widget.js"
  data-board="${board.publicKey}"
  strategy="afterInteractive" />`;
  }, [board.publicKey]);

  const dirty =
    color !== (initial.color || "#10b981") ||
    position !== (initial.position || "br") ||
    emoji !== (initial.emoji || "💬");

  async function save() {
    setSaving(true);
    setSaved(false);
    try {
      const res = await fetch(`/api/proxy/boards/${board.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brand: { color, position, emoji } }),
      });
      if (res.ok) {
        setSaved(true);
        setTimeout(() => setSaved(false), 2500);
      }
    } finally {
      setSaving(false);
    }
  }

  function copy(text: string, key: string) {
    navigator.clipboard.writeText(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 2000);
  }

  const posStyle: Record<typeof position, React.CSSProperties> = {
    br: { bottom: 12, right: 12 },
    bl: { bottom: 12, left: 12 },
    tr: { top: 12, right: 12 },
    tl: { top: 12, left: 12 },
  };

  return (
    <>
      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <h3 className="font-bold mb-4">Customize</h3>
        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-5">
            <div>
              <label className="block text-xs uppercase text-white/50 font-mono mb-2">Brand color</label>
              <div className="flex flex-wrap gap-2 mb-2">
                {PRESET_COLORS.map((c) => (
                  <button key={c.v}
                    onClick={() => setColor(c.v)}
                    title={c.name}
                    className="w-8 h-8 rounded-lg border-2 transition"
                    style={{
                      background: c.v,
                      borderColor: color === c.v ? "white" : "transparent",
                    }} />
                ))}
              </div>
              <div className="flex items-center gap-2">
                <input type="color" value={color} onChange={(e) => setColor(e.target.value)}
                  className="w-12 h-9 bg-transparent border border-white/10 rounded-md cursor-pointer" />
                <input type="text" value={color}
                  onChange={(e) => /^#[0-9a-fA-F]{0,6}$/.test(e.target.value) && setColor(e.target.value)}
                  className="flex-1 px-3 py-1.5 bg-ink-900 border border-white/10 rounded-md font-mono text-sm" />
              </div>
            </div>

            <div>
              <label className="block text-xs uppercase text-white/50 font-mono mb-2">Position</label>
              <div className="grid grid-cols-2 gap-2">
                {POSITIONS.map((p) => (
                  <button key={p.key}
                    onClick={() => setPosition(p.key)}
                    className={`px-3 py-2 rounded-lg text-sm font-semibold border transition ${
                      position === p.key
                        ? "bg-brand-500/15 border-brand-500/40 text-brand-400"
                        : "bg-ink-900 border-white/10 text-white/60 hover:border-white/20"
                    }`}
                  >{p.label}</button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-xs uppercase text-white/50 font-mono mb-2">Button icon</label>
              <div className="flex flex-wrap gap-2">
                {EMOJIS.map((e) => (
                  <button key={e} onClick={() => setEmoji(e)}
                    className={`w-10 h-10 rounded-lg border text-lg transition ${
                      emoji === e ? "bg-brand-500/15 border-brand-500/40" : "bg-ink-900 border-white/10 hover:border-white/20"
                    }`}
                  >{e}</button>
                ))}
              </div>
            </div>

            <div className="flex items-center gap-3">
              <button onClick={save} disabled={!dirty || saving}
                className="bg-brand-500 hover:bg-brand-400 text-ink-950 font-semibold px-4 py-2 rounded-lg disabled:opacity-50">
                {saving ? "Saving…" : dirty ? "Save changes" : "Saved"}
              </button>
              {saved && <span className="text-sm text-emerald-400">✓ saved · live in &lt;5s</span>}
            </div>
          </div>

          <div>
            <label className="block text-xs uppercase text-white/50 font-mono mb-2">Live preview</label>
            <div className="relative rounded-lg overflow-hidden bg-gradient-to-br from-ink-900 to-ink-950 border border-white/10 aspect-[4/3]">
              <div className="absolute inset-0 grid place-items-center text-white/30 text-xs">
                your-site.com
              </div>
              <button
                style={{
                  ...posStyle[position],
                  position: "absolute",
                  width: 48,
                  height: 48,
                  borderRadius: "50%",
                  background: color,
                  color: "white",
                  border: "none",
                  fontSize: 20,
                  boxShadow: "0 6px 18px rgba(0,0,0,.25)",
                  cursor: "pointer",
                }}
                title="This is what the widget looks like"
              >{emoji}</button>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <div className="flex items-center justify-between mb-3 gap-2 flex-wrap">
          <h3 className="font-bold">HTML — drop in &lt;head&gt; or end of &lt;body&gt;</h3>
          <button onClick={() => copy(snippet, "html")}
            className="text-xs px-3 py-1.5 rounded-lg bg-ink-900 border border-white/10 hover:border-brand-500/40">
            {copied === "html" ? "✓ Copied" : "Copy"}
          </button>
        </div>
        <pre className="bg-ink-900 border border-white/10 rounded-lg p-4 text-sm font-mono text-brand-400 overflow-x-auto">{snippet}</pre>
      </div>

      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <div className="flex items-center justify-between mb-3 gap-2 flex-wrap">
          <h3 className="font-bold">Next.js / React</h3>
          <button onClick={() => copy(reactSnippet, "react")}
            className="text-xs px-3 py-1.5 rounded-lg bg-ink-900 border border-white/10 hover:border-brand-500/40">
            {copied === "react" ? "✓ Copied" : "Copy"}
          </button>
        </div>
        <pre className="bg-ink-900 border border-white/10 rounded-lg p-4 text-sm font-mono text-white/70 overflow-x-auto whitespace-pre">{reactSnippet}</pre>
      </div>
    </>
  );
}
