// Helper321 Admin — Coupons / promo code CRUD
// Mirrors Stripe Coupon — `kind` matches Stripe's percent_off vs amount_off,
// `duration` matches Stripe's "once" / "forever" / "repeating" pattern.
// Real impl backs onto:
//   GET    /v1/admin/coupons
//   POST   /v1/admin/coupons        (creates both our row + the Stripe coupon)
//   PATCH  /v1/admin/coupons/{id}   (active flag only — Stripe coupons are
//                                    largely immutable; price/duration can't change)
//   DELETE /v1/admin/coupons/{id}   (also voids in Stripe via stripe.coupons.del)
// Until backend ships, mock-only — edits live in component state and persist
// onto ADMIN.coupons so the page survives tab switches in the same session.

const CouponsPageReal = () => {
  const toast = useToast();
  const [coupons, setCoupons] = uS(() => (ADMIN.coupons || []).map(c => ({ ...c })));
  const [q, setQ] = uS('');
  const [statusFilter, setStatusFilter] = uS('ALL');     // ALL | ACTIVE | EXPIRED | INACTIVE
  const [openId, setOpenId] = uS(null);
  const [showNew, setShowNew] = uS(false);

  const now = ADMIN.now;
  const isExpired = (c) => c.redeemBy && new Date(c.redeemBy) < now;
  const isCapped = (c) => c.maxRedemptions && c.timesRedeemed >= c.maxRedemptions;
  const effectiveStatus = (c) => {
    if (!c.active) return 'INACTIVE';
    if (isExpired(c)) return 'EXPIRED';
    if (isCapped(c)) return 'EXPIRED';
    return 'ACTIVE';
  };

  const filtered = uM(() => {
    let list = coupons;
    if (statusFilter !== 'ALL') list = list.filter(c => effectiveStatus(c) === statusFilter);
    if (q) {
      const qL = q.toLowerCase();
      list = list.filter(c =>
        c.code.toLowerCase().includes(qL) ||
        c.id.toLowerCase().includes(qL) ||
        (c.note || '').toLowerCase().includes(qL)
      );
    }
    return [...list].sort((a,b) => new Date(b.createdAt) - new Date(a.createdAt));
  }, [coupons, statusFilter, q]);

  const kpi = uM(() => {
    const active = coupons.filter(c => effectiveStatus(c) === 'ACTIVE').length;
    const totalRedemptions = coupons.reduce((s, c) => s + (c.timesRedeemed || 0), 0);
    const expiringSoon = coupons.filter(c =>
      c.active && c.redeemBy && (() => {
        const days = (new Date(c.redeemBy) - now) / 86400000;
        return days >= 0 && days <= 7;
      })()
    ).length;
    return { active, totalRedemptions, expiringSoon };
  }, [coupons]);

  const upsertCoupon = (data) => {
    setCoupons(xs => {
      const idx = xs.findIndex(c => c.id === data.id);
      const next = idx >= 0 ? xs.map(c => c.id === data.id ? { ...c, ...data } : c) : [{ ...data, timesRedeemed: 0, createdAt: new Date() }, ...xs];
      ADMIN.coupons = next.map(c => ({ ...c }));
      return next;
    });
    ADMIN.auditLogs.unshift({
      id: 'log_' + Math.random().toString(36).slice(2,8),
      at: new Date(), actor: 'Vincent Chen',
      action: data.id && coupons.some(c => c.id === data.id) ? 'COUPON_UPDATE' : 'COUPON_CREATE',
      targetType: 'Coupon', targetId: data.id, diff: {},
    });
  };

  const toggleActive = (id) => {
    setCoupons(xs => {
      const next = xs.map(c => c.id === id ? { ...c, active: !c.active } : c);
      ADMIN.coupons = next.map(c => ({ ...c }));
      return next;
    });
    const c = coupons.find(x => x.id === id);
    ADMIN.auditLogs.unshift({
      id: 'log_' + Math.random().toString(36).slice(2,8),
      at: new Date(), actor: 'Vincent Chen',
      action: c?.active ? 'COUPON_DEACTIVATE' : 'COUPON_ACTIVATE',
      targetType: 'Coupon', targetId: id, diff: {},
    });
    toast.push({ kind:'success', msg: c?.active ? '已停用 ' + c.code : '已啟用 ' + c.code });
  };

  const removeCoupon = (id) => {
    setCoupons(xs => {
      const next = xs.filter(c => c.id !== id);
      ADMIN.coupons = next.map(c => ({ ...c }));
      return next;
    });
    ADMIN.auditLogs.unshift({
      id: 'log_' + Math.random().toString(36).slice(2,8),
      at: new Date(), actor: 'Vincent Chen',
      action: 'COUPON_DELETE',
      targetType: 'Coupon', targetId: id, diff: {},
    });
    toast.push({ kind:'danger', msg:'已刪除折扣碼' });
  };

  const tabs = [
    { key: 'ALL',      label: '全部' },
    { key: 'ACTIVE',   label: '生效中' },
    { key: 'EXPIRED',  label: '已過期' },
    { key: 'INACTIVE', label: '已停用' },
  ];
  const tabCount = (k) => k === 'ALL' ? coupons.length : coupons.filter(c => effectiveStatus(c) === k).length;

  const openCoupon = coupons.find(c => c.id === openId);

  return (
    <div className="a-page">
      <div className="a-page-head">
        <div>
          <h1 className="a-page-title">折扣碼 / Coupons</h1>
          <div className="text-muted fs-13">
            建立並管理 Stripe Coupon — 對應 stripe.coupons.* API。停用後現有用戶不受影響，僅阻擋新領取。
          </div>
        </div>
        <div className="a-page-actions">
          <button className="a-btn a-btn-primary" onClick={() => setShowNew(true)}>
            <AIcon name="plus" size={13}/> 新增折扣碼
          </button>
        </div>
      </div>

      {/* KPIs */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginBottom:20}}>
        <KpiTileLocal label="生效中" value={kpi.active} icon="check"/>
        <KpiTileLocal label="累計兌換次數" value={kpi.totalRedemptions} icon="gift" mono/>
        <KpiTileLocal label="7 日內到期" value={kpi.expiringSoon} icon="clock" tone={kpi.expiringSoon > 0 ? 'warn' : 'neutral'}/>
      </div>

      {/* Tabs */}
      <div className="a-tabs" style={{marginBottom:14}}>
        {tabs.map(t => (
          <div key={t.key} className={'a-tab ' + (statusFilter === t.key ? 'active' : '')} onClick={() => setStatusFilter(t.key)}>
            {t.label} {tabCount(t.key) > 0 && <span className="a-tab-count">{tabCount(t.key)}</span>}
          </div>
        ))}
      </div>

      {/* Search */}
      <div style={{display:'flex',gap:10,marginBottom:14}}>
        <input className="a-input" style={{flex:1,maxWidth:360}} placeholder="搜尋 code / id / 備註…"
               value={q} onChange={e => setQ(e.target.value)}/>
      </div>

      {/* Coupons table */}
      {filtered.length === 0 ? (
        <div className="a-card" style={{padding:60,textAlign:'center'}}>
          <AIcon name="gift" size={32} style={{color:'var(--a-ink-muted)',marginBottom:8}}/>
          <div style={{fontWeight:500,marginBottom:6}}>沒有符合的折扣碼</div>
          <div className="text-muted fs-13">調整篩選條件，或點「新增折扣碼」建立一個。</div>
        </div>
      ) : (
        <div className="a-card" style={{padding:0,overflow:'hidden'}}>
          <table className="a-table a-table-compact">
            <thead>
              <tr>
                <th style={{width:140}}>Code</th>
                <th style={{width:120}}>折扣</th>
                <th style={{width:120}}>持續期</th>
                <th style={{width:140}}>適用方案</th>
                <th style={{width:130}}>到期日</th>
                <th style={{width:120}}>兌換 / 上限</th>
                <th style={{width:90}}>狀態</th>
                <th style={{width:140,textAlign:'right'}}>動作</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(c => {
                const status = effectiveStatus(c);
                const statusBadge = {
                  ACTIVE:   { label:'生效中', kind:'success' },
                  EXPIRED:  { label:'已過期', kind:'neutral' },
                  INACTIVE: { label:'已停用', kind:'warn' },
                }[status];
                const discountLabel = c.kind === 'percent'
                  ? c.value + '% off'
                  : 'NT$' + Math.round(c.value/100) + ' off';
                const durationLabel = {
                  once:      '單次使用',
                  forever:   '永久',
                  repeating: '前 ' + c.durationMonths + ' 個月',
                }[c.duration] || c.duration;
                const appliesLabel = {
                  all:      '所有方案',
                  standard: '僅 Standard',
                  premium:  '僅 Premium',
                }[c.appliesTo] || c.appliesTo;
                return (
                  <tr key={c.id} className="clickable" onClick={() => setOpenId(c.id)}>
                    <td><Mono style={{fontWeight:600}}>{c.code}</Mono></td>
                    <td style={{fontWeight:600,color:'var(--a-primary)'}}>{discountLabel}</td>
                    <td className="fs-13">{durationLabel}</td>
                    <td className="fs-13">{appliesLabel}</td>
                    <td className="fs-13 text-muted">{c.redeemBy ? FMT.iso(c.redeemBy).slice(0,10) : '無'}</td>
                    <td className="a-table-num">
                      <Mono>{c.timesRedeemed}{c.maxRedemptions ? ' / ' + c.maxRedemptions : ''}</Mono>
                    </td>
                    <td><span className={'a-badge a-badge-' + statusBadge.kind}>{statusBadge.label}</span></td>
                    <td style={{textAlign:'right'}} onClick={e => e.stopPropagation()}>
                      <button className="a-btn a-btn-ghost a-btn-sm" style={{padding:'4px 8px'}}
                              onClick={() => { navigator.clipboard.writeText(c.code); toast.push({ kind:'success', msg:'已複製 ' + c.code }); }}
                              title="複製 code">
                        <AIcon name="copy" size={12}/>
                      </button>
                      <button className="a-btn a-btn-ghost a-btn-sm" style={{padding:'4px 8px'}}
                              onClick={() => toggleActive(c.id)}
                              title={c.active ? '停用' : '啟用'}>
                        <AIcon name={c.active ? 'eyeOff' : 'eye'} size={12}/>
                      </button>
                      <button className="a-btn a-btn-ghost a-btn-sm" style={{padding:'4px 8px',color:'var(--a-danger)'}}
                              onClick={() => { if (confirm('確定刪除折扣碼 ' + c.code + '？')) removeCoupon(c.id); }}
                              title="刪除">
                        <AIcon name="trash" size={12}/>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {openCoupon && <CouponDrawer coupon={openCoupon} onClose={() => setOpenId(null)} onSave={upsertCoupon} onToggle={toggleActive} onDelete={removeCoupon}/>}
      {showNew && <CouponEditModal coupon={null} onClose={() => setShowNew(false)} onSave={(d) => { upsertCoupon(d); setShowNew(false); toast.push({ kind:'success', msg:'已建立 ' + d.code }); }}/>}
    </div>
  );
};

const KpiTileLocal = ({ label, value, icon, tone = 'neutral', mono }) => (
  <div className="a-card" style={{padding:16}}>
    <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:6}}>
      <AIcon name={icon} size={14} style={{color: tone === 'warn' ? 'var(--a-warn)' : tone === 'danger' ? 'var(--a-danger)' : 'var(--a-ink-muted)'}}/>
      <span className="text-muted fs-11" style={{textTransform:'uppercase',letterSpacing:'0.06em'}}>{label}</span>
    </div>
    <div style={{fontSize:22,fontWeight:700,color: tone === 'danger' ? 'var(--a-danger)' : 'var(--a-ink)', fontVariantNumeric: mono ? 'tabular-nums' : 'normal'}}>
      {value}
    </div>
  </div>
);

// ============================================================
// COUPON — DRAWER (read + edit + delete)
// ============================================================
const CouponDrawer = ({ coupon, onClose, onSave, onToggle, onDelete }) => {
  const toast = useToast();
  const [showEdit, setShowEdit] = uS(false);
  const redemptionRate = coupon.maxRedemptions
    ? Math.round((coupon.timesRedeemed / coupon.maxRedemptions) * 100)
    : null;

  return (
    <ADrawer open onClose={onClose} size="lg" title={
      <span style={{display:'flex',alignItems:'center',gap:10}}>
        <AIcon name="gift" size={16}/>
        <Mono style={{fontWeight:600}}>{coupon.code}</Mono>
        <span className="text-muted fs-12"><Mono>{coupon.id}</Mono></span>
      </span>
    } footer={
      <>
        <button className="a-btn a-btn-danger" onClick={() => { if (confirm('確定刪除？')) { onDelete(coupon.id); onClose(); } }}>
          <AIcon name="trash" size={13}/> 刪除
        </button>
        <div style={{flex:1}}/>
        <button className="a-btn a-btn-default" onClick={() => onToggle(coupon.id)}>
          <AIcon name={coupon.active ? 'eyeOff' : 'eye'} size={13}/> {coupon.active ? '停用' : '啟用'}
        </button>
        <button className="a-btn a-btn-primary" onClick={() => setShowEdit(true)}>
          <AIcon name="edit" size={13}/> 編輯
        </button>
      </>
    }>
      <div className="a-card" style={{padding:18,marginBottom:14}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
          <CouponField label="折扣金額">
            <div style={{fontSize:22,fontWeight:700,color:'var(--a-primary)'}}>
              {coupon.kind === 'percent' ? coupon.value + '%' : 'NT$' + Math.round(coupon.value/100)}
              <span className="text-muted fs-12" style={{marginLeft:4,fontWeight:400}}>off</span>
            </div>
          </CouponField>
          <CouponField label="持續期">
            <div style={{fontWeight:600}}>
              {coupon.duration === 'once' ? '單次使用'
                : coupon.duration === 'forever' ? '永久'
                : '前 ' + coupon.durationMonths + ' 個月'}
            </div>
          </CouponField>
          <CouponField label="適用方案">
            <div style={{fontWeight:600}}>{coupon.appliesTo === 'all' ? '所有方案' : (coupon.appliesTo === 'standard' ? 'Standard' : 'Premium')}</div>
          </CouponField>
          <CouponField label="到期日">
            <div className="fs-13">{coupon.redeemBy ? FMT.iso(coupon.redeemBy).slice(0,10) : '無 — 永久有效'}</div>
          </CouponField>
        </div>
      </div>

      <div className="a-card" style={{padding:18,marginBottom:14}}>
        <h4 style={{fontSize:13,fontWeight:600,marginBottom:10}}>兌換情況</h4>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
          <div>
            <div className="text-muted fs-11" style={{textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:4}}>已兌換</div>
            <div style={{fontSize:18,fontWeight:700,fontVariantNumeric:'tabular-nums'}}>{coupon.timesRedeemed}</div>
          </div>
          <div>
            <div className="text-muted fs-11" style={{textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:4}}>上限</div>
            <div style={{fontSize:18,fontWeight:700,fontVariantNumeric:'tabular-nums'}}>{coupon.maxRedemptions || '無上限'}</div>
          </div>
        </div>
        {redemptionRate !== null && (
          <div style={{marginTop:12}}>
            <div className="a-progress" style={{height:6}}>
              <div className="a-progress-bar" style={{width: redemptionRate + '%', background: redemptionRate >= 80 ? 'var(--a-warn)' : 'var(--a-primary)'}}/>
            </div>
            <div className="text-muted fs-11" style={{marginTop:4}}>{redemptionRate}% 已使用</div>
          </div>
        )}
      </div>

      {coupon.note && (
        <div className="a-card" style={{padding:18,marginBottom:14}}>
          <h4 style={{fontSize:13,fontWeight:600,marginBottom:8}}>備註</h4>
          <div className="fs-13" style={{lineHeight:1.55,color:'var(--a-ink-soft)'}}>{coupon.note}</div>
        </div>
      )}

      <div className="text-muted fs-11" style={{padding:'10px 4px'}}>
        建立於 {FMT.iso(coupon.createdAt).slice(0,10)}
      </div>

      {showEdit && <CouponEditModal coupon={coupon} onClose={() => setShowEdit(false)} onSave={(d) => { onSave(d); setShowEdit(false); toast.push({ kind:'success', msg:'已更新 ' + d.code }); }}/>}
    </ADrawer>
  );
};

// ============================================================
// COUPON — EDIT / CREATE MODAL
// ============================================================
const CouponEditModal = ({ coupon, onClose, onSave }) => {
  const isNew = !coupon;
  const [form, setForm] = uS(() => coupon ? { ...coupon } : {
    id: 'cpn_' + Math.random().toString(36).slice(2, 8),
    code: '',
    kind: 'percent',
    value: 10,
    currency: null,
    duration: 'once',
    durationMonths: 3,
    redeemBy: null,
    maxRedemptions: null,
    appliesTo: 'all',
    note: '',
    active: true,
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const canSave = form.code.trim().length > 0 && form.value > 0;

  return (
    <AModal open onClose={onClose} title={isNew ? '新增折扣碼' : <>編輯 <Mono>{form.code}</Mono></>} footer={
      <>
        <button className="a-btn a-btn-default" onClick={onClose}>取消</button>
        <button className="a-btn a-btn-primary" disabled={!canSave}
                onClick={() => {
                  // For fixed-amount coupons, force the currency we operate in.
                  const next = { ...form, currency: form.kind === 'fixed' ? 'TWD' : null };
                  onSave(next);
                }}>
          <AIcon name="check" size={13}/> {isNew ? '建立' : '儲存'}
        </button>
      </>
    }>
      <CouponField label="Code (用戶輸入的折扣碼)">
        <input className="a-input" value={form.code} onChange={e => set('code', e.target.value.toUpperCase())}
               placeholder="例：WELCOME50" disabled={!isNew}
               style={{textTransform:'uppercase',fontFamily:'var(--a-mono)',letterSpacing:'0.04em'}}/>
        {!isNew && <div className="text-muted fs-11" style={{marginTop:4}}>code 建立後無法修改（與 Stripe 設計一致）</div>}
      </CouponField>

      <CouponField label="折扣類型">
        <div style={{display:'flex',gap:8}}>
          {[['percent','百分比 (%)'],['fixed','固定金額 (NT$)']].map(([v, l]) => (
            <button key={v} type="button"
                    className={'a-btn a-btn-sm ' + (form.kind === v ? 'a-btn-primary' : 'a-btn-default')}
                    onClick={() => set('kind', v)}>{l}</button>
          ))}
        </div>
      </CouponField>

      <CouponField label={form.kind === 'percent' ? '折扣百分比' : '折扣金額 (NT$)'}>
        <input className="a-input" type="number" value={form.kind === 'percent' ? form.value : Math.round(form.value/100)}
               onChange={e => set('value', form.kind === 'percent' ? Number(e.target.value) : Number(e.target.value) * 100)}
               min={1} max={form.kind === 'percent' ? 100 : undefined}/>
      </CouponField>

      <CouponField label="持續期">
        <div style={{display:'flex',gap:8,marginBottom:8}}>
          {[['once','單次'],['repeating','重複數月'],['forever','永久']].map(([v, l]) => (
            <button key={v} type="button"
                    className={'a-btn a-btn-sm ' + (form.duration === v ? 'a-btn-primary' : 'a-btn-default')}
                    onClick={() => set('duration', v)}>{l}</button>
          ))}
        </div>
        {form.duration === 'repeating' && (
          <input className="a-input" type="number" value={form.durationMonths}
                 onChange={e => set('durationMonths', Math.max(1, Number(e.target.value)))}
                 min={1} max={36} style={{width:120}}/>
        )}
      </CouponField>

      <CouponField label="適用方案">
        <select className="a-select" value={form.appliesTo} onChange={e => set('appliesTo', e.target.value)}>
          <option value="all">所有方案</option>
          <option value="standard">僅 Standard</option>
          <option value="premium">僅 Premium</option>
        </select>
      </CouponField>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
        <CouponField label="到期日（選填）">
          <input className="a-input" type="date"
                 value={form.redeemBy ? FMT.iso(form.redeemBy).slice(0,10) : ''}
                 onChange={e => set('redeemBy', e.target.value ? new Date(e.target.value) : null)}/>
        </CouponField>
        <CouponField label="兌換次數上限（選填）">
          <input className="a-input" type="number" value={form.maxRedemptions || ''}
                 onChange={e => set('maxRedemptions', e.target.value ? Number(e.target.value) : null)}
                 placeholder="無限制"/>
        </CouponField>
      </div>

      <CouponField label="內部備註（不會給用戶看）">
        <textarea className="a-input" rows={3} value={form.note}
                  onChange={e => set('note', e.target.value)}
                  placeholder="例：Q3 行銷活動 · 標準方案 25% off"/>
      </CouponField>
    </AModal>
  );
};

// Local Field — match shape of other admin modals so we don't depend on
// admin-subscriptions.jsx's internal Field component.
const CouponField = ({ label, children }) => (
  <div style={{marginBottom:12}}>
    <label className="text-muted fs-12" style={{display:'block',marginBottom:6}}>{label}</label>
    {children}
  </div>
);

const CouponsPage = () => <CouponsPageReal/>;

Object.assign(window, { CouponsPage, CouponsPageReal });
