'use client';

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

// Per-(definition, project) workflow settings drawer.
//
// Brand inheritance: this drawer does NOT duplicate the global brand. All
// brand attributes (logo, colors, fonts, voice, presentation style) come
// from /settings/brand. The drawer holds only WORKFLOW-SPECIFIC
// presentation overrides: sender name override, cover image, cover copy,
// and optional accent override.
//
// Sections:
//   1. Project — which project owns cases started from this definition
//   2. Presentation — cover artwork + copy + optional sender/accent override
//   3. Agents — per-stage agent template overrides
//   4. Auto-approval — declarative rule JSON
//   5. Sharing — toggle + default expiry days

function emptyPresentation() {
  return {
    sender_name: '',
    cover_image_url: '',
    cover_copy: { title: '', subtitle: '' },
    accent_hex: '',
    logo_url: '',
  };
}

export default function SettingsDrawer({ definition, projects, initialProjectId, onClose }) {
  const [projectId, setProjectId] = useState(initialProjectId);
  const [settings, setSettings] = useState(null);
  const [resolvedBrand, setResolvedBrand] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [savingSection, setSavingSection] = useState(null);

  const [presentation, setPresentation] = useState(emptyPresentation());
  const [agentDraft, setAgentDraft] = useState('{}');
  const [autoApproveDraft, setAutoApproveDraft] = useState('[]');
  const [shareEnabled, setShareEnabled] = useState(false);
  const [shareExpiry, setShareExpiry] = useState(14);
  const [defaultForProject, setDefaultForProject] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    fetch(`/api/processes/definitions/${definition.slug}/settings?project_id=${encodeURIComponent(projectId)}&include_brand=1`)
      .then((r) => r.json())
      .then((j) => {
        if (cancelled) return;
        if (j.error) { setError(j.error); setLoading(false); return; }
        setSettings(j.settings);
        setResolvedBrand(j.resolved_brand || null);
        const brand = j.settings?.brand || emptyPresentation();
        setPresentation({
          sender_name: brand.sender_name || '',
          cover_image_url: brand.cover_image_url || '',
          cover_copy: { title: brand.cover_copy?.title || '', subtitle: brand.cover_copy?.subtitle || '' },
          accent_hex: brand.accent_hex || '',
          logo_url: brand.logo_url || '',
        });
        setAgentDraft(JSON.stringify(j.settings?.agent_overrides || {}, null, 2));
        setAutoApproveDraft(JSON.stringify(j.settings?.auto_approve_rules || [], null, 2));
        setShareEnabled(Boolean(j.settings?.share_link_enabled));
        setShareExpiry(Number(j.settings?.share_link_default_expiry_days || 14));
        setDefaultForProject(Boolean(j.settings?.default_for_project));
        setLoading(false);
      })
      .catch((err) => { if (!cancelled) { setError(String(err)); setLoading(false); } });
    return () => { cancelled = true; };
  }, [definition.slug, projectId]);

  const saveSection = async (patch, sectionId) => {
    setSavingSection(sectionId);
    setError(null);
    try {
      const res = await fetch(`/api/processes/definitions/${definition.slug}/settings`, {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ project_id: projectId, ...patch }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || 'save_failed');
      setSettings(json.settings);
    } catch (err) {
      setError(String(err?.message || err));
    } finally {
      setSavingSection(null);
    }
  };

  // Compute the effective brand the renderer will use (overrides + global).
  const effectiveBrand = useMemo(() => ({
    accent_hex: presentation.accent_hex || resolvedBrand?.accent_hex || '#c2452a',
    sender_name: presentation.sender_name || resolvedBrand?.sender_name || 'Madarx OS',
    logo_url: presentation.logo_url || resolvedBrand?.logo_url || null,
    cover_image_url: presentation.cover_image_url || null,
    cover_copy: presentation.cover_copy,
    fonts: resolvedBrand?.fonts || [],
  }), [presentation, resolvedBrand]);

  const previewSrcDoc = useMemo(() => {
    const accent = effectiveBrand.accent_hex;
    const sender = escapeForHtml(effectiveBrand.sender_name);
    const title = escapeForHtml(presentation.cover_copy.title || definition.name);
    const subtitle = escapeForHtml(presentation.cover_copy.subtitle || 'Submit the details below to start.');
    const cover = effectiveBrand.cover_image_url
      ? `background-image:linear-gradient(135deg,${accent}cc,#0e0d0ccc),url('${escapeForHtml(effectiveBrand.cover_image_url)}');background-size:cover;background-position:center;`
      : `background:linear-gradient(135deg,${accent},#0e0d0c);`;
    return `<!DOCTYPE html><html><head><style>body{margin:0;font:13px/1.45 ui-sans-serif,system-ui,sans-serif;background:#f7f4ee;padding:14px;color:#1a1817}.hdr{font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:#69707a;margin-bottom:8px}.cv{${cover};height:74px;border-radius:12px;margin-bottom:10px}h1{font-size:18px;margin:0 0 4px}p{margin:0;color:#5f5a55;font-size:12px}.ftr{margin-top:10px;color:#69707a;font-size:10.5px}</style></head><body><div class="hdr">${sender} · Intake</div><div class="cv"></div><h1>${title}</h1><p>${subtitle}</p><p class="ftr">Powered by ${sender}</p></body></html>`;
  }, [definition.name, effectiveBrand, presentation.cover_copy]);

  return (
    <div className="wf-drawer-scrim" role="dialog" aria-label="Workflow settings" onClick={onClose}>
      <aside className="wf-drawer" onClick={(e) => e.stopPropagation()}>
        <header className="wf-drawer-head">
          <div>
            <span className="wf-drawer-kicker">Configure workflow</span>
            <h3>{definition.name}</h3>
            <small>{definition.category || 'process'} · v{definition.version}</small>
          </div>
          <button type="button" className="wf-drawer-close" onClick={onClose} aria-label="Close">×</button>
        </header>

        {error ? <p className="wf-drawer-error">{error}</p> : null}

        {loading ? (
          <div className="wf-drawer-body"><p className="wf-drawer-muted">Loading…</p></div>
        ) : (
          <div className="wf-drawer-body">
            {/* Brand: inherited from /settings/brand. Show what will be used. */}
            <section className="wf-drawer-section wf-drawer-brand-row">
              <header className="wf-drawer-section-head">
                <h4>Brand</h4>
                <a href="/settings/brand" target="_blank" rel="noreferrer" className="wf-drawer-link">Edit at /settings/brand ↗</a>
              </header>
              <p className="wf-drawer-muted">
                Logo, palette, fonts, and voice inherit from the global brand. You can override the
                sender name + accent below, but everything else flows through.
              </p>
              <div className="wf-brand-chips">
                <div className="wf-brand-chip">
                  <span>Sender</span>
                  <strong>{resolvedBrand?.company_name || resolvedBrand?.sender_name || '—'}</strong>
                </div>
                <div className="wf-brand-chip">
                  <span>Accent</span>
                  <strong style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
                    <i className="wf-brand-swatch" style={{ background: resolvedBrand?.accent_hex || '#c2452a' }} />
                    {resolvedBrand?.accent_hex || '#c2452a'}
                  </strong>
                </div>
                <div className="wf-brand-chip">
                  <span>Fonts</span>
                  <strong>{(resolvedBrand?.fonts || []).slice(0, 2).join(' · ') || '—'}</strong>
                </div>
              </div>
            </section>

            {/* 1. Project */}
            <section className="wf-drawer-section">
              <header className="wf-drawer-section-head"><h4>1 · Project</h4></header>
              <label className="wf-field">
                <span>Project</span>
                <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
                  {projects.map((p) => <option key={p.id} value={p.id}>{p.name || p.slug || p.id}</option>)}
                </select>
              </label>
              <label className="wf-checkbox">
                <input type="checkbox" checked={defaultForProject} onChange={(e) => setDefaultForProject(e.target.checked)} />
                <span>Default process for this project</span>
              </label>
              <button type="button" className="wf-btn" disabled={savingSection === 'project'} onClick={() => saveSection({ default_for_project: defaultForProject }, 'project')}>
                {savingSection === 'project' ? 'Saving…' : 'Save'}
              </button>
            </section>

            {/* 2. Presentation */}
            <section className="wf-drawer-section">
              <header className="wf-drawer-section-head"><h4>2 · Presentation</h4></header>
              <p className="wf-drawer-muted">
                Workflow-specific copy and artwork. The intake form's wrapping inherits from your brand;
                these fields only override the surface details unique to this workflow.
              </p>
              <label className="wf-field">
                <span>Cover image URL <em className="wf-optional">optional</em></span>
                <input type="url" value={presentation.cover_image_url} onChange={(e) => setPresentation({ ...presentation, cover_image_url: e.target.value })} placeholder="https://…/cover.jpg" />
              </label>
              <label className="wf-field">
                <span>Cover title</span>
                <input type="text" value={presentation.cover_copy.title} onChange={(e) => setPresentation({ ...presentation, cover_copy: { ...presentation.cover_copy, title: e.target.value } })} placeholder={`${definition.name} — Intake`} />
              </label>
              <label className="wf-field">
                <span>Cover subtitle</span>
                <input type="text" value={presentation.cover_copy.subtitle} onChange={(e) => setPresentation({ ...presentation, cover_copy: { ...presentation.cover_copy, subtitle: e.target.value } })} placeholder="Submit the details below to start." />
              </label>
              <details className="wf-advanced">
                <summary>Override sender name / accent (optional)</summary>
                <label className="wf-field">
                  <span>Sender name override <em className="wf-optional">defaults to {resolvedBrand?.company_name || 'brand'}</em></span>
                  <input type="text" value={presentation.sender_name} onChange={(e) => setPresentation({ ...presentation, sender_name: e.target.value })} placeholder={resolvedBrand?.company_name || ''} />
                </label>
                <label className="wf-field">
                  <span>Accent override <em className="wf-optional">defaults to {resolvedBrand?.accent_hex || '#c2452a'}</em></span>
                  <div className="wf-accent-row">
                    <input type="color" value={presentation.accent_hex || resolvedBrand?.accent_hex || '#c2452a'} onChange={(e) => setPresentation({ ...presentation, accent_hex: e.target.value })} />
                    <input type="text" value={presentation.accent_hex} onChange={(e) => setPresentation({ ...presentation, accent_hex: e.target.value })} placeholder="leave empty to use brand" />
                  </div>
                </label>
                <label className="wf-field">
                  <span>Logo URL override <em className="wf-optional">defaults to brand logo</em></span>
                  <input type="url" value={presentation.logo_url} onChange={(e) => setPresentation({ ...presentation, logo_url: e.target.value })} placeholder="https://…/logo.svg" />
                </label>
              </details>

              <div className="wf-preview">
                <small>Live preview</small>
                <iframe title="Brand preview" srcDoc={previewSrcDoc} sandbox="allow-same-origin" />
              </div>

              <button type="button" className="wf-btn" disabled={savingSection === 'presentation'} onClick={() => saveSection({ brand: presentation }, 'presentation')}>
                {savingSection === 'presentation' ? 'Saving…' : 'Save presentation'}
              </button>
            </section>

            {/* 3. Agents */}
            <section className="wf-drawer-section">
              <header className="wf-drawer-section-head"><h4>3 · Agents</h4></header>
              <p className="wf-drawer-muted">
                Per-stage agent template overrides. JSON map: <code>{`{ stage_slug: { agent_template_slug, prompt_override } }`}</code>.
              </p>
              <textarea rows={6} className="wf-code" value={agentDraft} onChange={(e) => setAgentDraft(e.target.value)} />
              <button type="button" className="wf-btn" disabled={savingSection === 'agents'} onClick={() => {
                try { saveSection({ agent_overrides: JSON.parse(agentDraft) }, 'agents'); }
                catch (err) { setError(`agents: invalid JSON — ${err.message}`); }
              }}>
                {savingSection === 'agents' ? 'Saving…' : 'Save agent overrides'}
              </button>
            </section>

            {/* 4. Auto-approval */}
            <section className="wf-drawer-section">
              <header className="wf-drawer-section-head"><h4>4 · Auto-approval</h4></header>
              <p className="wf-drawer-muted">
                Declarative rules (same dialect as <code>policy_gate</code>). Array of <code>{`{ when, decision }`}</code> entries.
              </p>
              <textarea rows={5} className="wf-code" value={autoApproveDraft} onChange={(e) => setAutoApproveDraft(e.target.value)} />
              <button type="button" className="wf-btn" disabled={savingSection === 'autoapprove'} onClick={() => {
                try { saveSection({ auto_approve_rules: JSON.parse(autoApproveDraft) }, 'autoapprove'); }
                catch (err) { setError(`auto-approve: invalid JSON — ${err.message}`); }
              }}>
                {savingSection === 'autoapprove' ? 'Saving…' : 'Save auto-approval'}
              </button>
            </section>

            {/* 5. Sharing */}
            <section className="wf-drawer-section">
              <header className="wf-drawer-section-head"><h4>5 · Sharing</h4></header>
              <label className="wf-checkbox">
                <input type="checkbox" checked={shareEnabled} onChange={(e) => setShareEnabled(e.target.checked)} />
                <span>Allow share-link submissions</span>
              </label>
              <label className="wf-field">
                <span>Default link expiry (days)</span>
                <input type="number" min={1} max={90} value={shareExpiry} onChange={(e) => setShareExpiry(Number(e.target.value))} />
              </label>
              <button type="button" className="wf-btn" disabled={savingSection === 'sharing'} onClick={() => saveSection({ share_link_enabled: shareEnabled, share_link_default_expiry_days: shareExpiry }, 'sharing')}>
                {savingSection === 'sharing' ? 'Saving…' : 'Save sharing'}
              </button>
            </section>
          </div>
        )}
      </aside>
    </div>
  );
}

function escapeForHtml(s) {
  return String(s || '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
