// T2 Falcon Admin — Templates: Details page (3 states)

const { useState: useStateD } = React;

// Build the maker–checker action history from the template's OWN checker data
// (tpl.checker1 / tpl.checker2) so it can never contradict the Status pill — e.g. a
// "Rejected" template must never show two "Approved" rows. Rules:
//   • A checker that has acted (real name + non-pending status) renders its decision,
//     dated with the template's creation date/time and an optional rejection reason.
//   • A checker that is unassigned ("---") or still pending renders as a Pending row.
//   • Level 2 is omitted when Level 1 rejected and there is no second reviewer — the
//     review stopped there, so there is no Level 2 record to show.
const TPL_HIST_ACTION = { approved: 'Approved', rejected: 'Rejected', pending: 'Pending' };
const buildTplActionHistory = (tpl) => {
  const acted = (c) => c && c.name && c.name !== '---' && c.status && c.status !== 'pending';
  const mkRow = (level, c) => acted(c)
    ? { level, name: c.name, date: tplFmtDate(tpl.creationDate) || '---',
        time: (tpl.creationTime || '').toUpperCase(),
        reason: c.reason || (c.status === 'rejected' ? '—' : '---'),
        action: TPL_HIST_ACTION[c.status] || c.status }
    // Pending / not-yet-reviewed level → "---" everywhere, with a "Pending" sub-label
    // shown beneath the checker dash (see TplActionHistory).
    : { level, name: '---', date: '---', time: '', reason: '---', action: '---', pending: true };
  const rows = [mkRow('Level 1', tpl.checker1)];
  const c1Rejected = tpl.checker1 && tpl.checker1.status === 'rejected';
  if (!(c1Rejected && tpl.checker2 == null)) rows.push(mkRow('Level 2', tpl.checker2));
  return rows;
};

const tplFmtAction = (a) => {
  const v = a.action || a.status || '';
  if (v === '---' || v === '') return <span className="tpl-history-na">---</span>;
  const k = v.toLowerCase();
  return <span className={`tpl-history-action ${k}`}>{v}</span>;
};

// Reusable maker–checker "Action history" card — derived from the template's own
// checker data (buildTplActionHistory). Used by the More-Details page AND the IVR
// Edit / Share screens so all three show the exact same table.
const TplActionHistory = ({ tpl, t }) => {
  if (!tpl) return null;
  const history = buildTplActionHistory(tpl);
  return (
    <div className="tpl-details-card">
      <div className="hd">{t.actionHistory}</div>
      <table className="tpl-history-table">
        <thead>
          <tr>
            <th>{t.levelLbl}</th>
            <th>{t.checkerName}</th>
            <th>{t.dateTimeLbl}</th>
            <th>{t.reasonLbl}</th>
            <th>{t.actionLbl}</th>
          </tr>
        </thead>
        <tbody>
          {history.map((row, i) => (
            <tr key={i}>
              <td>{row.level}</td>
              <td>{row.name}{row.pending && <span className="tpl-history-sub">{t.tplStatusPending || 'Pending'}</span>}</td>
              <td>{row.date}{row.time ? ' • ' + row.time : ''}</td>
              <td>{row.reason}</td>
              <td>{tplFmtAction(row)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const TplDetailsPage = ({ tpl, scopeNode, onBack, onApprove, onReject, t, lang, pushToast, readOnly = false, shareMode = false, sharedIds = [], onSharedChange, onShareSave, onShareCancel, reviewMode = false }) => {
  if (!tpl) return null;
  const ShareMulti = window.TplShareMulti;
  const isPending = tpl.status === 'pending';
  const isRejected = tpl.status === 'rejected';
  const isApproved = tpl.status === 'approved';
  const isIvr = tpl.channel === 'IVR Voice' || tpl.channel === 'Voice';   // Voice / IVR Voice templates hide WABA Account (N/A) + Language
  const [decisionMode, setDecisionMode] = useStateD(null); // null | 'approve' | 'reject'
  const [reason, setReason] = useStateD('');

  // Open the details view scrolled to the TOP — start at "Template Details" rather than
  // wherever the list/page was scrolled (matters most for IVR, whose inline flow canvas
  // makes the page tall).
  const wrapRef = React.useRef(null);
  React.useLayoutEffect(() => {
    let p = wrapRef.current && wrapRef.current.parentElement;
    while (p) {
      const cs = getComputedStyle(p);
      if (/(auto|scroll)/.test(cs.overflowY) && p.scrollHeight > p.clientHeight + 1) p.scrollTop = 0;
      p = p.parentElement;
    }
    if (window.scrollTo) window.scrollTo(0, 0);
  }, [tpl.id]);

  // Local copy of the IVR flow so the user can click a node and view/tweak its values in
  // the side panel (preview only — not persisted to the real template); reset per template.
  const [ivrPreview, setIvrPreview] = useStateD(null);
  React.useEffect(() => { setIvrPreview(null); }, [tpl.id]);

  const metaHistory = isApproved && tpl.statusByMeta !== 'NA' && tpl.statusByMeta !== '---'
                    ? window.actionHistoryByMetaApproved
                    : (tpl.metaRejected ? window.actionHistoryByMeta : null);

  const fmtAction = (a) => {
    const k = (a.action || a.status || '').toLowerCase();
    return <span className={`tpl-history-action ${k}`}>{a.action || a.status}</span>;
  };

  return (
    <div className="td-wrap" ref={wrapRef}>
      {/* Top bar — same pattern as User Profile (.ud-top-bar):
          Left  = client logo + name (Falcon root suppressed per earlier request).
          Right = Back button styled like "Back to User list". */}
      <div className="td-top-bar">
        <div className="td-top-left">
          {scopeNode && scopeNode.type === 'client' && (
            <>
              <BrandLogo brand={scopeNode.brand} size={32} />
              <span className="td-top-name">{scopeNode.name}</span>
            </>
          )}
          {scopeNode && scopeNode.type !== 'client' && scopeNode.type !== 'root' && scopeNode.id !== 'falcon' && (
            <>
              <span className="node-avatar" style={{ background: '#0d3f44', color: 'white' }}>
                <span style={{ fontSize: 12, fontWeight: 700 }}>{(scopeNode.name || 'N').slice(0, 1)}</span>
              </span>
              <span className="td-top-name">{scopeNode.name}</span>
            </>
          )}
        </div>
        <div className="td-top-actions">
          {shareMode ? (
            <>
              <button className="btn btn-secondary" onClick={onShareCancel}>{t.cancel || 'Cancel'}</button>
              <button className="btn btn-primary" onClick={onShareSave}>{t.save || 'Save'}</button>
            </>
          ) : (
            <button className="btn btn-secondary" onClick={onBack}>
              <IcArrowLeft size={14} stroke={1.8} className="flip-rtl" />
              {t.tplBackToTemplates || 'Back to Templates'}
            </button>
          )}
        </div>
      </div>

      {shareMode && (
        <div className="tpl-share-note">
          <span>{t.shareNote || 'All fields are read-only. Only "Shared With" can be changed below.'}</span>
        </div>
      )}

      {/* Top info card */}
      <div className="tpl-details-card">
        <div className="hd">{t.templateDetails}</div>
        <div className="tpl-details-grid">
          <div className="tpl-d-field"><span className="lab">{t.detailTemplateName}</span><span className="val">{tpl.name}</span></div>
          <div className="tpl-d-field"><span className="lab">{t.detailTemplateId}</span><span className="val">{tpl.id}</span></div>
          <div className="tpl-d-field"><span className="lab">{t.detailReferenceId}</span><span className="val">{tpl.referenceId}</span></div>
          {!isIvr && <div className="tpl-d-field"><span className="lab">{t.detailWabaAccount}</span><span className="val">{tpl.wabaAccount || '—'}</span></div>}
          {!isIvr && <div className="tpl-d-field"><span className="lab">{t.detailLanguage}</span><span className="val">{tpl.language}</span></div>}
          <div className="tpl-d-field"><span className="lab">{t.detailCreatedBy}</span><span className="val">{tpl.createdBy}</span></div>
          <div className="tpl-d-field"><span className="lab">{t.detailCreationDate}</span><span className="val">{tplFmtDate(tpl.creationDate)} • {tpl.creationTime}</span></div>
          <div className="tpl-d-field"><span className="lab">{t.detailCommchannelType}</span><span className="val">{tpl.channel}</span></div>
          <div className="tpl-d-field"><span className="lab">{t.detailServicesType}</span><span className="val">{tpl.serviceType}</span></div>
          {!isIvr && <div className="tpl-d-field"><span className="lab">{t.detailSubCategory}</span><span className="val">{tpl.subCategory}</span></div>}
          <div className="tpl-d-field"><span className="lab">{t.detailStatus}</span><div className="pill-row"><TplStatusPill status={tpl.status} t={t} /></div></div>
          <div className={`tpl-d-field ${shareMode ? 'tpl-d-share-edit' : 'full'}`}>
            <span className="lab">{t.detailSharedWith}{shareMode && <span className="opt"> ({t.multipleSelect || 'Multiple Select'})</span>}</span>
            {shareMode && ShareMulti
              ? <ShareMulti value={sharedIds} onChange={onSharedChange} t={t} />
              : <div className="pill-row">{(tpl.sharedWith || []).map((n, i) => <span key={i} className="tpl-shared-pill no-extra">{n}</span>)}</div>}
          </div>
        </div>
      </div>

      {/* Pending: Review decision card — only from the Pending Review tab (not the
          Templates/Shared tabs), and never in read-only / Falcon / Share view. */}
      {isPending && !readOnly && !shareMode && reviewMode && (
        <div className="tpl-decision-card">
          <div className="tpl-decision-head">
            <span className="ttl">{t.reviewDecision}</span>
            <div className="acts">
              <button className={`btn-approve ${decisionMode === 'approve' ? '' : 'outline'}`} onClick={() => setDecisionMode('approve')}>
                <IcCheck size={12} stroke={3} /> {t.decisionApproved}
              </button>
              <button className={`btn-reject ${decisionMode === 'reject' ? '' : 'outline'}`} onClick={() => setDecisionMode('reject')}>
                <IcClose size={12} stroke={2.5} /> {t.decisionReject}
              </button>
            </div>
          </div>
          {decisionMode === 'reject' && (
            <div>
              <label className="tpl-field-label" style={{ display: 'block', marginBottom: 4 }}>{t.decisionReason}</label>
              <textarea className="tpl-field-textarea" placeholder={t.decisionReason} value={reason} onChange={(e) => setReason(e.target.value)}></textarea>
            </div>
          )}
          <div className="tpl-decision-foot">
            <button className="cancel" onClick={() => { setDecisionMode(null); setReason(''); }}>{t.cancelDecision}</button>
            <button
              className={`save ${decisionMode ? 'active' : ''}`}
              onClick={() => {
                if (!decisionMode) return;
                if (decisionMode === 'approve') { onApprove(tpl); pushToast(t.toastTplApproved); }
                else { onReject(tpl, reason); pushToast(t.toastTplRejected); }
              }}
            >{t.saveDecision}</button>
          </div>
        </div>
      )}

      {/* Action history (maker–checker) — shared with the IVR Edit / Share screens */}
      <TplActionHistory tpl={tpl} t={t} />

      {/* Action history by meta (only when relevant) */}
      {metaHistory && (
        <div className="tpl-details-card">
          <div className="hd">{t.actionHistoryByMeta}</div>
          <table className="tpl-history-table">
            <thead>
              <tr>
                <th>{t.dateTimeSent}</th>
                <th>{t.detailStatus}</th>
                <th>{t.reasonLbl}</th>
              </tr>
            </thead>
            <tbody>
              {metaHistory.map((row, i) => (
                <tr key={i}>
                  <td>{tplFmtDate(row.date)}{row.time ? ' • ' + row.time : ''}</td>
                  <td>{fmtAction(row)}</td>
                  <td>{row.reason && row.reason.startsWith('meta') ? t[row.reason] : row.reason}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* IVR Voice templates: the flow canvas shown full-width inline (read-only) —
          the same canvas/layout as the IVR Edit screen, instead of a cramped side rail. */}
      {isIvr && tpl.ivr && window.TplIvrStep2 && (
        <div className="ivr-edit-canvas is-readonly td-ivr-flow">
          {/* More Details, Share and Pending-review all show the read-only tree; clicking a node
              opens ONLY the "Edit variable" panel (no node/tree editing). */}
          <window.TplIvrStep2 data={ivrPreview || tpl} setData={setIvrPreview} t={t} readOnly={true} inspect={true} />
        </div>
      )}
    </div>
  );
};

Object.assign(window, { TplDetailsPage, TplActionHistory });
