// Employees page

const EmployeesPage = ({ data, refresh }) => {
  const [search, setSearch] = React.useState('');
  const [editingEmp, setEditingEmp] = React.useState(null);
  const [addingEmp, setAddingEmp] = React.useState(false);
  const [resettingEmp, setResettingEmp] = React.useState(null);

  let list = data.employees;
  if (search) {
    const s = search.toLowerCase();
    list = list.filter(e => e.name.toLowerCase().includes(s) || e.nameEn.toLowerCase().includes(s) || e.role.toLowerCase().includes(s));
  }

  // Compute leave used per employee
  const usedMap = {};
  data.leaves.filter(l => l.status === 'approved').forEach(l => {
    if (!usedMap[l.empId]) usedMap[l.empId] = { vacation: 0, personal: 0, sick: 0 };
    usedMap[l.empId][l.type] = (usedMap[l.empId][l.type] || 0) + l.days;
  });

  return (
    <div data-screen-label="Employees">
      <div className="row between mb-3">
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-.02em' }}>พนักงานทั้งหมด</div>
          <div className="text-sm muted">{data.employees.length} คน · {new Set(data.employees.map(e => e.dept)).size} แผนก</div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <div className="search" style={{ width: 240 }}>
            <Icon name="search" size={14}/>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="ค้นหา..."/>
          </div>
          <button className="btn btn-primary" onClick={() => setAddingEmp(true)}><Icon name="plus" size={14}/> เพิ่มพนักงาน</button>
        </div>
      </div>

      <div className="card">
        <table className="t">
          <thead>
            <tr>
              <th>พนักงาน</th>
              <th>ตำแหน่ง</th>
              <th>แผนก</th>
              <th>Login</th>
              <th className="num">พักร้อนใช้</th>
              <th className="num">ลากิจ</th>
              <th className="num">ลาป่วย</th>
              <th className="num">หยุดพิเศษ</th>
              <th>สถานะวันนี้</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {list.map(e => {
              const used = usedMap[e.id] || { vacation: 0, personal: 0, sick: 0 };
              return (
                <tr key={e.id}>
                  <td>
                    <div className="row" style={{ gap: 10 }}>
                      <span className="avatar" style={{ background: e.color, width: 32, height: 32, fontSize: 11 }}>{e.avatar}</span>
                      <div>
                        <div style={{ fontWeight: 500 }}>{e.name}</div>
                        <div className="text-xs muted">{e.nameEn}</div>
                      </div>
                    </div>
                  </td>
                  <td className="text-sm">{e.role}</td>
                  <td><span className="chip">{e.dept}</span></td>
                  <td className="text-sm muted" style={{ fontFamily: 'var(--font-mono)' }}>{e.email || (e.nameEn ? e.nameEn.toLowerCase().split(' ')[0] + '@example.com' : '—')}</td>
                  <td className="num">
                    <span>{used.vacation}</span> <span className="muted text-xs">/ {data.settings.leaveQuota.vacation}</span>
                  </td>
                  <td className="num">
                    <span>{used.personal}</span> <span className="muted text-xs">/ {data.settings.leaveQuota.personal}</span>
                  </td>
                  <td className="num">
                    <span>{used.sick}</span> <span className="muted text-xs">/ {data.settings.leaveQuota.sick}</span>
                  </td>
                  <td className="num">
                    <span className="chip chip-special"><Icon name="star" size={10}/>{(data.settings.perEmployeeSpecial?.[e.id] ?? e.specialOffMonthly ?? data.settings.specialOffPerMonth)} วัน/ด.</span>
                  </td>
                  <td>
                    <span className="chip chip-approved"><span className="chip-dot"/>ทำงานปกติ</span>
                  </td>
                  <td>
                    <div className="row" style={{ gap: 2 }}>
                      <button className="icon-btn" style={{ width: 28, height: 28 }} title="รีเซ็ตรหัสผ่าน" onClick={() => setResettingEmp(e)}><Icon name="lock" size={14}/></button>
                      <button className="icon-btn" style={{ width: 28, height: 28 }} title="แก้ไข" onClick={() => setEditingEmp(e)}><Icon name="edit" size={14}/></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {(addingEmp || editingEmp) && (
        <EmployeeModal
          employee={editingEmp}
          onClose={() => { setAddingEmp(false); setEditingEmp(null); }}
          data={data}
          refresh={refresh}
        />
      )}

      {resettingEmp && (
        <ResetPasswordModal emp={resettingEmp} onClose={() => setResettingEmp(null)}/>
      )}
    </div>
  );
};

window.EmployeesPage = EmployeesPage;

// ───── Reset Password Modal (admin) ─────
const ResetPasswordModal = ({ emp, onClose }) => {
  const [pw, setPw] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [done, setDone] = React.useState(null);

  const gen = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
    let s = '';
    for (let i = 0; i < 10; i++) s += chars[Math.floor(Math.random() * chars.length)];
    setPw(s);
  };

  const submit = async () => {
    setErr(null); setBusy(true);
    try {
      const res = await window.API.resetEmployeePassword(emp.id, pw);
      setDone(res.newPassword);
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <div className="modal-header">
          <div>
            <div className="modal-title">รีเซ็ตรหัสผ่าน</div>
            <div className="text-xs muted mt-2">{emp.name} · {emp.email}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          {done ? (
            <div style={{ background:'var(--swap-bg)', padding:14, borderRadius:8 }}>
              <div className="text-sm" style={{ color:'var(--swap)', fontWeight:600, marginBottom:8 }}>
                <Icon name="check" size={14}/> รีเซ็ตเรียบร้อย — แจ้งรหัสนี้กับพนักงาน
              </div>
              <div style={{ fontFamily:'var(--font-mono)', fontSize:16, fontWeight:700, padding:'10px 14px', background:'white', borderRadius:6, border:'1px solid var(--ink-200)', userSelect:'all' }}>
                {done}
              </div>
              <div className="text-xs muted mt-2">session ทั้งหมดของพนักงานนี้ถูก logout แล้ว · ต้องล็อกอินใหม่ด้วยรหัสนี้</div>
            </div>
          ) : (<>
            <div className="row" style={{ gap:10, padding:12, background:'#fef3c7', borderRadius:8, marginBottom:14 }}>
              <Icon name="alert" size={16} style={{ color:'#92400e' }}/>
              <div className="text-xs" style={{ color:'#92400e' }}>
                การรีเซ็ตจะแทนรหัสผ่านเดิมและ logout ทุก session ของพนักงานคนนี้ทันที
              </div>
            </div>
            <div className="field">
              <label>รหัสผ่านใหม่ (เว้นว่างเพื่อใช้ค่าเริ่มต้น <code>password123</code>)</label>
              <div className="row" style={{ gap:6 }}>
                <input type="text" value={pw} onChange={e => setPw(e.target.value)} placeholder="ตั้งเอง หรือกด สุ่ม" style={{ flex:1, fontFamily:'var(--font-mono)' }}/>
                <button className="btn btn-ghost btn-sm" type="button" onClick={gen}><Icon name="sparkle" size={12}/> สุ่ม</button>
              </div>
              {pw && pw.length < 6 && <div className="field-help" style={{ color:'var(--sick)' }}>สั้นเกินไป — ต้อง ≥ 6 ตัวอักษร</div>}
            </div>
            {err && <div style={{ background:'#fef2f2', color:'#b91c1c', padding:'8px 12px', borderRadius:8, fontSize:12 }}>{err}</div>}
          </>)}
        </div>
        <div className="modal-footer">
          {done ? (
            <button className="btn btn-primary" onClick={onClose}>เสร็จสิ้น</button>
          ) : (<>
            <button className="btn btn-ghost" onClick={onClose} disabled={busy}>ยกเลิก</button>
            <button className="btn btn-danger" disabled={busy || (pw && pw.length < 6)} onClick={submit}>
              <Icon name="lock" size={14}/> {busy ? 'กำลังรีเซ็ต…' : 'ยืนยันรีเซ็ต'}
            </button>
          </>)}
        </div>
      </div>
    </div>
  );
};

window.ResetPasswordModal = ResetPasswordModal;

// ───── Add / Edit Employee Modal ─────
const EmployeeModal = ({ employee, onClose, data, refresh }) => {
  const isEdit = !!employee;
  const [name, setName] = React.useState(employee?.name || '');
  const [nameEn, setNameEn] = React.useState(employee?.nameEn || '');
  const [role, setRole] = React.useState(employee?.role || '');
  const [dept, setDept] = React.useState(employee?.dept || 'Sales');
  const [email, setEmail] = React.useState(employee?.email || '');
  const [password, setPassword] = React.useState('');
  const [specialOff, setSpecialOff] = React.useState(employee?.specialOffMonthly ?? data.settings.specialOffPerMonth);
  const [color, setColor] = React.useState(employee?.color || '#2563eb');
  const [busy, setBusy] = React.useState(false);

  const save = async () => {
    setBusy(true);
    try {
      const payload = { name, nameEn, role, dept, email, color, specialOffMonthly: specialOff };
      if (password) payload.password = password;
      if (isEdit) {
        await window.API.updateEmployee(employee.id, payload);
      } else {
        if (!password) payload.password = 'password123';
        await window.API.createEmployee(payload);
      }
      if (refresh) await refresh();
      onClose();
    } catch (e) { alert(e.message); setBusy(false); }
  };

  const doDelete = async () => {
    if (!confirm(`ต้องการลบ ${name} จริงหรือไม่?`)) return;
    setBusy(true);
    try {
      await window.API.deleteEmployee(employee.id);
      if (refresh) await refresh();
      onClose();
    } catch (e) { alert(e.message); setBusy(false); }
  };

  const COLORS = ['#1e40af','#2563eb','#0d9488','#7c3aed','#dc2626','#ea580c','#c026d3','#0891b2','#65a30d','#9333ea','#475569','#be185d'];
  const DEPTS = ['Management','Warehouse','Sales','Marketing','Finance'];
  const avatar = (name || 'NA').split(' ').map(s => s[0]).join('').slice(0, 2).toUpperCase();

  const canSave = name.trim() && email.trim() && (isEdit || password || true);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 560 }}>
        <div className="modal-header">
          <div>
            <div className="modal-title">{isEdit ? 'แก้ไขพนักงาน' : 'เพิ่มพนักงานใหม่'}</div>
            <div className="text-xs muted mt-2">{isEdit ? 'แก้ไขข้อมูลส่วนตัวและสิทธิ์การลา' : 'สร้าง Account สำหรับพนักงานใหม่ · ระบบจะส่ง link ยืนยันทางอีเมล'}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          {/* Preview */}
          <div className="row" style={{ gap: 12, padding: 14, background: 'var(--ink-50)', borderRadius: 8, marginBottom: 16 }}>
            <span className="avatar" style={{ background: color, width: 48, height: 48, fontSize: 16 }}>{avatar}</span>
            <div>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{name || 'ชื่อพนักงาน'}</div>
              <div className="text-xs muted">{role || 'ตำแหน่ง'} · {dept}</div>
            </div>
          </div>

          <div className="field-row">
            <div className="field">
              <label>ชื่อ-สกุล (ไทย)</label>
              <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="เช่น สมชาย ใจดี"/>
            </div>
            <div className="field">
              <label>ชื่อภาษาอังกฤษ</label>
              <input type="text" value={nameEn} onChange={e => setNameEn(e.target.value)} placeholder="e.g. Somchai Jaidee"/>
            </div>
          </div>

          <div className="field-row">
            <div className="field">
              <label>ตำแหน่ง</label>
              <input type="text" value={role} onChange={e => setRole(e.target.value)} placeholder="เช่น Pack & Ship, Customer Care"/>
            </div>
            <div className="field">
              <label>แผนก</label>
              <select value={dept} onChange={e => setDept(e.target.value)}>
                {DEPTS.map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </div>
          </div>

          <div className="field">
            <label>Email (ใช้ Login)</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="name@example.com"/>
          </div>

          <div className="field">
            <label>รหัสผ่าน {isEdit && <span className="text-xs muted">(เว้นว่างเพื่อไม่เปลี่ยน)</span>}</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder={isEdit ? 'กรอกเฉพาะถ้าต้องการรีเซ็ตรหัสผ่าน' : 'ค่าเริ่มต้น: password123'}/>
          </div>

          <div className="field">
            <label>สีอวาตาร์</label>
            <div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
              {COLORS.map(c => (
                <button
                  key={c}
                  type="button"
                  onClick={() => setColor(c)}
                  style={{
                    width: 30, height: 30,
                    borderRadius: '50%',
                    background: c,
                    border: color === c ? '3px solid var(--ink-900)' : '2px solid white',
                    boxShadow: color === c ? '0 0 0 1px var(--ink-300)' : '0 1px 3px rgba(0,0,0,.1)',
                    cursor: 'pointer',
                  }}
                />
              ))}
            </div>
          </div>

          <div className="field">
            <label>วันหยุดพิเศษ / เดือน</label>
            <div className="row" style={{ gap: 6 }}>
              {[0, 1, 2, 3, 4].map(n => (
                <button
                  key={n}
                  type="button"
                  onClick={() => setSpecialOff(n)}
                  style={{
                    width: 36, height: 36,
                    borderRadius: 7,
                    border: specialOff === n ? '2px solid var(--brand-600)' : '1px solid var(--ink-200)',
                    background: specialOff === n ? 'var(--brand-50)' : 'var(--paper)',
                    color: specialOff === n ? 'var(--brand-700)' : 'var(--ink-600)',
                    fontWeight: 600,
                    fontSize: 13,
                    fontFamily: 'var(--font-en)',
                  }}
                >{n}</button>
              ))}
              <span className="text-xs muted" style={{ marginLeft: 6, alignSelf: 'center' }}>วัน/เดือน</span>
            </div>
            <div className="field-help">ปรับได้ภายหลังที่หน้า ตั้งค่าระบบ → tab วันทำงาน</div>
          </div>
        </div>
        <div className="modal-footer">
          {isEdit && (
            <button className="btn btn-danger btn-sm" style={{ marginRight: 'auto' }} onClick={doDelete} disabled={busy}>
              <Icon name="trash" size={13}/> ลบพนักงาน
            </button>
          )}
          <button className="btn btn-ghost" onClick={onClose} disabled={busy}>ยกเลิก</button>
          <button className="btn btn-primary" disabled={!canSave || busy} onClick={save}>
            <Icon name="check" size={14}/> {busy ? 'กำลังบันทึก…' : (isEdit ? 'บันทึก' : 'เพิ่มพนักงาน')}
          </button>
        </div>
      </div>
    </div>
  );
};

window.EmployeeModal = EmployeeModal;
