/* global React, Ic, useStore, useToast, Modal, fireConfetti */
const { useState: useAdmS, useMemo: useAdmM } = React;

// Permission groups — mirror the sidebar nav structure
const PERM_GROUPS = [
  { label: 'ภาพรวม', items: [{ id: 'dashboard', label: 'แดชบอร์ด' }] },
  { label: 'การดำเนินงาน', items: [
    { id: 'receive', label: 'รับเข้าวัตถุดิบ' },
    { id: 'issue', label: 'จ่ายออกสินค้า' },
    { id: 'transfer', label: 'โอนระหว่าง Location' },
    { id: 'count', label: 'Stock Count' },
    { id: 'scanner', label: 'Barcode Scanner' },
  ]},
  { label: 'คลังสินค้า', items: [
    { id: 'items', label: 'รายการสินค้า' },
    { id: 'locations', label: 'Locations & Map' },
  ]},
  { label: 'รายงาน', items: [
    { id: 'stock-report', label: 'รายงานสต็อกคงเหลือ' },
    { id: 'movement', label: 'รายงานเคลื่อนไหว' },
    { id: 'lifeshelf', label: 'Life Shelf Monitor' },
    { id: 'documents', label: 'ประวัติเอกสาร' },
  ]},
  { label: 'ผู้ดูแลระบบ', items: [
    { id: 'users', label: 'จัดการผู้ใช้งาน' },
  ]},
];
const ALL_PERM_IDS = PERM_GROUPS.flatMap(g => g.items.map(i => i.id));
const TOTAL_PERMS = ALL_PERM_IDS.length;
const AVATAR_COLORS = ['#2563eb', '#16a34a', '#d97706', '#dc2626', '#7c3aed', '#0891b2', '#db2777'];

// ============ Login Page ============
function LoginPage() {
  const store = useStore();
  const [username, setUsername] = useAdmS('');
  const [password, setPassword] = useAdmS('');
  const [show, setShow] = useAdmS(false);
  const [error, setError] = useAdmS('');
  const [busy, setBusy] = useAdmS(false);

  const submit = (e) => {
    if (e) e.preventDefault();
    setError('');
    setBusy(true);
    const res = store.login(username, password);
    if (!res.ok) { setError(res.error); setBusy(false); }
    // on success, Root re-renders to the app automatically
  };

  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="login-brand">
          <div className="brand-mark" style={{ width: 44, height: 44, fontSize: 20 }}>W</div>
          <div>
            <div className="login-title">Warehouse OS</div>
            <div className="login-sub">ระบบบริหารคลังสินค้า · WMS</div>
          </div>
        </div>

        <div className="login-heading">เข้าสู่ระบบ</div>
        <div className="login-heading-sub">กรอกชื่อผู้ใช้และรหัสผ่านเพื่อเริ่มใช้งาน</div>

        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 18 }}>
          <div className="field">
            <label>ชื่อผู้ใช้ · Username</label>
            <input className="input" autoFocus value={username} onChange={e => setUsername(e.target.value)} placeholder="admin"/>
          </div>
          <div className="field">
            <label>รหัสผ่าน · Password</label>
            <div className="input-with-suffix">
              <input className="input" type={show ? 'text' : 'password'} value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••"/>
              <button type="button" className="suffix-btn" onClick={() => setShow(!show)} tabIndex={-1}>
                <Ic name={show ? 'eye-off' : 'eye'} size={15}/>
              </button>
            </div>
          </div>

          {error && (
            <div className="login-error">
              <Ic name="alert" size={14}/>
              <span>{error}</span>
            </div>
          )}

          <button type="submit" className="btn btn-primary" style={{ justifyContent: 'center', padding: '11px', marginTop: 4 }} disabled={busy}>
            <Ic name="log-in" size={15}/>เข้าสู่ระบบ
          </button>
        </form>
      </div>
      <div className="login-foot mono">WAREHOUSE OS · v2.6 · © 2026 Prime Glory</div>
    </div>
  );
}

// ============ Permission editor (used in user modal) ============
function PermissionEditor({ role, perms, onChangeRole, onChangePerms }) {
  const isAdmin = role === 'admin';
  const checked = (id) => isAdmin || perms.includes(id);
  const toggle = (id) => {
    if (isAdmin) return;
    onChangePerms(perms.includes(id) ? perms.filter(p => p !== id) : [...perms, id]);
  };
  const count = isAdmin ? TOTAL_PERMS : perms.length;

  return (
    <div className="perm-editor">
      {/* Admin master toggle */}
      <label className={`perm-admin ${isAdmin ? 'on' : ''}`}>
        <input type="checkbox" checked={isAdmin} onChange={e => onChangeRole(e.target.checked ? 'admin' : 'custom')}/>
        <span className="perm-box"><Ic name="check" size={12}/></span>
        <span>
          <span className="perm-admin-title">ผู้ดูแลระบบ (สิทธิ์เต็ม — เห็นทุกส่วน)</span>
          <span className="perm-admin-sub">เข้าถึงได้ทุกเมนูรวมถึงการจัดการผู้ใช้งาน</span>
        </span>
      </label>

      <div className="perm-head">
        <span className="mono">อนุญาตให้เห็นแถบเมนู ({count}/{TOTAL_PERMS})</span>
        <div className="row" style={{ gap: 6 }}>
          <button type="button" className="btn btn-ghost btn-sm" disabled={isAdmin}
            onClick={() => onChangePerms([...ALL_PERM_IDS])}>เลือกทั้งหมด</button>
          <button type="button" className="btn btn-ghost btn-sm" disabled={isAdmin}
            onClick={() => onChangePerms([])}>ล้าง</button>
        </div>
      </div>

      <div className={`perm-grid ${isAdmin ? 'locked' : ''}`}>
        {PERM_GROUPS.map(g => (
          <div key={g.label} className="perm-group">
            <div className="perm-group-label">{g.label}</div>
            {g.items.map(it => (
              <label key={it.id} className={`perm-chk ${checked(it.id) ? 'on' : ''}`}>
                <input type="checkbox" checked={checked(it.id)} disabled={isAdmin} onChange={() => toggle(it.id)}/>
                <span className="perm-box"><Ic name="check" size={11}/></span>
                <span>{it.label}</span>
              </label>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ User Management Page ============
function PageUsers() {
  const store = useStore();
  const { state } = store;
  const toast = useToast();
  const [reveal, setReveal] = useAdmS({});       // {userId: bool}
  const [editing, setEditing] = useAdmS(null);   // user object | 'new' | null

  const blank = () => ({
    id: `U-${String(Date.now()).slice(-4)}`,
    name: '', username: '', password: '', email: '',
    role: 'custom', perms: ['dashboard'], active: true,
    lastLogin: '—', initials: '', color: AVATAR_COLORS[Math.floor(Math.random() * AVATAR_COLORS.length)],
  });

  const accessLabel = (u) => {
    if (u.role === 'admin') return { text: 'ผู้ดูแลระบบ (สิทธิ์เต็ม)', cls: 'admin' };
    return { text: `${u.perms.length}/${TOTAL_PERMS} ส่วน`, cls: 'partial' };
  };

  return (
    <div className="page-enter">
      <div className="page-header">
        <div>
          <h2 className="page-title">จัดการผู้ใช้งาน <span className="muted mono" style={{ fontSize: 14, marginLeft: 8 }}>// USER MANAGEMENT</span></h2>
          <div className="page-subtitle">{state.users.length} บัญชี · กำหนดสิทธิ์การเข้าถึงแต่ละเมนู</div>
        </div>
        <button className="btn btn-primary" onClick={() => setEditing(blank())}><Ic name="plus" size={14}/>สร้างผู้ใช้ใหม่</button>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div className="table-wrap" style={{ border: 'none' }}>
          <table className="data">
            <thead>
              <tr>
                <th>ชื่อ</th>
                <th>ชื่อผู้ใช้</th>
                <th>รหัสผ่าน</th>
                <th>อีเมล</th>
                <th>สิทธิ์การเข้าถึง</th>
                <th>เข้าใช้ล่าสุด</th>
                <th>สถานะ</th>
                <th style={{ textAlign: 'right' }}>จัดการ</th>
              </tr>
            </thead>
            <tbody>
              {state.users.map(u => {
                const acc = accessLabel(u);
                const isMe = store.currentUser?.id === u.id;
                return (
                  <tr key={u.id} className="user-row">
                    <td>
                      <div className="row" style={{ gap: 10 }}>
                        <div className="user-ava" style={{ background: u.color }}>{u.initials || u.name.slice(0, 2).toUpperCase()}</div>
                        <div>
                          <div style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{u.name || '—'}{isMe && <span className="badge info" style={{ marginLeft: 6, fontSize: 9 }}>คุณ</span>}</div>
                        </div>
                      </div>
                    </td>
                    <td className="mono" style={{ color: 'var(--accent)' }}>{u.username}</td>
                    <td>
                      <div className="row" style={{ gap: 6 }}>
                        <span className="mono" style={{ letterSpacing: reveal[u.id] ? 0 : '2px' }}>{reveal[u.id] ? u.password : '••••••'}</span>
                        <button className="row-action" style={{ opacity: 1 }} onClick={() => setReveal(r => ({ ...r, [u.id]: !r[u.id] }))}>
                          <Ic name={reveal[u.id] ? 'eye-off' : 'eye'} size={13}/>
                        </button>
                      </div>
                    </td>
                    <td style={{ color: 'var(--text-secondary)' }}>{u.email || '—'}</td>
                    <td><span className={`access-badge ${acc.cls}`}>{acc.text}</span></td>
                    <td className="mono" style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{u.lastLogin}</td>
                    <td>
                      <span className={`badge ${u.active ? 'ok' : 'neutral'}`}>{u.active ? 'ใช้งาน' : 'ปิดใช้งาน'}</span>
                    </td>
                    <td>
                      <div className="row" style={{ gap: 4, justifyContent: 'flex-end' }}>
                        <button className="row-action" style={{ opacity: 1 }} data-tip="แก้ไข" onClick={() => setEditing(u)}><Ic name="edit" size={13}/></button>
                        <button className="row-action" style={{ opacity: 1 }} data-tip={u.active ? 'ปิดใช้งาน' : 'เปิดใช้งาน'}
                          onClick={() => { store.toggleUserActive(u.id); toast.info(u.active ? 'ปิดใช้งานบัญชี' : 'เปิดใช้งานบัญชี', u.name); }}>
                          <Ic name={u.active ? 'lock' : 'unlock'} size={13}/>
                        </button>
                        <button className="row-action danger" style={{ opacity: 1 }} data-tip="ลบ"
                          disabled={isMe || u.role === 'admin'}
                          onClick={() => {
                            if (isMe) { toast.error('ลบบัญชีตัวเองไม่ได้'); return; }
                            if (!confirm(`ลบผู้ใช้ ${u.name} (${u.username}) ?`)) return;
                            store.deleteUser(u.id);
                            toast.success('ลบผู้ใช้แล้ว', u.name);
                          }}>
                          <Ic name="trash" size={13}/>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <DataCleanupCard/>

      {editing && <UserModal user={editing} onClose={() => setEditing(null)}/>}
    </div>
  );
}

// ============ Admin: Data Cleanup (clear mock/test data by category) ============
function DataCleanupCard() {
  const store = useStore();
  const { state } = store;
  const toast = useToast();
  if (!store.isAdmin || !store.isAdmin()) return null;

  const run = (label, count, action, note) => {
    if (!count) { toast.info('ไม่มีข้อมูลให้ล้าง', label); return; }
    if (!confirm(`ล้าง "${label}" ?\n\nจะลบ ${count} รายการออกถาวร${note ? '\n• ' + note : ''}\n\n⚠ ย้อนกลับไม่ได้`)) return;
    action();
    toast.success('ล้างข้อมูลแล้ว', `${label} · ลบ ${count} รายการ`);
  };

  const rows = [
    { key: 'items', label: 'รายการสินค้า (Item Master)', sub: 'สินค้าทั้งหมด', count: state.items.length, action: store.clearItems, note: 'ลบสต็อกที่ผูกกับสินค้าเหล่านี้ด้วย' },
    { key: 'stock', label: 'สต็อกคงเหลือ (Stock Balance)', sub: 'ยอดคงเหลือทุก lot/location · เก็บรายการสินค้าไว้', count: state.stock.length, action: store.clearStock },
    { key: 'mv', label: 'ประวัติเคลื่อนไหว (Movement)', sub: 'รับเข้า / จ่ายออก / โอน / นับสต็อก · ชุดข้อมูลเดียวกับประวัติเอกสาร', count: state.movements.length, action: store.clearMovements },
    { key: 'docs', label: 'ประวัติเอกสาร (Document Trail)', sub: 'เลขที่เอกสารทั้งหมด · เป็นข้อมูลชุดเดียวกับประวัติเคลื่อนไหว', count: state.movements.length, action: store.clearMovements, note: 'ล้างที่ใดที่หนึ่งจะหายทั้งคู่' },
    { key: 'loc', label: 'Locations & Warehouse Map', sub: 'ทุก bin / ชั้นวาง · เก็บตัวคลังไว้', count: state.locations.length, action: store.clearLocations, note: 'ลบสต็อกในทุก location ด้วย' },
  ];
  const totalAll = state.items.length + state.stock.length + state.movements.length + state.locations.length;

  return (
    <div className="card" style={{ marginTop: 18, border: '1px solid var(--danger)', borderTopWidth: 3 }}>
      <div className="card-head">
        <div>
          <div className="card-title" style={{ color: 'var(--danger)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Ic name="trash" size={15}/> ล้างข้อมูล · Data Cleanup
          </div>
          <div className="card-sub">สำหรับ Admin — ล้าง mock/ข้อมูลทดสอบเป็นหมวด · <b>ไม่กระทบ</b> ผู้ใช้, สิทธิ์, หมวดสินค้า, supplier, customer, ตัวคลัง</div>
        </div>
        <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)', borderColor: 'var(--danger)' }} disabled={!totalAll}
          onClick={() => run('ข้อมูลปฏิบัติการทั้งหมด (สินค้า + สต็อก + เคลื่อนไหว + location)', totalAll, store.clearAllData, 'รีเซ็ตเป็นสถานะพร้อมเริ่มใช้งานจริง')}>
          <Ic name="trash" size={13}/> ล้างทั้งหมด
        </button>
      </div>

      <div style={{ marginTop: 4 }}>
        {rows.map((r, i) => (
          <div key={r.key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, padding: '12px 2px', borderTop: i === 0 ? 'none' : '1px solid var(--border)' }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>
                {r.label}
                <span className="badge neutral" style={{ marginLeft: 8 }}>{r.count}</span>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{r.sub}</div>
            </div>
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)', flexShrink: 0 }} disabled={!r.count}
              onClick={() => run(r.label, r.count, r.action, r.note)}>
              <Ic name="trash" size={13}/> ล้าง
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ Create / Edit user modal ============
function UserModal({ user, onClose }) {
  const store = useStore();
  const toast = useToast();
  const isNew = !store.state.users.find(u => u.id === user.id);
  const [form, setForm] = useAdmS(user);
  const set = (patch) => setForm(f => ({ ...f, ...patch }));

  const save = () => {
    if (!form.name.trim() || !form.username.trim()) { toast.error('กรอกชื่อและชื่อผู้ใช้'); return; }
    if (!form.password) { toast.error('กรอกรหัสผ่าน'); return; }
    const dup = store.state.users.find(u => u.id !== form.id && u.username.toLowerCase() === form.username.trim().toLowerCase());
    if (dup) { toast.error('ชื่อผู้ใช้ซ้ำ', form.username); return; }
    const clean = {
      ...form,
      username: form.username.trim(),
      initials: form.initials || form.name.trim().slice(0, 2).toUpperCase(),
      perms: form.role === 'admin' ? [] : form.perms,
    };
    if (isNew) { store.addUser(clean); toast.success('สร้างผู้ใช้ใหม่', clean.name); fireConfetti(); }
    else { store.updateUser(form.id, clean); toast.success('บันทึกผู้ใช้', clean.name); }
    onClose();
  };

  return (
    <Modal open onClose={onClose} width={640} title={isNew ? 'สร้างผู้ใช้ใหม่' : `แก้ไขผู้ใช้ · ${user.name}`}
      footer={(
        <>
          <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button className="btn btn-primary" onClick={save}><Ic name="check" size={14}/>{isNew ? 'สร้างบัญชี' : 'บันทึก'}</button>
        </>
      )}>
      <div className="grid-2">
        <div className="field"><label>ชื่อ-นามสกุล</label><input className="input" value={form.name} onChange={e => set({ name: e.target.value })} placeholder="เช่น สมชาย ใจดี"/></div>
        <div className="field"><label>อีเมล</label><input className="input" value={form.email} onChange={e => set({ email: e.target.value })} placeholder="name@company.com"/></div>
        <div className="field"><label>ชื่อผู้ใช้ · Username</label><input className="input mono" value={form.username} onChange={e => set({ username: e.target.value })} placeholder="username"/></div>
        <div className="field"><label>รหัสผ่าน · Password</label><input className="input mono" value={form.password} onChange={e => set({ password: e.target.value })} placeholder="••••••"/></div>
      </div>

      <div className="hr"/>
      <PermissionEditor
        role={form.role}
        perms={form.perms}
        onChangeRole={(role) => set({ role })}
        onChangePerms={(perms) => set({ perms })}
      />
    </Modal>
  );
}

Object.assign(window, { LoginPage, PageUsers, PermissionEditor, PERM_GROUPS, ALL_PERM_IDS });
