"use client";

import { useMemo, useState } from "react";
import { Check, Copy, Loader2, Lock, Rocket } from "lucide-react";

type Tab = {
  id: string;
  title: string;
  description: string;
  endpoints: string[];
  sample: Record<string, any>;
};

const tabs: Tab[] = [
  {
    id: "theme",
    title: "Theme & Branding",
    description:
      "Brand colors, typography, radii, shadows, container widths, logos.",
    endpoints: [
      "GET /api/site/theme",
      "PATCH /api/site/theme",
      "POST /api/site/theme/publish",
    ],
    sample: {
      lang: "en",
      theme: {
        primary_color: "#0F9972",
        secondary_color: "#111827",
        accent_color: "#22c55e",
        gradient_from: "#0F9972",
        gradient_to: "#0ea5e9",
        text_primary: "#111827",
        text_secondary: "#4b5563",
        background: "#f8fafc",
        button_radius: 12,
        button_shadow: "0 10px 30px rgba(15,153,114,0.25)",
        container_width: 1200,
        font_heading: "Space Grotesk",
        font_body: "Inter",
      },
      branding: {
        logo_url: "https://cdn.mawidi.com/logo.svg",
        favicon_url: "https://cdn.mawidi.com/favicon.png",
        social_links: { x: "https://x.com/mawidi" },
        contact_email: "hello@mawidi.com",
      },
    },
  },
  {
    id: "hero",
    title: "Hero",
    description: "Headline, subheading, CTAs, background art.",
    endpoints: [
      "GET /api/site/hero",
      "PATCH /api/site/hero",
      "POST /api/site/hero/publish",
    ],
    sample: {
      lang: "en",
      title: "Run your clinic on autopilot",
      subtitle:
        "AI reception, scheduling, reminders, payments—all in one place.",
      eyebrow: "Healthcare-grade automation",
      badgeText: "14-day free trial",
      alignment: "left",
      primaryCta: { label: "Start free trial", href: "/signup" },
      secondaryCta: { label: "Talk to sales", href: "/demo" },
      background: { gradient: ["#0F9972", "#0ea5e9"] },
      mediaId: "",
    },
  },
  {
    id: "features",
    title: "Features",
    description: "Layout and feature bullets/cards.",
    endpoints: [
      "GET /api/site/features",
      "PATCH /api/site/features",
      "POST /api/site/features/publish",
    ],
    sample: {
      lang: "en",
      title: "Built for GCC clinics",
      subtitle: "Automate booking, intake, follow-ups, and billing.",
      layout: "cards",
      items: [
        {
          icon: "calendar",
          label: "Smart scheduling",
          description: "Fill calendars with AI reminders.",
        },
        {
          icon: "phone",
          label: "Voice concierge",
          description: "AI answers, routes, and books.",
        },
        {
          icon: "chart",
          label: "Revenue insights",
          description: "Track no-shows, deposits, LTV.",
        },
      ],
    },
  },
  {
    id: "social-proof",
    title: "Social Proof",
    description: "Logos and testimonials.",
    endpoints: [
      "GET /api/site/social-proof",
      "PATCH /api/site/social-proof",
      "POST /api/site/social-proof/publish",
    ],
    sample: {
      lang: "en",
      title: "Trusted across GCC",
      subtitle: "Clinics and spas in Doha, Riyadh, Dubai.",
      logos: [{ label: "Doha Clinics", url: "/logos/doha.svg" }],
      testimonials: [
        {
          quote: "Cut no-shows by 32% in month one.",
          name: "Dr. Sara",
          role: "Founder, Al Noor",
        },
      ],
    },
  },
  {
    id: "pricing-copy",
    title: "Pricing Copy",
    description: "Pricing page text and FAQ (prices still from Stripe/config).",
    endpoints: [
      "GET /api/site/pricing-copy",
      "PATCH /api/site/pricing-copy",
      "POST /api/site/pricing-copy/publish",
    ],
    sample: {
      lang: "en",
      title: "Transparent pricing for every stage",
      subtitle: "14-day free trial. No card required.",
      highlight: "Save 7% with yearly billing",
      ctaLabel: "Choose plan",
      ctaHref: "/pricing",
      faq: [
        {
          q: "Can I cancel anytime?",
          a: "Yes, instant cancel from dashboard.",
        },
      ],
    },
  },
  {
    id: "faq",
    title: "FAQ",
    description: "Global FAQ blocks.",
    endpoints: [
      "GET /api/site/faq",
      "PATCH /api/site/faq",
      "POST /api/site/faq/publish",
    ],
    sample: {
      lang: "en",
      entries: [
        {
          question: "Is there onboarding?",
          answer: "Yes, white-glove in English & Arabic.",
        },
      ],
    },
  },
  {
    id: "cta",
    title: "CTA",
    description: "End-of-page call to action.",
    endpoints: [
      "GET /api/site/cta",
      "PATCH /api/site/cta",
      "POST /api/site/cta/publish",
    ],
    sample: {
      lang: "en",
      title: "Ready to launch?",
      subtitle: "Spin up your AI receptionist today.",
      ctaLabel: "Get started",
      ctaHref: "/signup",
      background: { gradient: ["#0F9972", "#0ea5e9"] },
    },
  },
  {
    id: "footer",
    title: "Footer",
    description: "Footer columns, social, legal.",
    endpoints: [
      "GET /api/site/footer",
      "PATCH /api/site/footer",
      "POST /api/site/footer/publish",
    ],
    sample: {
      lang: "en",
      columns: [
        { title: "Product", links: [{ label: "Pricing", href: "/pricing" }] },
      ],
      legalLinks: [{ label: "Privacy", href: "/privacy" }],
      contactText: "hello@mawidi.com",
      newsletter: true,
      socialLinks: { x: "https://x.com/mawidi" },
    },
  },
  {
    id: "layout",
    title: "Layout",
    description: "Section ordering and visibility.",
    endpoints: [
      "GET /api/site/layout",
      "PATCH /api/site/layout",
      "POST /api/site/layout/publish",
    ],
    sample: {
      lang: "en",
      sections: [
        { id: "hero", enabled: true },
        { id: "social-proof", enabled: true },
        { id: "pricing", enabled: true },
        { id: "faq", enabled: true },
        { id: "cta", enabled: true },
      ],
    },
  },
];

function pretty(obj: Record<string, any>) {
  return JSON.stringify(obj, null, 2);
}

export default function SiteExperienceDashboard({
  user,
}: {
  user: { id: string; role: string; name: string };
}) {
  const [activeTab, setActiveTab] = useState<Tab>(tabs[0]);
  const [editorState, setEditorState] = useState<Record<string, string>>(() =>
    tabs.reduce<Record<string, string>>((acc, tab) => {
      acc[tab.id] = pretty(tab.sample);
      return acc;
    }, {}),
  );
  const [status, setStatus] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [previewToken, setPreviewToken] = useState<string | null>(null);
  const [tokenLoading, setTokenLoading] = useState(false);
  const [copied, setCopied] = useState(false);

  const canPublish = useMemo(
    () => ["ADMIN", "SUPER_ADMIN"].includes(user.role),
    [user.role],
  );

  const handleSaveDraft = async () => {
    try {
      setLoading(true);
      setStatus(null);
      const payload = JSON.parse(editorState[activeTab.id]);
      const res = await fetch(`/api/site/${activeTab.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to save draft");
      setStatus("Draft saved");
    } catch (err: any) {
      setStatus(err.message || "Failed to save draft");
    } finally {
      setLoading(false);
    }
  };

  const handlePublish = async () => {
    if (!canPublish) {
      setStatus("Publish is admin only");
      return;
    }
    try {
      setLoading(true);
      setStatus(null);
      const payload = JSON.parse(editorState[activeTab.id]);
      const lang = payload.lang || "en";
      const res = await fetch(`/api/site/${activeTab.id}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ lang }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to publish");
      setStatus("Published");
    } catch (err: any) {
      setStatus(err.message || "Failed to publish");
    } finally {
      setLoading(false);
    }
  };

  const handleCreatePreviewToken = async () => {
    try {
      setTokenLoading(true);
      setCopied(false);
      const res = await fetch("/api/site/preview-token", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scopes: ["all"], expiresInMinutes: 120 }),
      });
      const data = await res.json();
      if (!res.ok)
        throw new Error(data.error || "Failed to create preview token");
      setPreviewToken(data.token);
      setStatus("Preview token created");
    } catch (err: any) {
      setStatus(err.message || "Failed to create preview token");
    } finally {
      setTokenLoading(false);
    }
  };

  const handleCopy = async () => {
    if (!previewToken) return;
    await navigator.clipboard.writeText(previewToken);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="space-y-8">
      <div className="rounded-3xl border border-gray-100 bg-white px-6 py-7 shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <p className="text-xs font-semibold uppercase text-emerald-600">
              Site Experience Control
            </p>
            <h1 className="text-3xl font-bold text-brand-ink">
              Brand, Content, Layout, Social
            </h1>
            <p className="text-gray-600 text-sm mt-1">
              Edit once, preview drafts with tokens, and publish when ready. All
              endpoints are live.
            </p>
          </div>
          <div className="flex flex-wrap gap-3">
            <button
              onClick={handleCreatePreviewToken}
              className="inline-flex items-center gap-2 rounded-lg border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 hover:bg-gray-50"
              disabled={tokenLoading}
            >
              {tokenLoading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Lock className="w-4 h-4" />
              )}
              Preview token
            </button>
            {previewToken && (
              <button
                onClick={handleCopy}
                className="inline-flex items-center gap-2 rounded-lg bg-emerald-50 px-4 py-2 text-sm font-semibold text-emerald-800"
              >
                {copied ? (
                  <Check className="w-4 h-4" />
                ) : (
                  <Copy className="w-4 h-4" />
                )}
                {copied ? "Copied" : "Copy token"}
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        <div className="lg:col-span-1 space-y-2">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab)}
              className={`w-full text-left px-4 py-3 rounded-xl border text-sm font-semibold transition ${
                activeTab.id === tab.id
                  ? "border-brand-green bg-emerald-50 text-brand-ink"
                  : "border-gray-200 bg-white hover:border-brand-green/60"
              }`}
            >
              <div className="flex items-center justify-between">
                <span>{tab.title}</span>
                {activeTab.id === tab.id && (
                  <span className="text-xs text-emerald-600">editing</span>
                )}
              </div>
              <p className="text-xs text-gray-500 mt-1">{tab.description}</p>
            </button>
          ))}
        </div>

        <div className="lg:col-span-3">
          <div className="rounded-2xl border border-gray-100 bg-white shadow-sm p-5 space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs uppercase text-gray-500 font-semibold">
                  Section
                </p>
                <h2 className="text-xl font-bold text-brand-ink">
                  {activeTab.title}
                </h2>
                <p className="text-sm text-gray-600">{activeTab.description}</p>
              </div>
              <div className="flex gap-2">
                <button
                  onClick={handleSaveDraft}
                  disabled={loading}
                  className="inline-flex items-center gap-2 rounded-lg bg-gray-900 text-white px-4 py-2 text-sm font-semibold shadow-sm hover:bg-gray-800 disabled:opacity-60"
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <SaveIcon />
                  )}
                  Save draft
                </button>
                <button
                  onClick={handlePublish}
                  disabled={loading || !canPublish}
                  className="inline-flex items-center gap-2 rounded-lg bg-brand-green text-white px-4 py-2 text-sm font-semibold shadow-sm hover:bg-emerald-700 disabled:opacity-60"
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Rocket className="w-4 h-4" />
                  )}
                  Publish
                </button>
              </div>
            </div>

            <div className="rounded-xl border border-gray-100 bg-gray-50 p-3">
              <p className="text-xs font-semibold text-gray-500 mb-2">
                Endpoints
              </p>
              <div className="flex flex-wrap gap-2">
                {activeTab.endpoints.map((ep) => (
                  <span
                    key={ep}
                    className="inline-flex items-center gap-2 rounded-lg bg-white border border-gray-200 px-3 py-1 text-xs font-semibold text-gray-700"
                  >
                    {ep}
                  </span>
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <p className="text-sm font-semibold text-brand-ink">
                  Draft payload (JSON)
                </p>
                <span className="text-xs text-gray-500">
                  Include `lang` when editing multiple locales
                </span>
              </div>
              <textarea
                value={editorState[activeTab.id]}
                onChange={(e) =>
                  setEditorState((prev) => ({
                    ...prev,
                    [activeTab.id]: e.target.value,
                  }))
                }
                rows={16}
                className="w-full font-mono text-sm rounded-lg border border-gray-200 bg-gray-50 p-3 focus:border-brand-green focus:ring-2 focus:ring-brand-green/30"
              />
            </div>

            {status && (
              <div className="rounded-lg bg-emerald-50 border border-emerald-200 text-emerald-800 px-3 py-2 text-sm font-semibold">
                {status}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function SaveIcon() {
  return (
    <svg
      className="w-4 h-4"
      viewBox="0 0 20 20"
      fill="currentColor"
      aria-hidden="true"
    >
      <path d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h9a1 1 0 00.7-.3l3-3A1 1 0 0017 13V5a2 2 0 00-2-2H4zm8 1h2v3h-2V4zM5 4h5v4a1 1 0 001 1h4v2h-4a1 1 0 00-1 1v4H5V4z" />
    </svg>
  );
}
