// User Management screen — Super User only
const { useState: useState_um, useMemo: useMemo_um } = React;

function UsersScreen({ store }) {
  const { users, addUser, updateUser, deleteUser, toggleUserStatus, setUserViewerPerm, setTourDone, setMustChangePassword, currentUser } = store;
  const [editing, setEditing] = useState_um(null); // user object or "new"
  const [deleting, setDeleting] = useState_um(null); // user object to confirm delete
  const [search, setSearch] = useState_um("");
  const [deleteLoading, setDeleteLoading] = useState_um(false);
  const toast = useToast();

  const filtered = useMemo_um(
    () => users.filter(u =>
      u.email.toLowerCase().includes(search.toLowerCase()) ||
      u.name.toLowerCase().includes(search.toLowerCase())
    ),
    [users, search]
  );

  const expiringSoon = users.filter(u => {
    if (!u.expiry || u.status === "disabled") return false;
    const days = (new Date(u.expiry).getTime() - Date.now()) / (24*3600*1000);
    return days > 0 && days < 30;
  });

  return (
    <div className="page" data-screen-label="Users">
      <div className="sec-head">
        <div>
          <h2 className="sec-title">จัดการผู้ใช้ระบบ</h2>
          <div className="sec-sub">เฉพาะ Super User · {users.length} บัญชี · ใช้งานจริง {users.filter(u => u.status === "active").length} บัญชี</div>
        </div>
        <button className="btn primary" onClick={() => setEditing("new")}>
          <Icon name="plus" size={15} stroke={2.2} /> สร้างบัญชี
        </button>
      </div>

      <section>
        <div className="tile-grid">
          <Tile label="Super Users" num={users.filter(u => u.role === "super").length} sub="เข้าถึงทุกอย่าง" />
          <Tile label="Group Owners" num={users.filter(u => u.role === "admin").length} sub="ดูแลก๊วนตัวเอง" />
          <Tile label="ใช้งานอยู่" num={users.filter(u => u.status === "active").length} sub={`จาก ${users.length} บัญชี`} accent="green" />
          <Tile label="กำลังจะหมดอายุ" num={expiringSoon.length} sub="ภายใน 30 วัน" />
        </div>
      </section>

      <section>
        <div style={{position:"relative", marginBottom:12, maxWidth: 400}}>
          <input placeholder="ค้นหาผู้ใช้…" value={search} onChange={e => setSearch(e.target.value)} style={{paddingLeft: 36}} />
          <div style={{position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--text-3)", pointerEvents:"none"}}>
            <Icon name="search" size={16} />
          </div>
        </div>

        <div className="card dtable">
          <div className="dhead card-row" style={{background:"var(--bg-elev-2)", fontSize:11, fontWeight:600, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.05em"}}>
            <div className="dcol dc-avatar" />
            <div className="dcol-main">ผู้ใช้</div>
            <div className="dcol dc-role">บทบาท</div>
            <div className="dcol dc-exp">วันหมดอายุ</div>
            <div className="dcol dc-status">สถานะ</div>
            <div className="dcol dc-act" />
          </div>
          {filtered.map(u => {
            const expDays = u.expiry ? Math.floor((new Date(u.expiry).getTime() - Date.now()) / (24*3600*1000)) : null;
            const expired = expDays !== null && expDays < 0;
            return (
              <div key={u.id} className="drow card-row" style={{opacity: u.status === "disabled" ? 0.55 : 1}}>
                <div className="dcol dc-avatar avatar" style={{width:32, height:32, fontSize:11, background:`linear-gradient(135deg, ${u.role==="super" ? "#ffd60a" : u.role==="admin" ? "#0a84ff" : "#8e8e93"}, ${u.role==="super" ? "#ff9f0a" : u.role==="admin" ? "#5e5ce6" : "#3a3a3c"})`}}>
                  {initials(u.name)}
                </div>
                <div className="dcol-main">
                  <div style={{fontWeight: 500}}>{u.name}</div>
                  <div className="small muted" style={{whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>
                    {u.username ? <span>@{u.username} · </span> : null}{u.email}
                  </div>
                  {u.role === "admin" && u.permViewerCustomize && (
                    <span className="chip" style={{marginTop:4, fontSize:10, background:"var(--tint-soft, var(--bg-inset))", color:"var(--tint)"}}>
                      <Icon name="eye" size={10} /> ปรับแต่งหน้าผู้ชมได้
                    </span>
                  )}
                  <span className="chip" style={{marginTop:4, fontSize:10,
                    background: u.tourDone ? "var(--green-soft)" : "var(--orange-soft, rgba(255,149,0,0.12))",
                    color: u.tourDone ? "var(--green)" : "var(--orange)"}}>
                    <Icon name="help" size={10} /> {u.tourDone ? "ดู Tutorial แล้ว" : "ยังไม่ได้ดู Tutorial"}
                  </span>
                  {u.mustChangePassword && (
                    <span className="chip" style={{marginTop:4, fontSize:10,
                      background:"rgba(255,59,48,0.12)", color:"var(--red)"}}>
                      <Icon name="lock" size={10} /> ต้องเปลี่ยนรหัสผ่าน
                    </span>
                  )}
                </div>
                <div className="dmeta">
                  <div className="dcol dc-role">
                    <span className="dmeta-label">บทบาท</span>
                    <span className={`role-badge role-${u.role}`}>
                      {roleLabel(u.role)}
                    </span>
                  </div>
                  <div className="dcol dc-exp small">
                    <span className="dmeta-label">วันหมดอายุ</span>
                    {u.expiry ? (
                      <div>
                        <div>{u.expiry}</div>
                        <div className={expired ? "small" : "small muted"}
                            style={expired ? {color:"var(--red)", fontWeight:600} : {}}>
                          {expired ? "หมดอายุแล้ว" : `อีก ${expDays} วัน`}
                        </div>
                      </div>
                    ) : <span className="muted">ไม่จำกัด</span>}
                  </div>
                  <div className="dcol dc-status">
                    <span className="dmeta-label">สถานะ</span>
                    {u.status === "active"
                      ? <span className="chip green">ใช้งาน</span>
                      : <span className="chip">ระงับ</span>}
                  </div>
                </div>
                <div className="dcol dc-act dcol-actions">
                  {u.role === "admin" && (
                    <button className={`btn icon ${u.permViewerCustomize ? "primary" : ""}`}
                            onClick={() => { setUserViewerPerm(u.id, !u.permViewerCustomize); toast(u.permViewerCustomize ? "ปิดสิทธิ์ปรับแต่งหน้าผู้ชมแล้ว" : "เปิดสิทธิ์ปรับแต่งหน้าผู้ชมแล้ว"); }}
                            title={u.permViewerCustomize ? "ปิดสิทธิ์ปรับแต่งหน้าผู้ชม" : "เปิดสิทธิ์ปรับแต่งหน้าผู้ชม"}>
                      <Icon name="eye" size={13} />
                    </button>
                  )}
                  <button className={`btn icon ${!u.tourDone ? "primary" : ""}`}
                          onClick={() => {
                            setTourDone(!u.tourDone, u.id);
                            toast(u.tourDone ? `รีเซ็ต Tutorial ของ ${u.name} แล้ว` : `ทำเครื่องหมาย Tutorial ว่าดูแล้ว`);
                          }}
                          title={u.tourDone ? "รีเซ็ต Tutorial (จะให้ขึ้นใหม่ครั้งหน้า login)" : "ทำเครื่องหมายว่าดู Tutorial แล้ว"}>
                    <Icon name="help" size={13} />
                  </button>
                  <button className={`btn icon ${u.mustChangePassword ? "primary" : ""}`}
                          onClick={() => {
                            setMustChangePassword(!u.mustChangePassword, u.id);
                            toast(u.mustChangePassword ? `ยกเลิกบังคับเปลี่ยนรหัสผ่านของ ${u.name} แล้ว` : `บังคับให้ ${u.name} เปลี่ยนรหัสผ่านครั้งหน้า login`);
                          }}
                          title={u.mustChangePassword ? "ยกเลิกบังคับเปลี่ยนรหัสผ่าน" : "บังคับเปลี่ยนรหัสผ่านครั้งหน้า Login"}>
                    <Icon name="lock" size={13} />
                  </button>
                  <button className="btn icon" onClick={() => setEditing(u)} title="แก้ไข">
                    <Icon name="edit" size={13} />
                  </button>
                  <button className="btn icon" onClick={() => { toggleUserStatus(u.id); toast(u.status === "active" ? "ระงับบัญชีแล้ว" : "เปิดใช้งานแล้ว"); }}
                          title={u.status === "active" ? "ระงับ" : "เปิด"}>
                    <Icon name="door" size={13} />
                  </button>
                  {u.id !== currentUser?.id && (
                    <button className="btn icon danger" onClick={() => setDeleting(u)} title="ลบบัญชี">
                      <Icon name="trash" size={13} />
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </section>

      {editing && (
        <UserEditor
          user={editing === "new" ? null : editing}
          sbMode={store.sbMode}
          onClose={() => setEditing(null)}
          onSave={async (data) => {
            if (editing === "new") {
              try {
                await addUser(data);
                toast("สร้างบัญชีแล้ว — ผู้ใช้จะต้องเปลี่ยนรหัสผ่านเมื่อ Login ครั้งแรก");
                setEditing(null);
              } catch (e) {
                toast("สร้างบัญชีไม่สำเร็จ: " + (e.message || "ลองใหม่อีกครั้ง"));
              }
            } else {
              updateUser(editing.id, data);
              toast("บันทึกแล้ว");
              setEditing(null);
            }
          }}
        />
      )}

      {deleting && (
        <Modal open title="ลบบัญชีผู้ใช้" onClose={() => !deleteLoading && setDeleting(null)}
          footer={<>
            <button className="btn" onClick={() => setDeleting(null)} disabled={deleteLoading}>ยกเลิก</button>
            <button className="btn danger" disabled={deleteLoading} onClick={async () => {
              setDeleteLoading(true);
              try {
                await deleteUser(deleting.id);
                toast(`ลบบัญชี ${deleting.name} แล้ว`);
                setDeleting(null);
              } catch (e) {
                toast("ลบบัญชีไม่สำเร็จ: " + (e.message || "ลองใหม่อีกครั้ง"));
              } finally {
                setDeleteLoading(false);
              }
            }}>
              {deleteLoading ? "กำลังลบ…" : "ยืนยันลบ"}
            </button>
          </>}>
          <div style={{marginBottom:8}}>
            คุณต้องการลบบัญชีนี้ถาวรหรือไม่?
          </div>
          <div className="card card-pad" style={{background:"var(--bg-elev-2)"}}>
            <div style={{fontWeight:600}}>{deleting.name}</div>
            <div className="small muted">{deleting.username ? `@${deleting.username} · ` : ""}{deleting.email}</div>
            <div className="small muted mt-1">บทบาท: {roleLabel(deleting.role)}</div>
          </div>
          <div className="small" style={{marginTop:12, color:"var(--red)", fontWeight:500}}>
            การกระทำนี้ไม่สามารถย้อนกลับได้ — ข้อมูลทั้งหมดของบัญชีนี้จะถูกลบออกจากระบบ
          </div>
        </Modal>
      )}
    </div>
  );
}

function UserEditor({ user, sbMode, onClose, onSave }) {
  const isNew = !user;
  const [name, setName]     = useState_um(user?.name || "");
  const [username, setUsername] = useState_um(user?.username || "");
  const [email, setEmail]   = useState_um(user?.email || "");
  const [role, setRole]     = useState_um(user?.role || "admin");
  const [expiry, setExpiry] = useState_um(user?.expiry || "");
  const [password, setPassword] = useState_um("");
  const [showPw, setShowPw] = useState_um(false);
  const [saving, setSaving] = useState_um(false);

  const genPassword = () => {
    const chars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#$";
    let pw = "";
    for (let i = 0; i < 12; i++) pw += chars[Math.floor(Math.random() * chars.length)];
    setPassword(pw);
    setShowPw(true);
  };

  const submit = async () => {
    if (!name.trim() || !email.trim()) return alert("กรุณากรอกชื่อและอีเมล");
    if (role !== "super" && role !== "admin") return alert("บทบาทไม่ถูกต้อง");
    const uname = username.trim();
    if (uname && !/^[a-zA-Z0-9._-]+$/.test(uname))
      return alert("Username ใช้ได้เฉพาะ a-z, 0-9, จุด, ขีดล่าง, ขีดกลาง (ห้ามเว้นวรรคหรือ @)");
    if (isNew && sbMode && !password.trim())
      return alert("กรุณากรอกรหัสผ่านสำหรับบัญชีใหม่ (หรือกดสร้างอัตโนมัติ)");
    if (isNew && password.trim() && password.trim().length < 8)
      return alert("รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร");
    setSaving(true);
    try {
      await onSave({
        name: name.trim(), username: uname || null,
        email: email.trim(), role, expiry: expiry || null,
        ...(isNew ? { password: password.trim() } : {}),
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open title={isNew ? "สร้างบัญชีใหม่" : "แก้ไขบัญชี"} onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose} disabled={saving}>ยกเลิก</button>
        <button className="btn primary" onClick={submit} disabled={saving}>
          {saving ? "กำลังบันทึก…" : isNew ? "สร้าง" : "บันทึก"}
        </button>
      </>}>
      <div className="field">
        <label>ชื่อ <span style={{color:"var(--red)"}}>*</span></label>
        <input value={name} onChange={e => setName(e.target.value)} placeholder="ชื่อ-สกุล หรือ ชื่อเล่น" />
      </div>
      <div className="field">
        <label>Username (ไม่บังคับ)</label>
        <input value={username} onChange={e => setUsername(e.target.value)} placeholder="เช่น coach_aek" autoCapitalize="none" spellCheck="false" />
        <div className="hint">ใช้เข้าสู่ระบบแทนอีเมลได้ — a-z, 0-9, . _ - (ห้ามเว้นวรรค)</div>
      </div>
      <div className="field">
        <label>อีเมล <span style={{color:"var(--red)"}}>*</span></label>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="user@example.com" autoCapitalize="none" />
        <div className="hint">ใช้เข้าสู่ระบบได้เช่นกัน · เป็นบัญชีหลักของ Supabase Auth</div>
      </div>
      {isNew && (
        <div className="field">
          <label>รหัสผ่านเริ่มต้น {sbMode && <span style={{color:"var(--red)"}}>*</span>}</label>
          <div className="row gap-8" style={{alignItems:"stretch"}}>
            <input
              type={showPw ? "text" : "password"}
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="อย่างน้อย 8 ตัวอักษร"
              style={{flex:1}}
              autoComplete="new-password"
            />
            <button type="button" className="btn" style={{flexShrink:0}} onClick={genPassword} title="สร้างรหัสผ่านแบบสุ่ม">
              สร้างอัตโนมัติ
            </button>
          </div>
          {password && (
            <div className="hint" style={{display:"flex", alignItems:"center", gap:6, marginTop:4}}>
              <input type="checkbox" id="show-pw-toggle" checked={showPw} onChange={e => setShowPw(e.target.checked)} style={{width:13,height:13}} />
              <label htmlFor="show-pw-toggle" style={{cursor:"pointer"}}>แสดงรหัสผ่าน</label>
              {showPw && password && <span style={{fontFamily:"monospace", color:"var(--tint)", fontWeight:600}}>{password}</span>}
            </div>
          )}
          <div className="hint" style={{marginTop:4}}>ผู้ใช้จะถูกบังคับเปลี่ยนรหัสผ่านเมื่อ Login ครั้งแรก</div>
        </div>
      )}
      <div className="field">
        <label>บทบาท</label>
        <Segmented value={role} onChange={setRole}
          options={[
            {value:"super",  label:"Super User"},
            {value:"admin",  label:"Group Owner"},
          ]} />
        <div className="hint">
          {role === "super" && "เข้าถึงทุกอย่าง — จัดการบัญชี, ตั้งค่าระบบ, ดู audit log"}
          {role === "admin" && "ดูแลก๊วนของตน — สร้างก๊วน, จัดการผู้เล่น, จับคู่, ดูสถิติ"}
        </div>
        <div className="hint" style={{marginTop: 6, color:"var(--text-3)"}}>
          💡 ผู้ชมไม่ต้องมีบัญชี — ให้แชร์ลิงก์สาธารณะจากหน้า group session แทน
        </div>
      </div>
      <div className="field">
        <label>วันหมดอายุบัญชี (ไม่บังคับ)</label>
        <input type="date" value={expiry} onChange={e => setExpiry(e.target.value)} />
        <div className="hint">เว้นว่างไว้ = ไม่จำกัด</div>
      </div>
    </Modal>
  );
}

Object.assign(window, { UsersScreen });
