/* global React, I, UI, SSSData */
// =============== KPI ประเมินผลพนักงาน ===============
// รวม ขาด/ลา/มาสาย (จากลงเวลา) + คะแนนงานจากใบประเมินงาน → คำนวณโบนัสรายเดือนอัตโนมัติ
const { useState: useStateKP, useEffect: useEffectKP } = React;

const KPI_MONTHS = [
  { key: "2569-06", label: "มิถุนายน 2569", th: "มิ.ย.", days: 10 },
  { key: "2569-05", label: "พฤษภาคม 2569", th: "พ.ค.", days: 25 },
  { key: "2569-04", label: "เมษายน 2569", th: "เม.ย.", days: 24 }
];

// ขาด/ลา/สาย ต่อเดือน (จากระบบลงเวลา — ตัวอย่าง)
const KPI_ATT = {
  "2569-05": {
    "EMP-005": { absent: 0, leave: 1, late: 1 },
    "EMP-009": { absent: 0, leave: 0, late: 0 },
    "EMP-012": { absent: 0, leave: 0, late: 2 },
    "EMP-013": { absent: 1, leave: 0, late: 4 },
    "EMP-018": { absent: 0, leave: 0, late: 0 },
    "EMP-021": { absent: 0, leave: 1, late: 0 },
    "EMP-024": { absent: 0, leave: 0, late: 0 },
    "EMP-027": { absent: 1, leave: 1, late: 1 },
    "EMP-030": { absent: 2, leave: 0, late: 3 }
  },
  "2569-04": {
    "EMP-005": { absent: 0, leave: 0, late: 2 },
    "EMP-009": { absent: 0, leave: 1, late: 0 },
    "EMP-012": { absent: 0, leave: 0, late: 1 },
    "EMP-013": { absent: 0, leave: 2, late: 2 },
    "EMP-018": { absent: 0, leave: 0, late: 0 },
    "EMP-021": { absent: 1, leave: 0, late: 0 },
    "EMP-024": { absent: 0, leave: 1, late: 1 },
    "EMP-027": { absent: 0, leave: 0, late: 0 },
    "EMP-030": { absent: 1, leave: 1, late: 5 }
  },
  "2569-06": {
    "EMP-005": { absent: 0, leave: 0, late: 0 },
    "EMP-009": { absent: 0, leave: 0, late: 0 },
    "EMP-012": { absent: 0, leave: 0, late: 1 },
    "EMP-013": { absent: 0, leave: 1, late: 1 },
    "EMP-018": { absent: 0, leave: 0, late: 0 },
    "EMP-021": { absent: 0, leave: 0, late: 0 },
    "EMP-024": { absent: 0, leave: 0, late: 0 },
    "EMP-027": { absent: 0, leave: 0, late: 0 },
    "EMP-030": { absent: 1, leave: 0, late: 1 }
  }
};

// คะแนนงานเฉลี่ยตั้งต้น (กรณียังไม่มีใบประเมินงานจริงของเดือนนั้น)
const KPI_WORK_SEED = {
  "EMP-005": 4.4, "EMP-009": 4.7, "EMP-012": 4.5, "EMP-013": 3.8,
  "EMP-018": 4.6, "EMP-021": 4.8, "EMP-024": 4.3, "EMP-027": 4.0, "EMP-030": 3.4
};

function kpiGrade(total) {
  if (total >= 90) return { g: "A", tone: "success", pct: 1 };
  if (total >= 80) return { g: "B", tone: "info", pct: 0.75 };
  if (total >= 70) return { g: "C", tone: "warning", pct: 0.5 };
  return { g: "D", tone: "danger", pct: 0 };
}

function KPIBar({ value, max, color }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 110 }}>
      <div style={{ flex: 1, height: 6, background: "var(--surface-3)", borderRadius: 999, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${pct}%`, background: color, borderRadius: 999 }} />
      </div>
      <span className="amount" style={{ fontSize: 12.5, fontWeight: 600, minWidth: 36, textAlign: "right" }}>{value.toFixed(1)}</span>
    </div>
  );
}

function KPIPage({ navigate }) {
  const D = window.SSSData;
  const { Btn, Badge, Card, PageHead, Stat, fmt0 } = window.UI;
  const [month, setMonth] = useStateKP("2569-05");
  const [bonusBase, setBonusBase] = useStateKP(3000);
  const [diligence, setDiligence] = useStateKP(500);
  const [, force] = useStateKP(0);
  useEffectKP(() => {
    const h = () => force(n => n + 1);
    window.addEventListener("sss-evals-changed", h);
    return () => window.removeEventListener("sss-evals-changed", h);
  }, []);

  const mo = KPI_MONTHS.find(m => m.key === month);
  const emps = (D.Employees || []).filter(e => e.id !== "EMP-001");

  // ใบประเมินงานจริงของเดือนนี้ (จาก WorkEvalStore)
  const evals = (window.WorkEvalStore ? window.WorkEvalStore.load() : [])
    .filter(ev => ev.date.includes(mo.th) && ev.date.includes("2569"));

  const rows = emps.map(e => {
    const att = (KPI_ATT[month] || {})[e.id] || { absent: 0, leave: 0, late: 0 };
    // คะแนนขยัน (เต็ม 50): หัก ขาด -5 · สาย -1.5 · ลา -1
    const attend = Math.max(0, Math.min(50, 50 - att.absent * 5 - att.late * 1.5 - att.leave * 1));
    // คะแนนงาน (เต็ม 50): เฉลี่ยจากใบประเมินงาน (1-5) × 10
    const myScores = [];
    evals.forEach(ev => ev.rows.forEach(r => { if (r.empId === e.id || r.name === e.name) myScores.push(r.score); }));
    const evalAvg = myScores.length ? myScores.reduce((s, x) => s + x, 0) / myScores.length : (KPI_WORK_SEED[e.id] || 3.5);
    const work = Math.min(50, evalAvg * 10);
    const total = attend + work;
    const grade = kpiGrade(total);
    const perfect = att.absent === 0 && att.late === 0 && att.leave === 0;
    const bonus = Math.round(bonusBase * grade.pct + (perfect ? +diligence : 0));
    return { emp: e, att, attend, work, evalAvg, evalCount: myScores.length, total, grade, perfect, bonus };
  }).sort((a, b) => b.total - a.total);

  const perfectCount = rows.filter(r => r.perfect).length;
  const avgTotal = rows.reduce((s, r) => s + r.total, 0) / (rows.length || 1);
  const bonusSum = rows.reduce((s, r) => s + r.bonus, 0);

  const exportCSV = () => {
    window.exportRowsCSV && window.exportRowsCSV(`kpi-${month}`, [
      { key: "name", label: "พนักงาน" }, { key: "role", label: "ตำแหน่ง" },
      { key: "absent", label: "ขาด" }, { key: "leave", label: "ลา" }, { key: "late", label: "สาย" },
      { key: "attend", label: "คะแนนขยัน (50)" }, { key: "work", label: "คะแนนงาน (50)" },
      { key: "total", label: "รวม (100)" }, { key: "grade", label: "เกรด" }, { key: "bonus", label: "โบนัสแนะนำ" }
    ], rows.map(r => ({ name: r.emp.name, role: r.emp.role, absent: r.att.absent, leave: r.att.leave, late: r.att.late, attend: r.attend.toFixed(1), work: r.work.toFixed(1), total: r.total.toFixed(1), grade: r.grade.g, bonus: r.bonus })));
    window.toast && window.toast("ส่งออกรายงาน KPI แล้ว");
  };

  const postBonus = async () => {
    const ok = await window.confirmDialog({
      title: "บันทึกโบนัสเข้ารอบเงินเดือน",
      message: `นำโบนัสแนะนำของ <b>${mo.label}</b> รวม <b>฿${fmt0(bonusSum)}</b> (${rows.length} คน) เข้ารอบคำนวณเงินเดือน`,
      bullets: [
        `เกรด A ได้โบนัสเต็ม ฿${fmt0(bonusBase)} · B 75% · C 50% · D ไม่ได้`,
        `เบี้ยขยัน ฿${fmt0(+diligence)} สำหรับคนมาครบ ไม่ขาด ไม่ลา ไม่สาย (${perfectCount} คน)`,
        "แสดงในสลิปเงินเดือนงวดถัดไป"
      ],
      confirmText: "บันทึกโบนัส"
    });
    if (!ok) return;
    window.logActivity && window.logActivity("บันทึกโบนัส KPI", `${mo.label} รวม ฿${fmt0(bonusSum)} (${rows.length} คน)`, "approve");
    window.toast && window.toast(`บันทึกโบนัส ${mo.label} รวม ฿${fmt0(bonusSum)} เข้ารอบเงินเดือนแล้ว`);
  };

  return (
    <>
      <PageHead
        title="KPI ประเมินผลพนักงาน"
        sub="รวมการ ขาด · ลา · มาสาย จากระบบลงเวลา + คะแนนงานจากใบประเมินงาน → คำนวณโบนัสอัตโนมัติ"
        right={<>
          <select className="input" style={{ width: 170, height: 34 }} value={month} onChange={e => setMonth(e.target.value)}>
            {KPI_MONTHS.map(m => <option key={m.key} value={m.key}>{m.label}</option>)}
          </select>
          <Btn icon={I.download} kind="ghost" onClick={exportCSV}>ส่งออก Excel</Btn>
          <Btn icon={I.check} kind="primary" onClick={postBonus}>บันทึกโบนัสเข้าเงินเดือน</Btn>
        </>}
      />

      <div className="grid cols-4 mb-lg">
        <Stat label="มาครบ ไม่ขาด-ลา-สาย" value={`${perfectCount} คน`} sub={`ได้เบี้ยขยัน ฿${fmt0(+diligence)}/คน`} icon={I.check} />
        <Stat label="คะแนนเฉลี่ยทีม" value={avgTotal.toFixed(1)} sub="จากเต็ม 100 คะแนน" icon={I.sparkle} />
        <Stat label="ใบประเมินงานเดือนนี้" value={`${evals.length} ใบ`} sub={evals.length ? "ดึงคะแนนเข้า KPI แล้ว" : "ยังไม่มี — ใช้คะแนนเฉลี่ยสะสม"} icon={I.doc} />
        <Stat label="โบนัสรวมที่แนะนำ" value={`฿${fmt0(bonusSum)}`} sub={`${rows.length} คน · ${mo.label}`} icon={I.money} />
      </div>

      <Card className="mb-lg" padded={false} flush>
        <div style={{ padding: "10px 14px", display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap", fontSize: 12.5 }}>
          <b>เกณฑ์โบนัส:</b>
          <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
            โบนัสฐาน ฿<input className="input" type="number" min="0" step="500" value={bonusBase} onChange={e => setBonusBase(+e.target.value || 0)} style={{ width: 90, height: 28 }}></input>
          </span>
          <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
            เบี้ยขยัน ฿<input className="input" type="number" min="0" step="100" value={diligence} onChange={e => setDiligence(+e.target.value || 0)} style={{ width: 80, height: 28 }}></input>
          </span>
          <span className="spacer" />
          <span style={{ color: "var(--ink-3)" }}>
            คะแนนขยัน 50 (ขาด −5 · สาย −1.5 · ลา −1) + คะแนนงาน 50 (เฉลี่ยใบประเมิน × 10) · เกรด A ≥90 → 100% · B ≥80 → 75% · C ≥70 → 50% · D → ไม่ได้โบนัส
          </span>
        </div>
      </Card>

      <Card title={`สรุป KPI ${mo.label}`} sub="เรียงตามคะแนนรวม · คนแรกคือพนักงานยอดเยี่ยมประจำเดือน" flush>
        <div className="table-wrap">
          <table className="t">
            <thead><tr>
              <th>พนักงาน</th><th className="right">ขาด</th><th className="right">ลา</th><th className="right">สาย</th>
              <th>คะแนนขยัน /50</th><th>คะแนนงาน /50</th><th className="right">รวม /100</th><th>เกรด</th><th className="right">โบนัสแนะนำ</th>
            </tr></thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={r.emp.id} style={i === 0 ? { background: "var(--success-bg, var(--surface-2))" } : {}}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      {window.RankAvatar ? <window.RankAvatar name={r.emp.name} size={30} /> : <div className="avatar" style={{ width: 30, height: 30 }}>{r.emp.name.slice(0, 2)}</div>}
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{i === 0 && "🏆 "}{r.emp.name}{r.perfect && <span title="มาครบทั้งเดือน" style={{ marginLeft: 6 }}><Badge tone="success">มาครบ</Badge></span>}</div>
                        <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{r.emp.role} · {r.emp.dept}</div>
                      </div>
                    </div>
                  </td>
                  <td className="right" style={{ color: r.att.absent ? "var(--danger)" : "var(--ink-3)", fontWeight: r.att.absent ? 700 : 400 }}>{r.att.absent}</td>
                  <td className="right" style={{ color: "var(--ink-3)" }}>{r.att.leave}</td>
                  <td className="right" style={{ color: r.att.late ? "var(--warning)" : "var(--ink-3)", fontWeight: r.att.late ? 700 : 400 }}>{r.att.late}</td>
                  <td><KPIBar value={r.attend} max={50} color="var(--info)" /></td>
                  <td>
                    <KPIBar value={r.work} max={50} color="var(--c-violet, #7c3aed)" />
                    <div style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 2 }}>เฉลี่ย {r.evalAvg.toFixed(1)}/5{r.evalCount ? ` · ${r.evalCount} งานที่ประเมิน` : " · คะแนนสะสม"}</div>
                  </td>
                  <td className="right"><span style={{ fontSize: 15, fontWeight: 700 }}>{r.total.toFixed(1)}</span></td>
                  <td><Badge tone={r.grade.tone}>{r.grade.g}</Badge></td>
                  <td className="right amount" style={{ fontWeight: 700, color: r.bonus > 0 ? "var(--success)" : "var(--ink-3)" }}>{r.bonus > 0 ? `฿${fmt0(r.bonus)}` : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ padding: "10px 14px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12.5 }}>
          <span style={{ color: "var(--ink-3)" }}>คะแนนงานดึงจาก <b style={{ color: "var(--ink-1)" }}>ใบประเมินงาน</b> ที่ออกหลังใบสั่งงานเสร็จ (หน้าโปรเจกต์) โดยอัตโนมัติ</span>
          <span style={{ fontWeight: 700 }}>โบนัสรวม ฿{fmt0(bonusSum)}</span>
        </div>
      </Card>
    </>
  );
}

window.KPIPage = KPIPage;
