// OKR ประเมินผล — โครง workflow (ยังไม่มีเนื้อหา objective/key result จริง รอสรุปสูตรคะแนน)
//   HR: ตั้งรอบ + มอบหมายผู้ประเมิน/ผู้อนุมัติต่อพนักงาน (ตั้งใหม่ทุกรอบ) + สร้างแบบประเมิน + ล็อก/ปลดล็อก
//   ทุกคน: งานของตัวเอง — self-assessment (พนักงาน, ไม่บังคับ) / ประเมิน (ผู้ประเมิน) / อนุมัติ (ผู้อนุมัติ)
// ใช้ authFetch จาก org-structure.jsx (โหลดก่อนไฟล์นี้ใน index.html)

const OKR_STATUS_LABEL = {
  drafting: "ร่าง",
  pending_review: "รอทบทวน",
  approved: "อนุมัติแล้ว",
  locked: "ล็อกแล้ว",
};
const OKR_STATUS_CLASS = {
  drafting: "okr-status--drafting",
  pending_review: "okr-status--pending",
  approved: "okr-status--approved",
  locked: "okr-status--locked",
};

function OkrStatusBadge({ status }) {
  return <span className={"okr-status " + (OKR_STATUS_CLASS[status] || "")}>{OKR_STATUS_LABEL[status] || status}</span>;
}

function OkrScreen({ user }) {
  const [periods, setPeriods] = React.useState([]);
  const [periodId, setPeriodId] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [errMsg, setErrMsg] = React.useState("");

  async function loadPeriods(preserveIfStillValid) {
    const list = await (await authFetch("/api/okr/periods")).json();
    const arr = Array.isArray(list) ? list : [];
    setPeriods(arr);
    // เก็บ selection เดิมไว้ถ้ายังมีอยู่จริงในรายการใหม่ — ไม่งั้น (รวมถึงตอนยังไม่เคยเลือกอะไรเลย
    // เช่น สร้างรอบแรกสุด) ค่อย fallback ไปเลือกรอบ active ล่าสุด หรือรอบแรกสุดถ้าไม่มี active เลย
    setPeriodId((prev) => {
      if (preserveIfStillValid && prev && arr.some((p) => p.id === prev)) return prev;
      const active = arr.find((p) => p.status === "active");
      return (active || arr[0] || {}).id || null;
    });
    setLoading(false);
  }
  React.useEffect(() => { loadPeriods(false); }, []);

  if (loading) return <div className="org-page"><p>กำลังโหลด...</p></div>;

  return (
    <div className="org-page">
      <div className="org-toolbar">
        <h2>OKR ประเมินผล</h2>
      </div>
      {errMsg && <div className="error-msg">{errMsg}</div>}

      {user.isHr && (
        <OkrAdminPanel periods={periods} periodId={periodId} setPeriodId={setPeriodId}
          reloadPeriods={() => loadPeriods(true)} setErrMsg={setErrMsg} />
      )}

      <MyTasksPanel user={user} setErrMsg={setErrMsg} />
    </div>
  );
}

// ===== ส่วน HR: ตั้งรอบ + มอบหมายผู้ประเมิน/ผู้อนุมัติ + ภาพรวม =====
function OkrAdminPanel({ periods, periodId, setPeriodId, reloadPeriods, setErrMsg }) {
  const [newName, setNewName] = React.useState("");
  const [newStart, setNewStart] = React.useState("");
  const [newEnd, setNewEnd] = React.useState("");
  const [creating, setCreating] = React.useState(false);

  async function call(url, method, body) {
    setErrMsg("");
    const r = await authFetch(url, { method, body: body ? JSON.stringify(body) : undefined });
    if (!r.ok) {
      const err = await r.json().catch(() => ({}));
      setErrMsg(err.error || "ทำรายการไม่สำเร็จ");
      return null;
    }
    return r.json();
  }

  async function createPeriod() {
    if (!newName.trim()) return;
    const res = await call("/api/okr/periods", "POST", { name: newName, start_date: newStart || null, end_date: newEnd || null });
    if (res) { setNewName(""); setNewStart(""); setNewEnd(""); setCreating(false); reloadPeriods(); }
  }

  async function togglePeriodStatus(p) {
    const res = await call(`/api/okr/periods/${p.id}`, "PATCH", { status: p.status === "active" ? "closed" : "active" });
    if (res) reloadPeriods();
  }

  const currentPeriod = periods.find((p) => p.id === periodId);

  return (
    <section className="okr-admin">
      <h3 className="col-title">รอบประเมิน (HR)</h3>
      <div className="okr-period-bar">
        <select value={periodId || ""} onChange={(e) => setPeriodId(Number(e.target.value))}>
          {periods.length === 0 && <option value="">-- ยังไม่มีรอบ --</option>}
          {periods.map((p) => (
            <option key={p.id} value={p.id}>{p.name}{p.status === "closed" ? " (ปิดแล้ว)" : ""}</option>
          ))}
        </select>
        {currentPeriod && (
          <button className="link-btn" onClick={() => togglePeriodStatus(currentPeriod)}>
            {currentPeriod.status === "active" ? "ปิดรอบนี้" : "เปิดรอบนี้อีกครั้ง"}
          </button>
        )}
        <button className="link-btn" onClick={() => setCreating(!creating)}>+ สร้างรอบใหม่</button>
      </div>

      {creating && (
        <div className="add-inline">
          <input placeholder="ชื่อรอบ เช่น รอบประเมิน 2569 ครึ่งปีหลัง" value={newName}
            onChange={(e) => setNewName(e.target.value)} autoFocus />
          <input type="date" value={newStart} onChange={(e) => setNewStart(e.target.value)} title="วันเริ่ม" />
          <input type="date" value={newEnd} onChange={(e) => setNewEnd(e.target.value)} title="วันสิ้นสุด" />
          <button onClick={createPeriod}>สร้าง</button>
        </div>
      )}

      {currentPeriod && <AssignmentPanel period={currentPeriod} call={call} />}
    </section>
  );
}

function AssignmentPanel({ period, call }) {
  const [rows, setRows] = React.useState([]);
  const [allEmployees, setAllEmployees] = React.useState([]);
  const [evaluations, setEvaluations] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [generating, setGenerating] = React.useState(false);
  const [genMsg, setGenMsg] = React.useState("");

  async function load() {
    setLoading(true);
    const [assignRes, empRes, evalRes] = await Promise.all([
      authFetch(`/api/okr/assignments?period_id=${period.id}`),
      authFetch("/api/employees"),
      authFetch(`/api/okr/evaluations?period_id=${period.id}`),
    ]);
    setRows(await assignRes.json());
    setAllEmployees(await empRes.json());
    setEvaluations(await evalRes.json());
    setLoading(false);
  }
  React.useEffect(() => { load(); }, [period.id]);

  async function setAssignment(employeeId, evaluatorId, approverId) {
    if (!evaluatorId || !approverId) return;
    const res = await call("/api/okr/assignments", "POST", {
      period_id: period.id, employee_id: employeeId, evaluator_id: Number(evaluatorId), approver_id: Number(approverId),
    });
    if (res) load();
  }

  async function generate() {
    setGenerating(true);
    setGenMsg("");
    const res = await call(`/api/okr/periods/${period.id}/generate`, "POST", {});
    setGenerating(false);
    if (res) { setGenMsg(`สร้าง/อัปเดตแบบประเมินแล้ว ${res.created} ชุดใหม่`); load(); }
  }

  async function lockEval(id) { if (await call(`/api/okr/evaluations/${id}/lock`, "POST", {})) load(); }
  async function unlockEval(id) { if (await call(`/api/okr/evaluations/${id}/unlock`, "POST", {})) load(); }

  if (loading) return <p className="muted small">กำลังโหลด...</p>;
  const assignedCount = rows.filter((r) => r.evaluator_id).length;
  const closed = period.status === "closed";

  return (
    <React.Fragment>
      <h4 className="unassigned-title">มอบหมายผู้ประเมิน/ผู้อนุมัติ</h4>
      <p className="muted small">มอบหมายแล้ว {assignedCount}/{rows.length} คน{closed ? " — รอบนี้ปิดแล้ว แก้ไขไม่ได้" : ""}</p>
      <div className="table-scroll">
        <table className="org-table">
          <thead>
            <tr><th>พนักงาน</th><th>ตำแหน่ง</th><th>ผู้ประเมิน</th><th>ผู้อนุมัติ</th></tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <AssignmentRow key={r.employee_id} row={r} employees={allEmployees} disabled={closed}
                onSave={(evId, apId) => setAssignment(r.employee_id, evId, apId)} />
            ))}
          </tbody>
        </table>
      </div>

      <div className="okr-generate-bar">
        <button onClick={generate} disabled={generating || closed}>
          {generating ? "กำลังสร้าง..." : "สร้าง/อัปเดตแบบประเมินจากรายชื่อที่มอบหมายแล้ว"}
        </button>
        {genMsg && <span className="muted small">{genMsg}</span>}
      </div>

      <h4 className="unassigned-title">ภาพรวมแบบประเมินรอบนี้ ({evaluations.length})</h4>
      {evaluations.length === 0 ? (
        <p className="muted small">ยังไม่มีแบบประเมิน — มอบหมายแล้วกดปุ่มสร้างด้านบน</p>
      ) : (
        <div className="table-scroll">
          <table className="org-table">
            <thead><tr><th>พนักงาน</th><th>ผู้ประเมิน</th><th>ผู้อนุมัติ</th><th>สถานะ</th><th></th></tr></thead>
            <tbody>
              {evaluations.map((e) => (
                <tr key={e.id}>
                  <td>{e.employee_name}</td>
                  <td>{e.evaluator_name}</td>
                  <td>{e.approver_name}</td>
                  <td><OkrStatusBadge status={e.status} /></td>
                  <td className="row-actions">
                    {e.status === "approved" && <button className="link-btn" onClick={() => lockEval(e.id)}>ล็อก</button>}
                    {e.status === "locked" && <button className="link-btn danger" onClick={() => unlockEval(e.id)}>ปลดล็อก</button>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </React.Fragment>
  );
}

function AssignmentRow({ row, employees, disabled, onSave }) {
  const [evaluatorId, setEvaluatorId] = React.useState(row.evaluator_id ? String(row.evaluator_id) : "");
  const [approverId, setApproverId] = React.useState(row.approver_id ? String(row.approver_id) : "");
  const options = employees.filter((e) => e.id !== row.employee_id);

  return (
    <tr>
      <td>{row.full_name}</td>
      <td>{row.position || "-"}</td>
      <td>
        <select value={evaluatorId} disabled={disabled}
          onChange={(e) => { setEvaluatorId(e.target.value); onSave(e.target.value, approverId); }}>
          <option value="">-- เลือกผู้ประเมิน --</option>
          {options.map((e) => <option key={e.id} value={e.id}>{e.full_name}{e.position ? " · " + e.position : ""}</option>)}
        </select>
      </td>
      <td>
        <select value={approverId} disabled={disabled}
          onChange={(e) => { setApproverId(e.target.value); onSave(evaluatorId, e.target.value); }}>
          <option value="">-- เลือกผู้อนุมัติ --</option>
          {options.map((e) => <option key={e.id} value={e.id}>{e.full_name}{e.position ? " · " + e.position : ""}</option>)}
        </select>
      </td>
    </tr>
  );
}

// ===== ส่วน "งานของฉัน" — ทุก role เห็น (กรองจาก employeeId ของบัญชีตัวเอง) =====
function MyTasksPanel({ user, setErrMsg }) {
  const [evaluations, setEvaluations] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [expandedId, setExpandedId] = React.useState(null);

  async function load() {
    setLoading(true);
    const list = await (await authFetch("/api/okr/evaluations")).json();
    setEvaluations(Array.isArray(list) ? list : []);
    setLoading(false);
  }
  React.useEffect(() => { load(); }, []);

  const myEmpId = user.employeeId;

  if (loading) return <section className="okr-mytasks"><h3 className="col-title">งานประเมินของฉัน</h3><p className="muted small">กำลังโหลด...</p></section>;

  if (!myEmpId) {
    return (
      <section className="okr-mytasks">
        <h3 className="col-title">งานประเมินของฉัน</h3>
        <p className="muted small">บัญชีนี้ยังไม่ได้ผูกกับข้อมูลพนักงาน — ติดต่อ HR ให้ผูกบัญชีกับรายชื่อพนักงานก่อน</p>
      </section>
    );
  }

  const asEvaluator = evaluations.filter((e) => e.evaluator_id === myEmpId);
  const asApprover = evaluations.filter((e) => e.approver_id === myEmpId);
  const asEmployee = evaluations.filter((e) => e.employee_id === myEmpId);
  const groupProps = { myEmpId, expandedId, setExpandedId, reload: load, setErrMsg };

  return (
    <section className="okr-mytasks">
      <h3 className="col-title">งานประเมินของฉัน</h3>
      {asEvaluator.length === 0 && asApprover.length === 0 && asEmployee.length === 0 ? (
        <p className="muted small">ยังไม่มีงานที่เกี่ยวข้องกับคุณในตอนนี้</p>
      ) : (
        <React.Fragment>
          {asEvaluator.length > 0 && <TaskGroup title="ต้องประเมิน" items={asEvaluator} role="evaluator" {...groupProps} />}
          {asApprover.length > 0 && <TaskGroup title="ต้องทบทวน/อนุมัติ" items={asApprover} role="approver" {...groupProps} />}
          {asEmployee.length > 0 && <TaskGroup title="แบบประเมินของฉัน" items={asEmployee} role="employee" {...groupProps} />}
        </React.Fragment>
      )}
    </section>
  );
}

function TaskGroup({ title, items, role, myEmpId, expandedId, setExpandedId, reload, setErrMsg }) {
  return (
    <React.Fragment>
      <h4 className="unassigned-title">{title} ({items.length})</h4>
      <div className="chart-tree">
        {items.map((e) => {
          const key = role + "-" + e.id;
          return (
            <div className="node node-line" key={e.id}>
              <div className="node-head">
                <button className="node-toggle" onClick={() => setExpandedId(expandedId === key ? null : key)}
                  title={expandedId === key ? "หุบ" : "กาง"}>
                  {expandedId === key ? "▼" : "▶"}
                </button>
                <span className="node-tag line">{e.period_name}</span>
                <strong>{e.employee_name}</strong>
                <span className="node-actions"><OkrStatusBadge status={e.status} /></span>
              </div>
              {expandedId === key && (
                <EvalDetail evalId={e.id} role={role} myEmpId={myEmpId} reload={reload} setErrMsg={setErrMsg} />
              )}
            </div>
          );
        })}
      </div>
    </React.Fragment>
  );
}

function EvalDetail({ evalId, role, myEmpId, reload, setErrMsg }) {
  const [detail, setDetail] = React.useState(null);
  const [selfNote, setSelfNote] = React.useState("");
  const [evalNote, setEvalNote] = React.useState("");
  const [rejectReason, setRejectReason] = React.useState("");
  const [showReject, setShowReject] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  async function load() {
    const d = await (await authFetch(`/api/okr/evaluations/${evalId}`)).json();
    setDetail(d);
    setSelfNote(d.self_assessment_note || "");
    setEvalNote(d.evaluator_note || "");
  }
  React.useEffect(() => { load(); }, [evalId]);

  async function call(url, method, body) {
    setErrMsg(""); setBusy(true);
    const r = await authFetch(url, { method, body: body ? JSON.stringify(body) : undefined });
    setBusy(false);
    if (!r.ok) {
      const err = await r.json().catch(() => ({}));
      setErrMsg(err.error || "ทำรายการไม่สำเร็จ");
      return false;
    }
    return true;
  }

  async function saveSelf() { if (await call(`/api/okr/evaluations/${evalId}`, "PATCH", { self_assessment_note: selfNote })) load(); }
  async function saveEval() { if (await call(`/api/okr/evaluations/${evalId}`, "PATCH", { evaluator_note: evalNote })) load(); }
  async function submit() { if (await call(`/api/okr/evaluations/${evalId}/submit`, "POST", {})) { load(); reload(); } }
  async function approve() { if (await call(`/api/okr/evaluations/${evalId}/review`, "POST", { action: "approve" })) { load(); reload(); } }
  async function reject() {
    if (!rejectReason.trim()) { setErrMsg("กรุณาระบุเหตุผลที่ตีกลับ"); return; }
    if (await call(`/api/okr/evaluations/${evalId}/review`, "POST", { action: "reject", reason: rejectReason })) {
      setShowReject(false); setRejectReason(""); load(); reload();
    }
  }

  if (!detail) return <div className="node-children"><p className="muted small">กำลังโหลด...</p></div>;

  const canEditSelf = role === "employee" && myEmpId === detail.employee_id && detail.status === "drafting";
  const canEditEval = role === "evaluator" && myEmpId === detail.evaluator_id && detail.status === "drafting";
  const canReview = role === "approver" && myEmpId === detail.approver_id && detail.status === "pending_review";

  return (
    <div className="node-children okr-detail">
      {detail.review_action === "rejected" && detail.reject_reason && (
        <div className="error-msg">ถูกตีกลับล่าสุด: {detail.reject_reason}</div>
      )}
      <label className="okr-field">
        <span>การประเมินตนเอง (พนักงานกรอกเอง — ไม่บังคับ)</span>
        <textarea rows={3} value={selfNote} disabled={!canEditSelf}
          onChange={(e) => setSelfNote(e.target.value)} placeholder="ยังไม่ได้กรอก" />
      </label>
      {canEditSelf && <button className="link-btn" onClick={saveSelf} disabled={busy}>บันทึกการประเมินตนเอง</button>}

      <label className="okr-field">
        <span>ความเห็น/คะแนนจากผู้ประเมิน</span>
        <textarea rows={3} value={evalNote} disabled={!canEditEval}
          onChange={(e) => setEvalNote(e.target.value)} placeholder="ยังไม่ได้กรอก" />
      </label>
      {canEditEval && (
        <div className="okr-detail-actions">
          <button className="link-btn" onClick={saveEval} disabled={busy}>บันทึกร่าง</button>
          <button onClick={submit} disabled={busy}>ส่งต่อผู้อนุมัติ</button>
        </div>
      )}

      {canReview && (
        <div className="okr-detail-actions">
          <button onClick={approve} disabled={busy}>อนุมัติ</button>
          <button className="link-btn danger" onClick={() => setShowReject(!showReject)}>ตีกลับ</button>
        </div>
      )}
      {showReject && (
        <div className="add-inline">
          <input placeholder="เหตุผลที่ตีกลับ" value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} autoFocus />
          <button onClick={reject} disabled={busy}>ยืนยันตีกลับ</button>
        </div>
      )}
    </div>
  );
}
