/* global React, I, UI */
const { useState: useStateDBS, useEffect: useEffectDBS } = React;

const DBS_COLLECTIONS = [
  { key: 'Customers',        label: 'ลูกค้า' },
  { key: 'Vendors',          label: 'Vendor/ผู้ขาย' },
  { key: 'Products',         label: 'สินค้า' },
  { key: 'Quotations',       label: 'ใบเสนอราคา' },
  { key: 'Invoices',         label: 'Invoice' },
  { key: 'DeliveryNotes',    label: 'ใบส่งสินค้า' },
  { key: 'TaxInvoices',      label: 'ใบกำกับภาษี' },
  { key: 'BillingNotes',     label: 'ใบวางบิล' },
  { key: 'Receipts',         label: 'ใบเสร็จ' },
  { key: 'PurchaseOrders',   label: 'ใบสั่งซื้อ' },
  { key: 'Expenses',         label: 'ค่าใช้จ่าย' },
  { key: 'PaymentVouchers',  label: 'ใบสำคัญจ่าย' },
  { key: 'ReceiptVouchers',  label: 'ใบสำคัญรับ' },
  { key: 'Employees',        label: 'พนักงาน' },
  { key: 'PayrollRows',      label: 'เงินเดือน' },
  { key: 'TimeRecords',      label: 'เวลาทำงาน' },
  { key: 'QRClockRecords',   label: 'ลงเวลา QR' },
  { key: 'TimeRequests',     label: 'ขอแก้ไขเวลา' },
  { key: 'Projects',         label: 'โปรเจกต์' },
  { key: 'DailyTasks',       label: 'งานประจำวัน' },
  { key: 'TaxFilings',       label: 'ภาษี' },
  { key: 'CashAdvances',     label: 'เงินสดล่วงหน้า' },
  { key: 'Users',            label: 'ผู้ใช้' },
  { key: 'Roles',            label: 'บทบาท' },
  { key: 'WHTCertificates',  label: 'ใบรับรอง 50 ทวิ' },
  { key: 'Activity',         label: 'กิจกรรม' },
  { key: 'InventoryMoves',   label: 'เคลื่อนไหวสต็อก' },
];

const DBS_STATE_COLOR = {
  idle: '#22c55e', saving: '#f59e0b', loading: '#3b82f6', error: '#ef4444', offline: '#9ca3af',
};
const DBS_STATE_LABEL = {
  idle: 'เชื่อมต่อปกติ', saving: 'กำลังบันทึก…', loading: 'กำลังโหลด…', error: 'เกิดข้อผิดพลาด', offline: 'ออฟไลน์',
};
const DBS_LOG_COLOR = {
  ok: '#22c55e', error: '#ef4444', warn: '#f59e0b', load: '#3b82f6', save: '#f59e0b',
};

function fmtTime(d) {
  if (!d) return '—';
  return new Date(d).toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
function fmtDate(d) {
  if (!d) return '—';
  return new Date(d).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'medium' });
}

function DBStatusPage() {
  const snap = () => {
    const s = window.SSSDBStatus;
    if (!s) return { state: 'offline', lastSave: null, lastLoad: null, lastError: null, savedKeys: [], loadedCount: 0, log: [] };
    return { state: s.state, lastSave: s.lastSave, lastLoad: s.lastLoad, lastError: s.lastError, savedKeys: [...s.savedKeys], loadedCount: s.loadedCount, log: [...s.log] };
  };
  const [status, setStatus] = useStateDBS(snap);
  const [tick, setTick] = useStateDBS(0);

  useEffectDBS(() => {
    if (!window.SSSDBStatus) return;
    return window.SSSDBStatus.on(() => setStatus(snap()));
  }, []);

  // refresh counts every 5s to reflect live data changes
  useEffectDBS(() => {
    const t = setInterval(() => setTick(n => n + 1), 5000);
    return () => clearInterval(t);
  }, []);

  const D = window.SSSData;
  const { Card, Btn } = window.UI;
  const isAnim = status.state === 'saving' || status.state === 'loading';
  const dotColor = DBS_STATE_COLOR[status.state] || '#9ca3af';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <style>{`
        @keyframes dbs-pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:0.4;transform:scale(0.7)} }
        @keyframes dbs-spin  { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
      `}</style>

      {/* ── สถานะหลัก ── */}
      <Card padded>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ position: 'relative', width: 44, height: 44, display: 'grid', placeItems: 'center',
              background: dotColor + '18', borderRadius: '50%', flexShrink: 0 }}>
              <I.db size={22} style={{ color: dotColor }} />
              <span style={{ position: 'absolute', bottom: 2, right: 2, width: 11, height: 11, borderRadius: '50%',
                background: dotColor, border: '2px solid var(--surface)',
                animation: isAnim ? 'dbs-pulse 1.2s ease-in-out infinite' : 'none' }} />
            </div>
            <div>
              <div style={{ fontSize: 16, fontWeight: 700, color: dotColor }}>{DBS_STATE_LABEL[status.state] || status.state}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>Supabase PostgreSQL · build {(window.SSSSync && window.SSSSync.BUILD) || '—'}</div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 20, fontSize: 12, color: 'var(--ink-3)', flexWrap: 'wrap', flex: 1, justifyContent: 'center' }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10, marginBottom: 2 }}>บันทึกล่าสุด</div>
              <b style={{ color: 'var(--ink-1)', fontSize: 13 }}>{fmtTime(status.lastSave)}</b>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10, marginBottom: 2 }}>โหลดล่าสุด</div>
              <b style={{ color: 'var(--ink-1)', fontSize: 13 }}>{fmtTime(status.lastLoad)}</b>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10, marginBottom: 2 }}>คอลเลคชัน</div>
              <b style={{ color: 'var(--ink-1)', fontSize: 13 }}>{status.loadedCount || DBS_COLLECTIONS.length}</b>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {status.state === 'offline' || status.state === 'error' ? (
              <Btn size="sm" kind="primary" onClick={() => window.SSSSync && window.SSSSync.reconnect().then(() => { setStatus(snap()); window.toast && window.toast('ลองเชื่อมต่อใหม่แล้ว'); })}>
                🔌 เชื่อมต่อใหม่
              </Btn>
            ) : (
              <>
                <Btn size="sm" kind="ghost" onClick={() => window.SSSSync && window.SSSSync.save()}>💾 บันทึกทันที</Btn>
                <Btn size="sm" kind="primary" onClick={() => window.SSSSync && window.SSSSync.load().then(() => { window.toast && window.toast('โหลดข้อมูลสำเร็จ'); setStatus(snap()); })}>🔄 โหลดใหม่</Btn>
              </>
            )}
          </div>
        </div>

        {(status.state === 'offline') && (
          <div style={{ marginTop: 12, background: '#fff7ed', border: '1px solid #fed7aa', borderRadius: 8, padding: '10px 14px', fontSize: 12 }}>
            <b style={{ color: '#c2410c' }}>🔌 ไม่สามารถเชื่อมต่อ Supabase ได้ — สาเหตุที่เป็นไปได้:</b>
            <ol style={{ margin: '6px 0 0 16px', color: '#9a3412', lineHeight: 1.8 }}>
              <li>โปรเจกต์ Supabase หยุดชั่วคราว (Free Tier หยุดหลังไม่ได้ใช้ 1 สัปดาห์) → ไปที่ <b>supabase.com → โปรเจกต์ → Restore project</b></li>
              <li>ไลบรารี Supabase JS ไม่โหลด → กด F12 → Console ดูว่ามี error ไหม</li>
              <li>เน็ตไม่ได้เชื่อมต่อ → ตรวจสอบการเชื่อมต่ออินเทอร์เน็ต</li>
            </ol>
            <div style={{ marginTop: 8 }}>แอปยังทำงานได้ปกติด้วย localStorage — ข้อมูลจะ sync อัตโนมัติเมื่อเชื่อมต่อได้</div>
          </div>
        )}

        {status.lastError && status.state !== 'offline' && (
          <div style={{ marginTop: 12, background: '#fef2f2', color: '#ef4444', borderRadius: 8, padding: '8px 12px', fontSize: 12, border: '1px solid #fecaca' }}>
            ⚠️ {status.lastError}
          </div>
        )}
      </Card>

      {/* ── คอลเลคชันข้อมูล ── */}
      <Card title="คอลเลคชันข้อมูลในหน่วยความจำ" sub="นับจำนวน records ที่โหลดอยู่ใน SSSData ขณะนี้" padded>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 8 }}>
          {DBS_COLLECTIONS.map(({ key, label }) => {
            const count = D && Array.isArray(D[key]) ? D[key].length : null;
            const hasData = count !== null && count > 0;
            return (
              <div key={key} style={{ background: 'var(--surface-2)', borderRadius: 8, padding: '9px 11px',
                border: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 2 }}>
                <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</div>
                <div style={{ fontSize: 20, fontWeight: 800, color: hasData ? 'var(--ink-1)' : 'var(--ink-3)', lineHeight: 1.1 }}>
                  {count !== null ? count : '—'}
                </div>
                <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{key}</div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* ── LocalStore keys ที่ sync ── */}
      <Card title="LocalStore ที่ sync ขึ้น Supabase" sub="ข้อมูลการตั้งค่าที่ sync ผ่าน localStorage" padded>
        {(() => {
          const D2 = window.SSSData;
          const ls = D2 && D2.LocalStore && typeof D2.LocalStore === 'object' ? D2.LocalStore : {};
          const keys = Object.keys(ls);
          if (keys.length === 0) return <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>ไม่มีข้อมูล LocalStore</div>;
          return (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {keys.map(k => {
                const val = ls[k];
                const count = Array.isArray(val) ? val.length : (val && typeof val === 'object' ? Object.keys(val).length : null);
                return (
                  <div key={k} style={{ background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 6, padding: '4px 10px', fontSize: 11 }}>
                    <span className="mono" style={{ color: 'var(--ink-2)' }}>{k}</span>
                    {count !== null && <span style={{ marginLeft: 5, color: 'var(--ink-3)' }}>({count})</span>}
                  </div>
                );
              })}
            </div>
          );
        })()}
      </Card>

      {/* ── Sync log ── */}
      <Card title="ประวัติการซิงค์" sub={`${status.log.length} รายการล่าสุด`} padded>
        {status.log.length === 0 ? (
          <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>ยังไม่มีกิจกรรม — รอโหลด/บันทึกครั้งแรก</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {status.log.map((entry, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '6px 0',
                borderBottom: i < status.log.length - 1 ? '1px solid var(--line-soft)' : 'none' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: DBS_LOG_COLOR[entry.type] || '#9ca3af',
                  flexShrink: 0, marginTop: 5 }} />
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', flexShrink: 0, minWidth: 60 }}>
                  {fmtTime(entry.time)}
                </span>
                <span style={{ fontSize: 12 }}>{entry.msg}</span>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

window.DBStatusPage = DBStatusPage;
