"use client";

/**
 * Right-sidebar settings panel. When a section is selected, shows a
 * dynamic form built from the section's current content keys (text,
 * colors, images, booleans). Image fields open the ImageLibrary modal.
 * When no section is selected, shows page-level settings + SEO score.
 *
 * CTA sections get an "Optimize CTA" panel at the bottom.
 */

import { useState } from "react";
import { ImageIcon, Sparkles, Loader2 } from "lucide-react";
import type { Section, Branding } from "@/lib/page-studio/section-registry";
import { getBlockDefinition } from "@/lib/page-studio/section-registry";
import ImageLibrary, { type BrandAssetDto } from "./image-library";
import CTAOptimizerPanel from "./cta-optimizer-panel";
import SeoScoreGauge from "./seo-score-gauge";
import type { SeoScoreResult } from "@/lib/services/page-seo-score";

// ── AI rewrite pop-over for text/textarea fields ──
interface Alt { label: string; text: string }
function AiRewriteButton({ brandId, sectionType, label, value, onReplace }: {
  brandId: string; sectionType: string; label: string; value: string; onReplace: (next: string) => void;
}) {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [alts, setAlts] = useState<Alt[]>([]);
  const [error, setError] = useState<string | null>(null);

  async function run() {
    if (!value.trim()) return;
    setLoading(true); setError(null); setOpen(true);
    try {
      const res = await fetch("/api/page-studio/rewrite", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, text: value, sectionType, fieldLabel: label }),
      });
      if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || "Rewrite failed"); }
      const data = await res.json();
      setAlts(data.alternatives || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Rewrite failed");
    } finally { setLoading(false); }
  }

  return (
    <div className="relative">
      <button onClick={run} disabled={loading || !value.trim()} title="Rewrite with AI"
        className="flex items-center justify-center w-6 h-6 rounded-md text-brand-600 hover:bg-brand-50 disabled:opacity-40">
        {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
      </button>
      {open && (alts.length > 0 || error) && (
        <div className="absolute right-0 top-7 z-20 w-72 bg-white border border-slate-200 rounded-xl shadow-xl p-2">
          {error ? (
            <p className="text-xs text-red-600 px-2 py-1.5">{error}</p>
          ) : alts.map((a, i) => (
            <button key={i} onClick={() => { onReplace(a.text); setOpen(false); }}
              className="w-full text-left px-2.5 py-2 rounded-lg hover:bg-brand-50 border-b border-slate-100 last:border-b-0">
              <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600 mb-0.5">{a.label}</p>
              <p className="text-xs text-slate-700 leading-snug line-clamp-3">{a.text}</p>
            </button>
          ))}
          <button onClick={() => setOpen(false)} className="mt-1 w-full text-center text-[10px] text-slate-400 hover:text-slate-600 py-1">Close</button>
        </div>
      )}
    </div>
  );
}

type FieldKind = "text" | "textarea" | "color" | "image" | "boolean" | "json";

function detectKind(key: string, value: unknown): FieldKind {
  if (typeof value === "boolean") return "boolean";
  if (typeof value === "string") {
    if (/^#[0-9a-f]{3,8}$/i.test(value)) return "color";
    if (/color/i.test(key)) return "color";
    if (/image|logo|photo|avatar|poster/i.test(key) || /^https?:\/\/.*\.(png|jpe?g|gif|webp)/i.test(value)) return "image";
    if (value.length > 80 || /description|body|content|answer|subheadline/i.test(key)) return "textarea";
    return "text";
  }
  return "json";
}

const CTA_SECTION_TYPES = new Set(["cta_banner", "contact_form", "phone_cta", "hero_with_form", "hero"]);

interface SectionSettingsProps { brandId: string; section: Section; onChange: (next: Section) => void }

function SectionSettings({ brandId, section, onChange }: SectionSettingsProps) {
  const def = getBlockDefinition(section.type);
  const [libraryField, setLibraryField] = useState<string | null>(null);
  const entries = Object.entries(section.content);
  const isCTA = CTA_SECTION_TYPES.has(section.type);

  function updateKey(key: string, value: unknown) {
    onChange({ ...section, content: { ...section.content, [key]: value } });
  }

  const currentCTA = String(section.content.ctaText || section.content.buttonText || "Get Started");

  return (
    <div className="space-y-4">
      <div>
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Section</p>
        <h3 className="text-sm font-bold text-slate-900">{def?.name ?? section.type}</h3>
      </div>
      {entries.map(([key, value]) => {
        const kind = detectKind(key, value);
        const label = key.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
        if (kind === "text") return (
          <div key={key}>
            <div className="flex items-center justify-between mb-1">
              <label className="text-[11px] font-semibold text-slate-600">{label}</label>
              <AiRewriteButton brandId={brandId} sectionType={section.type} label={label} value={String(value ?? "")} onReplace={(next) => updateKey(key, next)} />
            </div>
            <input type="text" value={String(value ?? "")} onChange={(e) => updateKey(key, e.target.value)}
              className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
          </div>
        );
        if (kind === "textarea") return (
          <div key={key}>
            <div className="flex items-center justify-between mb-1">
              <label className="text-[11px] font-semibold text-slate-600">{label}</label>
              <AiRewriteButton brandId={brandId} sectionType={section.type} label={label} value={String(value ?? "")} onReplace={(next) => updateKey(key, next)} />
            </div>
            <textarea rows={3} value={String(value ?? "")} onChange={(e) => updateKey(key, e.target.value)}
              className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
          </div>
        );
        if (kind === "color") return (
          <div key={key}>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">{label}</label>
            <div className="flex items-center gap-2">
              <input type="color" value={String(value ?? "#000000")} onChange={(e) => updateKey(key, e.target.value)}
                className="w-10 h-9 rounded-lg border border-slate-200 cursor-pointer" />
              <input type="text" value={String(value ?? "")} onChange={(e) => updateKey(key, e.target.value)}
                className="flex-1 px-3 py-2 text-xs font-mono border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
            </div>
          </div>
        );
        if (kind === "image") return (
          <div key={key}>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">{label}</label>
            <button onClick={() => setLibraryField(key)}
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-200 bg-white text-xs text-slate-700 hover:border-slate-300">
              <ImageIcon className="w-3.5 h-3.5 text-slate-400" />
              {value ? <span className="truncate flex-1 text-left">{String(value).slice(-40)}</span> : <span className="flex-1 text-left text-slate-400">Choose image…</span>}
            </button>
          </div>
        );
        if (kind === "boolean") return (
          <label key={key} className="flex items-center justify-between gap-2">
            <span className="text-[11px] font-semibold text-slate-600">{label}</span>
            <button onClick={() => updateKey(key, !value)}
              className={`relative w-9 h-5 rounded-full transition-colors ${value ? "bg-brand-600" : "bg-slate-200"}`}>
              <span className={`absolute top-0.5 ${value ? "left-4" : "left-0.5"} w-4 h-4 bg-white rounded-full shadow-sm transition-all`} />
            </button>
          </label>
        );
        return (
          <div key={key}>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">{label}</label>
            <textarea rows={5} value={JSON.stringify(value, null, 2)}
              onChange={(e) => { try { updateKey(key, JSON.parse(e.target.value)); } catch { /* swallow */ } }}
              className="w-full px-3 py-2 text-[11px] font-mono border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
          </div>
        );
      })}

      {/* CTA Optimizer */}
      {isCTA && (
        <CTAOptimizerPanel brandId={brandId} currentCTA={currentCTA}
          onApply={(text) => updateKey(section.content.ctaText !== undefined ? "ctaText" : "buttonText", text)} />
      )}

      {libraryField && (
        <ImageLibrary brandId={brandId} open={true} onClose={() => setLibraryField(null)}
          onSelect={(asset: BrandAssetDto) => { updateKey(libraryField, asset.url); setLibraryField(null); }} />
      )}
    </div>
  );
}

interface PageSettings {
  title: string; slug: string; purpose: string; metaDescription: string; branding: Branding;
}

interface PageSettingsProps { page: PageSettings; onChange: (next: PageSettings) => void; seoScore: SeoScoreResult | null }

function PageSettingsEditor({ page, onChange, seoScore }: PageSettingsProps) {
  function update<K extends keyof PageSettings>(key: K, value: PageSettings[K]) { onChange({ ...page, [key]: value }); }
  function updateBranding(key: keyof Branding, value: string) { onChange({ ...page, branding: { ...page.branding, [key]: value } }); }
  return (
    <div className="space-y-4">
      <div><p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Page Settings</p></div>

      {/* SEO Score gauge */}
      {seoScore && <SeoScoreGauge result={seoScore} />}

      <div>
        <label className="block text-[11px] font-semibold text-slate-600 mb-1">Page Title</label>
        <input type="text" value={page.title} onChange={(e) => update("title", e.target.value)}
          className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
      </div>
      <div>
        <label className="block text-[11px] font-semibold text-slate-600 mb-1">Slug</label>
        <input type="text" value={page.slug} onChange={(e) => update("slug", e.target.value)}
          className="w-full px-3 py-2 text-sm font-mono border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
      </div>
      <div className="flex items-center gap-2">
        <span className="text-[11px] font-semibold text-slate-600">Purpose</span>
        <span className="text-[10px] font-bold uppercase tracking-wide text-brand-700 bg-brand-50 border border-brand-200 rounded-full px-2 py-0.5">{page.purpose.replace(/_/g, " ")}</span>
      </div>
      <div>
        <label className="block text-[11px] font-semibold text-slate-600 mb-1">Meta Description</label>
        <textarea rows={3} value={page.metaDescription} onChange={(e) => update("metaDescription", e.target.value)}
          className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
      </div>
      <div className="pt-2 border-t border-slate-100">
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Brand Colors</p>
        {(["primaryColor", "secondaryColor", "accentColor"] as const).map((k) => (
          <div key={k} className="mb-2">
            <label className="block text-[11px] font-semibold text-slate-600 mb-1 capitalize">{k.replace("Color", "")} color</label>
            <div className="flex items-center gap-2">
              <input type="color" value={page.branding[k]} onChange={(e) => updateBranding(k, e.target.value)} className="w-10 h-9 rounded-lg border border-slate-200 cursor-pointer" />
              <input type="text" value={page.branding[k]} onChange={(e) => updateBranding(k, e.target.value)} className="flex-1 px-3 py-2 text-xs font-mono border border-slate-200 rounded-lg" />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

interface Props {
  brandId: string;
  selectedSection: Section | null;
  onSectionChange: (next: Section) => void;
  page: PageSettings;
  onPageChange: (next: PageSettings) => void;
  seoScore?: SeoScoreResult | null;
}

export default function SettingsPanel({ brandId, selectedSection, onSectionChange, page, onPageChange, seoScore }: Props) {
  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-auto p-4">
        {selectedSection ? (
          <SectionSettings brandId={brandId} section={selectedSection} onChange={onSectionChange} />
        ) : (
          <PageSettingsEditor page={page} onChange={onPageChange} seoScore={seoScore ?? null} />
        )}
      </div>
    </div>
  );
}

export type { PageSettings };
