/* global React, window, Icon */
const { useState: useDeptState, useEffect: useDeptEffect } = React;

// Circular manager avatar (clickable → profile).
function DeptAvatar({ id, size = 34 }) {
  const [err, setErr] = useDeptState(false);
  const src = (err || !id) ? '/img/avatar-person.svg' : `/faces/${id}.jpg`;
  return <img src={src} alt="" onError={() => setErr(true)}
    onClick={() => id && window.openProfile && window.openProfile(id)} title={id ? 'ดูโปรไฟล์' : ''}
    style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: 'none',
      cursor: id ? 'pointer' : 'default', border: '1px solid var(--line)' }} />;
}

function deptSwatch(c) {
  const cv = c === 'indigo' ? 'primary' : (c || 'coral');
  return { soft: `var(--${cv}-soft)`, ink: `var(--${cv}-ink)`, solid: `var(--${cv})` };
}

// แผนก — CRUD departments + assign a manager (an employee) + a default shift
// that every employee in the department inherits unless they have their own.
function DepartmentPage({ role }) {
  const [depts, setDepts] = useDeptState(window.DEPARTMENTS || []);
  const [editing, setEditing] = useDeptState(null);     // dept obj or {} for new
  const canEdit = role === 'admin' || role === 'hr';

  const reload = async () => {
    const r = await fetch('/api/departments', { credentials: 'include' });
    if (r.ok) { const d = await r.json(); setDepts(d); window.DEPARTMENTS = d; }
  };
  useDeptEffect(() => { reload(); }, []);

  return (
    <div data-screen-label="Department">
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>{window.T.dept} / Departments</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>จัดการ{window.T.dept} · {window.T.boss} · ตารางกะเริ่มต้นของ{window.T.dept}</div>
        </div>
        {canEdit && (
          <button className="gv-btn ok sm" onClick={() => setEditing({})}>
            <Icon name="plus" size={13}/> เพิ่ม{window.T.dept}
          </button>
        )}
      </div>

      {depts.length === 0 ? (
        <div className="gv-card"><div className="gv-empty">ยังไม่มี{window.T.dept} — กด “เพิ่ม{window.T.dept}” เพื่อเริ่ม</div></div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
          {depts.map((d) => {
            const sw = deptSwatch(d.color);
            return (
              <div key={d.id} className="gv-card">
                <div className="gv-card-b">
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 14 }}>
                    <span className="gv-chip" style={{ background: sw.soft, color: sw.ink, fontWeight: 700 }}>{d.name}</span>
                    {canEdit && (
                      <div style={{ display: 'flex', gap: 6 }}>
                        <button className="gv-btn ghost sm" style={{ padding: '6px 9px' }} onClick={() => setEditing(d)} title="แก้ไข">
                          <Icon name="edit" size={14}/>
                        </button>
                        <button className="gv-btn danger sm" style={{ padding: '6px 9px' }}
                          onClick={async () => {
                            const ok = await window.appConfirm({
                              title: `ลบ${window.T.dept} "${d.name}"?`,
                              message: `${window.T.staff}ใน${window.T.dept}จะถูกปลดออกจาก${window.T.dept} (ไม่ลบ${window.T.staff})`,
                              danger: true, confirmText: 'ลบ',
                            });
                            if (!ok) return;
                            await fetch(`/api/departments/${d.id}`, { method: 'DELETE', credentials: 'include' });
                            window.appToast(`ลบ${window.T.dept}แล้ว`, { tone: 'success' });
                            reload();
                          }} title="ลบ">
                          <Icon name="trash" size={14}/>
                        </button>
                      </div>
                    )}
                  </div>
                  {d.description && <div style={{ fontSize: 13, color: 'var(--ink-4)', marginBottom: 14 }}>{d.description}</div>}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <DeptRow icon="users" label={window.T.staff} value={`${d.employee_count || 0} คน`}/>
                    <DeptRow icon="calendar" label="กะเริ่มต้น" value={d.default_shift_name || '— ไม่กำหนด —'}/>
                    <DeptManagerRow id={d.manager_id}/>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {editing && (
        <DeptModal
          dept={editing}
          onClose={() => setEditing(null)}
          onSaved={() => { setEditing(null); reload(); }}
        />
      )}
    </div>
  );
}

function managerName(empId) {
  if (!empId) return null;
  const e = (window.EMPLOYEES || []).find((x) => x.id === empId);
  return e ? `${e.first_name} ${e.last_name || ''}`.trim() : empId;
}

function DeptRow({ icon, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--surface-2)', color: 'var(--ink-4)', display: 'grid', placeItems: 'center', flex: 'none' }}>
        <Icon name={icon} size={13}/>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{label}</div>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{value}</div>
      </div>
    </div>
  );
}

function DeptManagerRow({ id }) {
  const name = managerName(id) || '— ไม่กำหนด —';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {id ? <DeptAvatar id={id} size={30}/> : (
        <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--surface-2)', color: 'var(--ink-4)', display: 'grid', placeItems: 'center', flex: 'none' }}>
          <Icon name="badge" size={13}/>
        </div>
      )}
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{window.T.boss}</div>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{name}</div>
      </div>
    </div>
  );
}

function DeptModal({ dept, onClose, onSaved }) {
  const isNew = !dept.id;
  const [name, setName] = useDeptState(dept.name || '');
  const [desc, setDesc] = useDeptState(dept.description || '');
  const [managerId, setManagerId] = useDeptState(dept.manager_id || '');
  const [shiftId, setShiftId] = useDeptState(dept.default_shift_id || '');
  const [color, setColor] = useDeptState(dept.color || 'coral');
  const [busy, setBusy] = useDeptState(false);
  const [err, setErr] = useDeptState('');

  const save = async () => {
    if (!name.trim()) { setErr(`กรุณาใส่ชื่อ${window.T.dept}`); return; }
    setBusy(true); setErr('');
    try {
      const body = {
        name: name.trim(), description: desc.trim(),
        manager_id: managerId || null,
        default_shift_id: shiftId ? Number(shiftId) : null,
        color,
      };
      const url = isNew ? '/api/departments' : `/api/departments/${dept.id}`;
      const r = await fetch(url, {
        method: isNew ? 'POST' : 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(d.error || `error ${r.status}`);
      window.appToast(isNew ? `เพิ่ม${window.T.dept}แล้ว` : 'บันทึกแล้ว', { tone: 'success' });
      onSaved();
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(15,23,42,.45)', display: 'grid', placeItems: 'center', padding: 20 }}>
      <div className="gv-card" onClick={(e) => e.stopPropagation()} style={{ width: 'min(520px,100%)', maxHeight: '90vh', overflow: 'auto' }}>
        <div className="gv-card-h"><b>{isNew ? `เพิ่ม${window.T.dept}` : `แก้ไข${window.T.dept}`}</b></div>
        <div className="gv-card-b">
          <div className="gv-field">
            <label>ชื่อ{window.T.dept} *</label>
            <input className="gv-input" value={name} autoFocus onChange={(e) => setName(e.target.value)} placeholder="เช่น ฝ่ายการตลาด"/>
          </div>
          <div className="gv-field">
            <label>คำอธิบาย</label>
            <input className="gv-input" value={desc} onChange={(e) => setDesc(e.target.value)}/>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <div className="gv-field" style={{ flex: 1 }}>
              <label>ตารางกะเริ่มต้น</label>
              <select className="gv-select" value={shiftId} onChange={(e) => setShiftId(e.target.value)}>
                <option value="">— ไม่กำหนด —</option>
                {(window.SHIFTS || []).map((s) => (
                  <option key={s.id} value={s.id}>{s.name} ({s.start_time}–{s.end_time})</option>
                ))}
              </select>
            </div>
            <div className="gv-field" style={{ flex: 1 }}>
              <label>ผู้จัดการ</label>
              <select className="gv-select" value={managerId} onChange={(e) => setManagerId(e.target.value)}>
                <option value="">— ไม่กำหนด —</option>
                {(window.EMPLOYEES || []).map((e) => (
                  <option key={e.id} value={e.id}>{e.first_name} {e.last_name}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="gv-field">
            <label>สีประจำแผนก</label>
            <div style={{ display: 'flex', gap: 8 }}>
              {['coral', 'indigo', 'mint', 'yellow', 'cyan', 'magenta'].map((c) => {
                const cv = c === 'indigo' ? 'primary' : c;
                return (
                  <button key={c} type="button" onClick={() => setColor(c)} style={{
                    width: 34, height: 34, borderRadius: 10, background: `var(--${cv})`,
                    border: color === c ? '3px solid var(--ink)' : '3px solid transparent', cursor: 'pointer',
                  }}/>
                );
              })}
            </div>
          </div>
          {err && <div style={{ padding: '10px 14px', borderRadius: 10, background: 'var(--coral-soft)', color: 'var(--coral-ink)', fontSize: 12.5, fontWeight: 600 }}>{err}</div>}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 4 }}>
            <button className="gv-btn no" onClick={onClose} disabled={busy}>ยกเลิก</button>
            <button className="gv-btn ok" onClick={save} disabled={busy}>{busy ? 'กำลังบันทึก…' : 'บันทึก'}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.DepartmentPage = DepartmentPage;
