/* global React, Icon, resetEmbeddedBuilderDraft, loadEmbeddedTemplateForEdit, getEmbeddedPositionLabel, capitalizeEmbedded, useSelectedWorkspaceId, getWorkspaceSearchParams */
const {
  useEffect: useEffectTemplates,
  useState: useStateTemplates,
} = React;

function TemplatesPage() {
  const workspaceId = useSelectedWorkspaceId();
  const [templates, setTemplates] = useStateTemplates([]);
  const [loading, setLoading] = useStateTemplates(true);
  const [error, setError] = useStateTemplates('');
  const [copiedBotId, setCopiedBotId] = useStateTemplates('');
  const [deletingBotId, setDeletingBotId] = useStateTemplates('');
  const [activatingBotId, setActivatingBotId] = useStateTemplates('');
  const [expandedBotId, setExpandedBotId] = useStateTemplates('');
  const [pendingDelete, setPendingDelete] = useStateTemplates(null);

  const templateTitle = template => (template && ((template.settings && template.settings.botName) || template.botName || template.templateName)) || 'this template';

  const loadTemplates = (silent = false) => {
    if (!silent) setLoading(true);
    setError('');

    fetch(`/api/embedded-bots${getWorkspaceSearchParams(workspaceId)}`, {
      credentials: 'include',
      cache: 'no-store',
    })
      .then(async response => {
        if (response.status === 401) {
          window.location.href = (['localhost','127.0.0.1'].includes(location.hostname)?'http://localhost:8788':'https://pluginchatbot.com')+'/login.html?redirect=' + encodeURIComponent(window.location.href);
          return null;
        }

        const data = await response.json();

        if (!response.ok || !data.ok) {
          throw new Error(data.error || 'Unable to load templates.');
        }

        return data;
      })
      .then(data => {
        if (!data) return;
        setTemplates(Array.isArray(data.bots) ? data.bots : []);
      })
      .catch(fetchError => {
        setError(fetchError.message || 'Unable to load templates.');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffectTemplates(() => {
    loadTemplates();
    const reload = () => loadTemplates(true);
    window.addEventListener('pluginchatbot:bot-status-changed', reload);
    return () => {
      window.removeEventListener('pluginchatbot:bot-status-changed', reload);
    };
  }, [workspaceId]);

  const startNewTemplate = () => {
    resetEmbeddedBuilderDraft();
    window.location.href = '/ai-builder';
  };

  const editTemplate = template => {
    loadEmbeddedTemplateForEdit(template);
    window.location.href = '/ai-builder';
  };

  const copyTemplateCode = template => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(template.embedCode || '').then(() => {
        setCopiedBotId(template.botId);
      }).catch(() => {
        setCopiedBotId('');
      });
    }
  };

  const manageKnowledgeBase = template => {
    window.location.href = `/ai-builder?botId=${encodeURIComponent(template.botId)}#ai-builder-knowledge-base`;
  };

  const activateTemplate = async template => {
    if (template.isActive) return;

    setActivatingBotId(template.botId);
    setError('');

    try {
      const response = await fetch(`/api/embedded-bots/${encodeURIComponent(template.botId)}/activate`, {
        method: 'POST',
        credentials: 'include',
      });

      const data = await response.json();

      if (!response.ok || !data.ok) {
        throw new Error(data.error || 'Unable to set the active template.');
      }

      setTemplates(prev => prev.map(item => ({
        ...item,
        isActive: item.botId === template.botId,
      })));
      window.dispatchEvent(new CustomEvent('pluginchatbot:bot-status-changed', {
        detail: { workspaceId },
      }));
    } catch (activateError) {
      setError(activateError.message || 'Unable to set the active template.');
    } finally {
      setActivatingBotId('');
    }
  };

  const deleteTemplate = async template => {
    setPendingDelete(null);

    setDeletingBotId(template.botId);
    setError('');

    try {
      const response = await fetch(`/api/embedded-bots/${encodeURIComponent(template.botId)}`, {
        method: 'DELETE',
        credentials: 'include',
      });

      const data = await response.json();

      if (!response.ok || !data.ok) {
        throw new Error(data.error || 'Unable to delete template.');
      }

      setTemplates(prev => prev.filter(item => item.botId !== template.botId));
      window.dispatchEvent(new CustomEvent('pluginchatbot:bot-status-changed', {
        detail: { workspaceId },
      }));
    } catch (deleteError) {
      setError(deleteError.message || 'Unable to delete template.');
    } finally {
      setDeletingBotId('');
    }
  };

  return (
    <div className="view">
      {pendingDelete && (
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby="pc-del-title"
          onClick={() => setPendingDelete(null)}
          style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(16,24,40,.55)', padding: '20px' }}
        >
          <div onClick={event => event.stopPropagation()} style={{ width: 'min(420px, 100%)', background: '#fff', borderRadius: '16px', padding: '24px', boxShadow: '0 24px 60px rgba(16,24,40,.28)' }}>
            <div style={{ width: '44px', height: '44px', borderRadius: '50%', background: '#fef3f2', display: 'grid', placeItems: 'center', color: '#d92d20', marginBottom: '16px' }}>
              <Icon name="alertTriangle" size={20} />
            </div>
            <h2 id="pc-del-title" style={{ margin: '0 0 8px', fontSize: '18px', color: '#101828' }}>Delete this template?</h2>
            <p style={{ margin: '0 0 22px', color: '#475467', fontSize: '14px', lineHeight: 1.5 }}>
              &ldquo;{templateTitle(pendingDelete)}&rdquo; will be removed from your dashboard. This can&rsquo;t be undone.
            </p>
            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
              <button type="button" className="btn btn-secondary btn-sm" onClick={() => setPendingDelete(null)}>Cancel</button>
              <button type="button" className="btn btn-primary btn-sm app-danger-button" onClick={() => deleteTemplate(pendingDelete)}>Delete template</button>
            </div>
          </div>
        </div>
      )}
      <div className="view-head">
        <div>
          <h1>Templates</h1>
          <div className="sub">Manage your saved chatbot templates, Knowledge Bases, and embed codes for each website</div>
        </div>
        <button className="btn btn-primary" type="button" onClick={startNewTemplate}>
          <Icon name="plus" size={13}/>Build another template
        </button>
      </div>

      {error && (
        <div className="embedded-api-feedback is-error app-page-feedback">
          <strong>Something went wrong</strong>
          <span>{error}</span>
        </div>
      )}

      {loading ? (
        <div className="card app-empty-state">Loading templates…</div>
      ) : templates.length === 0 ? (
        <div className="card app-empty-state">
          <div className="app-empty-icon"><Icon name="code" size={22}/></div>
          <h2>No chatbot templates yet</h2>
          <p>Customize your widget, complete bot setup, and generate your first embed code from AI Builder.</p>
          <div className="app-empty-actions">
            <button className="btn btn-primary" type="button" onClick={startNewTemplate}>Start setup</button>
            <a className="btn btn-secondary" href="/ai-builder">Go to AI Builder</a>
          </div>
        </div>
      ) : (
        <div className="app-template-grid">
          <button className="card app-template-create" type="button" onClick={startNewTemplate}>
            <span><Icon name="plus" size={26}/></span>
            <strong>Build another template</strong>
            <small>Create separate settings and embed code for a different website.</small>
          </button>

          {templates.map(template => (
            <TemplateCard
              key={template.botId}
              template={template}
              copied={copiedBotId === template.botId}
              deleting={deletingBotId === template.botId}
              activating={activatingBotId === template.botId}
              onCopy={() => copyTemplateCode(template)}
              onEdit={() => editTemplate(template)}
              onKnowledge={() => manageKnowledgeBase(template)}
              onDelete={() => setPendingDelete(template)}
              onActivate={() => activateTemplate(template)}
              expanded={expandedBotId === template.botId}
              onToggleDetails={() => setExpandedBotId(current => current === template.botId ? '' : template.botId)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function TemplateCard({ template, copied, deleting, activating, onCopy, onEdit, onKnowledge, onDelete, onActivate, expanded, onToggleDetails }) {
  const settings = template.settings || {};
  const domains = String(settings.allowedDomains || '')
    .split(',')
    .map(item => item.trim())
    .filter(Boolean);

  return (
    <article className={`card app-template-card ${expanded ? 'is-expanded' : ''}`}>
      <div className="app-template-head">
        <div className="app-template-title-wrap">
          <span className="app-template-icon"><Icon name="fileCode" size={20}/></span>
          <div>
            <h2>{(template.settings && template.settings.botName) || template.botName || template.templateName}</h2>
            <span>{template.botId}</span>
          </div>
        </div>
        {template.isActive
          ? <span className="pill success">Active</span>
          : <span className="pill">Saved</span>}
      </div>

      <div className="app-template-quick-grid">
        <OverviewItem label="Bot" value={settings.botName || template.botName || 'PluginChatBot Assistant'} />
        <OverviewItem label="Model" value={settings.model || 'No model selected'} />
        <OverviewItem label="Domains" value={domains.length ? `${domains.length} configured` : 'No domains'} />
      </div>

      <button className="app-template-detail-toggle" type="button" onClick={onToggleDetails} aria-expanded={expanded}>
        <span>{expanded ? 'Hide template details' : 'View template details'}</span>
        <Icon name={expanded ? 'chevronUp' : 'chevronDown'} size={17}/>
      </button>

      <div className="app-template-details" hidden={!expanded}>
        <div className="app-template-overview">
          <OverviewItem label="Bot" value={settings.botName || template.botName || 'PluginChatBot Assistant'} />
          <OverviewItem label="Model" value={settings.model || 'No model selected'} />
          <OverviewItem label="Position" value={getEmbeddedPositionLabel(settings.position)} />
          <OverviewItem label="Voice" value={settings.enableTts ? capitalizeEmbedded(settings.voice || 'cedar') : 'Off'} />
          <OverviewItem label="Capture" value={settings.visitorCaptureEnabled ? 'On' : 'Off'} />
          <OverviewItem label="Domains" value={domains.length ? domains.join(', ') : 'No domains'} />
        </div>

        <div className="embedded-code-box app-template-code">
          <pre>{template.embedCode}</pre>
        </div>
      </div>

      <div className="app-template-actions">
        {template.isActive
          ? <button className="btn btn-secondary btn-sm" type="button" disabled>Active</button>
          : <button className="btn btn-secondary btn-sm" type="button" onClick={onActivate} disabled={activating}>{activating ? 'Activating…' : 'Set as Active'}</button>}
        <button className="btn btn-primary btn-sm" type="button" onClick={onCopy}>{copied ? 'Copied' : 'Copy code'}</button>
        <button className="btn btn-secondary btn-sm" type="button" onClick={onKnowledge}>Knowledge Base</button>
        <button className="btn btn-secondary btn-sm" type="button" onClick={onEdit}>Edit</button>
        <button className="btn btn-secondary btn-sm app-danger-button" type="button" onClick={onDelete} disabled={deleting}>
          {deleting ? 'Deleting...' : 'Delete'}
        </button>
      </div>
    </article>
  );
}

function OverviewItem({ label, value }) {
  return (
    <div>
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}

window.TemplatesPage = TemplatesPage;
