// แบบฟอร์มประเมิน — ใช้ร่วมกัน ประเมินตนเอง (type="self") และผู้บังคับบัญชา (type="supervisor")
// mode: "create" = สร้างใหม่ (header only) | "self" = กรอกประเมินตนเอง | "supervisor" = กรอกผู้บังคับบัญชา

const SCORE_OPTIONS = [
  { v:5, label:"มากสุด (5)" }, { v:4, label:"มาก (4)" }, { v:3, label:"กลาง (3)" },
  { v:2, label:"น้อย (2)" }, { v:1, label:"น้อยสุด (1)" },
];

// Create modal (header fields only)
const CreateEvalModal = ({ open, onClose, onDataChange }) => {
  const { push } = useToast();
  const today = new Date().toISOString().slice(0,10);
  const [form, setForm] = React.useState({ course_name:"", course_date:"", dept:"", trainee_name:"", trainee_position:"", follow_up_date:"" });
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (!open) { setForm({ course_name:"", course_date:"", dept:"", trainee_name:"", trainee_position:"", follow_up_date:"" }); setSaving(false); }
  }, [open]);

  const setF = (k,v) => setForm(f => ({ ...f, [k]:v }));
  const valid = form.course_name.trim() && form.trainee_name.trim();

  const submit = async e => {
    e.preventDefault(); if (!valid) return;
    setSaving(true);
    try {
      const { id } = await window.TRN_API.createEval(form);
      push("สร้างแบบประเมินสำเร็จ", { kind:"success" });
      onDataChange?.();
      onClose();
    } catch(err) { push(err.message || "บันทึกไม่สำเร็จ", { kind:"error" }); }
    finally { setSaving(false); }
  };

  return (
    <Modal open={open} onClose={onClose} maxWidth={640}>
      <form onSubmit={submit}>
        <div style={{ padding:"20px 22px 16px", borderBottom:"1px solid var(--border)", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
          <div><div style={{ fontWeight:700, fontSize:16 }}>สร้างแบบประเมินใหม่</div><div className="faint" style={{ fontSize:12 }}>กรอกข้อมูลหลักสูตรและผู้เข้าอบรม</div></div>
          <button type="button" className="btn btn-ghost btn-sm" onClick={onClose} style={{ padding:"5px 7px" }}><Icon name="close" size={15} /></button>
        </div>

        <div style={{ padding:"18px 22px", maxHeight:"65vh", overflowY:"auto" }}>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
            <div style={{ gridColumn:"1/-1" }}>
              <label className="field-label">ชื่อหลักสูตร <span style={{ color:"var(--pink)" }}>*</span></label>
              <input className="input" value={form.course_name} onChange={e=>setF("course_name",e.target.value)} placeholder="การใช้งานโปรแกรม Excel…" required autoFocus />
            </div>
            <div>
              <label className="field-label">วันที่อบรม</label>
              <input className="input" type="date" value={form.course_date} onChange={e=>setF("course_date",e.target.value)} />
            </div>
            <div>
              <label className="field-label">วันที่ติดตามผล</label>
              <input className="input" type="date" value={form.follow_up_date} onChange={e=>setF("follow_up_date",e.target.value)} />
            </div>
            <div style={{ gridColumn:"1/-1" }}>
              <label className="field-label">ผู้เข้ารับการอบรม <span style={{ color:"var(--pink)" }}>*</span></label>
              <input className="input" value={form.trainee_name} onChange={e=>setF("trainee_name",e.target.value)} placeholder="น.ส. ชนิกานต์ ยอดดำเนิน" required />
            </div>
            <div>
              <label className="field-label">ตำแหน่ง</label>
              <input className="input" value={form.trainee_position} onChange={e=>setF("trainee_position",e.target.value)} placeholder="หัวหน้าแผนก…" />
            </div>
            <div>
              <label className="field-label">ฝ่าย/แผนก</label>
              <input className="input" value={form.dept} onChange={e=>setF("dept",e.target.value)} placeholder="แผนกจัดซื้อ" />
            </div>
          </div>
        </div>

        <div style={{ padding:"14px 22px", borderTop:"1px solid var(--border)", display:"flex", justifyContent:"flex-end", gap:10 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
          <button type="submit" className="btn btn-primary shine" disabled={!valid||saving} style={{ minWidth:120 }}>
            {saving ? "กำลังบันทึก…" : <><Icon name="check" size={14} /> สร้างแบบประเมิน</>}
          </button>
        </div>
      </form>
    </Modal>
  );
};

// Eval fill modal (self or supervisor)
const FillEvalModal = ({ open, onClose, evalId, type, onDataChange }) => {
  const { push } = useToast();
  const qs = window.EVAL_QUESTIONS;
  const [scores, setScores] = React.useState({});
  const [description, setDescription] = React.useState("");
  const [sigName, setSigName] = React.useState("");
  const [sigPosition, setSigPosition] = React.useState(""); // supervisor only
  const [loading, setLoading] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [evalData, setEvalData] = React.useState(null);
  const prefix = type === "self" ? "self" : "sup";

  React.useEffect(() => {
    if (!open || !evalId) return;
    setLoading(true);
    window.TRN_API.getEval(evalId).then(d => {
      setEvalData(d);
      // pre-fill if already has data
      const s = {};
      qs.forEach(q => { if (d[`${prefix}_${q.key}`]) s[q.key] = d[`${prefix}_${q.key}`]; });
      setScores(s);
      setDescription(d[`${prefix}_description`] || "");
      setSigName(d[`${prefix}_sig_name`] || (type==="self" ? d.trainee_name : ""));
      setSigPosition(d.sup_sig_position || "");
    }).catch(() => {}).finally(() => setLoading(false));
  }, [open, evalId, type]);

  React.useEffect(() => {
    if (!open) { setScores({}); setDescription(""); setSigName(""); setSigPosition(""); setEvalData(null); }
  }, [open]);

  const allFilled = qs.every(q => scores[q.key]);

  const submit = async e => {
    e.preventDefault(); if (!allFilled || !sigName) return;
    setSaving(true);
    const now = new Date().toISOString().slice(0,10);
    const patch = {};
    qs.forEach(q => { patch[`${prefix}_${q.key}`] = scores[q.key]; });
    patch[`${prefix}_description`]  = description;
    patch[`${prefix}_sig_name`]     = sigName;
    patch[`${prefix}_sig_date`]     = now;
    patch[`${prefix}_submitted_at`] = now;
    if (type === "supervisor") patch.sup_sig_position = sigPosition;

    try {
      await window.TRN_API.updateEval(evalId, patch);
      push(type==="self" ? "บันทึกการประเมินตนเองสำเร็จ" : "บันทึกการประเมินผู้บังคับบัญชาสำเร็จ", { kind:"success" });
      onDataChange?.();
      onClose();
    } catch(err) { push(err.message || "บันทึกไม่สำเร็จ", { kind:"error" }); }
    finally { setSaving(false); }
  };

  const typeLabel = type === "self" ? "ประเมินตนเอง" : "ผู้บังคับบัญชาประเมิน";
  const typeColor = type === "self" ? "var(--teal)" : "var(--purple)";

  return (
    <Modal open={open} onClose={onClose} maxWidth={700}>
      <form onSubmit={submit}>
        <div style={{ padding:"20px 22px 16px", borderBottom:"1px solid var(--border)", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
          <div>
            <div style={{ fontWeight:700, fontSize:16 }}>แบบฟอร์มติดตามผลการฝึกอบรม</div>
            <div style={{ fontSize:12, color:typeColor, fontWeight:500, marginTop:3 }}>({typeLabel})</div>
            {evalData && <div className="faint" style={{ fontSize:12, marginTop:2 }}>{evalData.trainee_name} · {evalData.course_name}</div>}
          </div>
          <button type="button" className="btn btn-ghost btn-sm" onClick={onClose} style={{ padding:"5px 7px" }}><Icon name="close" size={15} /></button>
        </div>

        {loading ? (
          <div style={{ padding:"48px", textAlign:"center" }}><LoadingSplash /></div>
        ) : (
          <>
            <div style={{ padding:"18px 22px", maxHeight:"68vh", overflowY:"auto" }}>
              {/* Score table */}
              <div style={{ fontWeight:600, fontSize:13.5, marginBottom:12 }}>การประเมินพฤติกรรม <span style={{ color:typeColor }}>({typeLabel})</span></div>
              <div className="glass" style={{ borderRadius:12, overflow:"hidden", marginBottom:18 }}>
                <table style={{ width:"100%", borderCollapse:"collapse" }}>
                  <thead>
                    <tr style={{ borderBottom:"1px solid var(--border)", background:"var(--surface)" }}>
                      <th style={{ padding:"10px 14px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left", width:30 }}>#</th>
                      <th style={{ padding:"10px 14px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"left" }}>รายการประเมิน</th>
                      {SCORE_OPTIONS.map(s => (
                        <th key={s.v} style={{ padding:"10px 10px", fontSize:11, color:"var(--text-muted)", fontWeight:500, textAlign:"center", whiteSpace:"nowrap" }}>
                          {s.v}<br/><span style={{ fontSize:10, fontWeight:400 }}>{s.label.split(" ")[0]}</span>
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {qs.map((q, i) => (
                      <tr key={q.key} style={{ borderBottom:i<qs.length-1?"1px solid var(--border)":"none", background:scores[q.key] ? "rgba(0,212,168,0.03)" : "" }}>
                        <td style={{ padding:"10px 14px", fontSize:12, color:"var(--text-muted)" }}>{i+1}</td>
                        <td style={{ padding:"10px 14px" }}>
                          <div style={{ fontSize:13, fontWeight:500 }}>{q.label}</div>
                          <div className="faint" style={{ fontSize:11 }}>{q.en}</div>
                        </td>
                        {SCORE_OPTIONS.map(s => (
                          <td key={s.v} style={{ padding:"10px 10px", textAlign:"center" }}>
                            <label style={{ cursor:"pointer", display:"flex", justifyContent:"center" }}>
                              <input type="radio" name={`score_${q.key}`} value={s.v} checked={scores[q.key]===s.v}
                                onChange={() => setScores(p => ({ ...p, [q.key]:s.v }))}
                                style={{ accentColor: typeColor, width:17, height:17 }} />
                            </label>
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Progress */}
              <div style={{ marginBottom:16, display:"flex", alignItems:"center", gap:10 }}>
                <div style={{ flex:1, height:5, borderRadius:3, background:"var(--surface)", overflow:"hidden" }}>
                  <div style={{ width:`${(Object.keys(scores).length/10)*100}%`, height:"100%", background:typeColor, borderRadius:3, transition:"width 0.3s" }} />
                </div>
                <div className="faint" style={{ fontSize:12 }}>{Object.keys(scores).length}/10 ข้อ</div>
              </div>

              {/* Description */}
              <div style={{ marginBottom:14 }}>
                <label className="field-label">อธิบายงานที่นำความรู้จากการอบรมมาประยุกต์ใช้</label>
                <textarea className="input" rows={3} value={description} onChange={e=>setDescription(e.target.value)}
                  style={{ resize:"vertical", lineHeight:1.65 }} placeholder="เช่น นำ Vlookup มาใช้สรุปข้อมูล, ใช้ Pivot Table…" />
              </div>

              {/* Signature */}
              <div style={{ display:"grid", gridTemplateColumns: type==="supervisor"?"1fr 1fr":"1fr", gap:12 }}>
                <div>
                  <label className="field-label">{type==="self" ? "ลงชื่อพนักงาน" : "ลงชื่อผู้บังคับบัญชา"} <span style={{ color:"var(--pink)" }}>*</span></label>
                  <input className="input" value={sigName} onChange={e=>setSigName(e.target.value)} placeholder="ชื่อ-สกุล" required />
                </div>
                {type === "supervisor" && (
                  <div>
                    <label className="field-label">ตำแหน่งผู้บังคับบัญชา</label>
                    <input className="input" value={sigPosition} onChange={e=>setSigPosition(e.target.value)} placeholder="ผู้จัดการแผนก…" />
                  </div>
                )}
              </div>
            </div>

            <div style={{ padding:"14px 22px", borderTop:"1px solid var(--border)", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
              <div className="faint" style={{ fontSize:12 }}>
                {!allFilled && `กรุณาประเมินให้ครบ ${10 - Object.keys(scores).length} ข้อที่เหลือ`}
              </div>
              <div className="row gap-10">
                <button type="button" className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
                <button type="submit" className="btn btn-primary shine" disabled={!allFilled||!sigName||saving} style={{ minWidth:130 }}>
                  {saving ? "กำลังบันทึก…" : <><Icon name="check" size={14} /> บันทึกการประเมิน</>}
                </button>
              </div>
            </div>
          </>
        )}
      </form>
    </Modal>
  );
};

window.CreateEvalModal = CreateEvalModal;
window.FillEvalModal   = FillEvalModal;
