/* ==================================================================
   Academics → Holidays
   ------------------------------------------------------------------
   Announcing a holiday tells the attendance machinery the school is
   shut: no check-in nudge, no absence digest to admins, no automatic
   student-register marking, and the staff heat-map stops counting the
   day as a working day. That last one is what makes a holiday not a
   leave.

   Check-in is NOT blocked: staff who work through a break still have
   their day recorded.

   Announce waits for a second press; everything else here is a list.
   ================================================================== */

const HolidaysScreen = ({ setScreen }) => {
  const CX = window.CX;
  const Api = window.AppApi;

  const [list, setList] = useState(null);
  const [err, setErr] = useState(null);
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(null);

  const todayIso = (() => {
    // Local parts, not toISOString(): before 05:30 IST that returns yesterday.
    const d = new Date();
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
  })();

  const [form, setForm] = useState({
    name: "", start_date: todayIso, end_date: todayIso, notes: "",
    // Outpass generation belongs to the (removed) hostel module; always off.
    generate_outpasses: false, pause_staff_attendance: true, pause_student_automark: true,
  });
  const [confirming, setConfirming] = useState(false);

  const load = async () => {
    try {
      const h = await Api.get("/admin/holidays?limit=24");
      setList(h.holidays); setErr(null);
    } catch (e) { setErr(e.message || "Couldn't load holidays"); }
  };
  useEffect(() => { load(); }, []);

  const set = (k) => (e) => {
    const v = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm((f) => {
      const next = { ...f, [k]: v };
      // A range that ends before it starts is a typo, not a choice.
      if (k === "start_date" && next.end_date < v) next.end_date = v;
      return next;
    });
    setConfirming(false);
  };

  const announce = async () => {
    setBusy(true); setErr(null);
    try {
      const r = await Api.post("/admin/holidays", form);
      setDone(r);
      setConfirming(false);
      setForm((f) => ({ ...f, name: "", notes: "" }));
      await load();
    } catch (e) { setErr(e.message || "Couldn't announce the holiday"); }
    finally { setBusy(false); }
  };

  const cancel = async (h) => {
    if (!window.confirm(`Call off ${h.name}?`)) return;
    setBusy(true); setErr(null);
    try {
      await Api.post(`/admin/holidays/${h.id}/cancel`, {});
      setDone(null);
      await load();
    } catch (e) { setErr(e.message || "Couldn't cancel the holiday"); }
    finally { setBusy(false); }
  };

  const days = (() => {
    const a = new Date(`${form.start_date}T00:00:00Z`), b = new Date(`${form.end_date}T00:00:00Z`);
    const n = Math.round((b - a) / 86400000) + 1;
    return Number.isFinite(n) && n > 0 ? n : 0;
  })();
  const ready = form.name.trim() && form.start_date && form.end_date && days > 0 && !busy;

  const HoBadge = window.AppUI.StatusBadge;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Academics"
        title="Holidays"
      />

      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        {err && <div className="ui-alert red">{err}</div>}

        {done && (
          <div className="ui-alert green">
            <strong>{done.holiday.name}</strong> announced
          </div>
        )}

        {/* ── Announce ─────────────────────────────────────────────── */}
        <CX.Card>
          <CX.CardHead
            title="Announce a holiday"
            sub="Pauses check-in nudges, absence digests and automatic register marking for the dates below."
          />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: 14, marginBottom: 16 }}>
            <label className="field">
              <span className="label">Name</span>
              <input className="input" value={form.name} onChange={set("name")} placeholder="Winter break" maxLength={120}/>
            </label>
            <label className="field">
              <span className="label">First day</span>
              <input className="input" type="date" value={form.start_date} onChange={set("start_date")}/>
            </label>
            <label className="field">
              <span className="label">Last day</span>
              <input className="input" type="date" value={form.end_date} min={form.start_date} onChange={set("end_date")}/>
            </label>
            <label className="field" style={{ gridColumn: "1 / -1" }}>
              <span className="label">Notes (optional)</span>
              <input className="input" value={form.notes} onChange={set("notes")} placeholder="School reopens the day after" maxLength={1000}/>
            </label>
          </div>

          <div style={{ display: "grid", gap: 10, fontSize: 13, color: "var(--ink-1)" }}>
            <label style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <input type="checkbox" checked={form.pause_staff_attendance} onChange={set("pause_staff_attendance")}/>
              Pause staff attendance (no nudges, not counted as leave)
            </label>
            <label style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <input type="checkbox" checked={form.pause_student_automark} onChange={set("pause_student_automark")}/>
              Pause automatic student-register marking
            </label>
          </div>

          <div className="cx-card-foot" style={{ flexWrap: "wrap" }}>
            <span style={{ fontSize: 13, color: "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>
              {days > 0 && <>{days} day{days === 1 ? "" : "s"}</>}
            </span>
            {!confirming ? (
              <button type="button" className="btn primary" disabled={!ready} onClick={() => { setDone(null); setConfirming(true); }}>
                <CX.Icon name="calendar" size={15}/> Announce holiday
              </button>
            ) : (
              <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                <span style={{ fontSize: 13, color: "var(--ink-1)" }}>
                  Announce <strong>{form.name}</strong> for {days} day{days === 1 ? "" : "s"}?
                </span>
                <button type="button" className="btn" disabled={busy} onClick={() => setConfirming(false)}>Back</button>
                <button type="button" className="btn primary" disabled={busy} onClick={announce}>
                  {busy ? "Announcing…" : "Yes, announce"}
                </button>
              </div>
            )}
          </div>
        </CX.Card>

        {/* ── What has been announced ──────────────────────────────── */}
        <div className="cx-tablecard">
          <div className="cx-tablecard-head">
            <div className="cx-tablecard-title">Announced</div>
            {list && list.length > 0 && <CX.Tag>{list.length}</CX.Tag>}
          </div>
          {!list && <div style={{ padding: 20 }}><CX.Skeleton rows={3}/></div>}
          {list && list.length === 0 && <CX.Empty icon="calendar" title="No holidays announced yet"/>}
          {list && list.length > 0 && (
            <div className="cx-tablescroll"><table className="cx-table">
              <thead>
                <tr>
                  <th>Holiday</th><th>Dates</th><th>Pauses</th><th>Announced</th><th></th>
                </tr>
              </thead>
              <tbody>
                {list.map((h) => (
                  <tr key={h.id} style={h.cancelled_at ? { opacity: 0.55 } : undefined}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                        <span className="t-main">{h.name}</span>
                        {h.running_now && <HoBadge tone="green" variant="solid">On now</HoBadge>}
                        {h.cancelled_at && <HoBadge tone="grey">Called off</HoBadge>}
                      </div>
                      {h.notes && <div className="t-sub">{h.notes}</div>}
                    </td>
                    <td style={{ whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                      {h.start_date === h.end_date ? CX.date(h.start_date) : `${CX.date(h.start_date)} – ${CX.date(h.end_date)}`}
                    </td>
                    <td className="muted">
                      {h.pause_staff_attendance ? "staff" : "—"}
                      {h.pause_student_automark ? " · register" : ""}
                    </td>
                    <td className="muted">
                      {CX.date(h.announced_at)}{h.announced_by_name ? ` · ${h.announced_by_name}` : ""}
                      {h.cancelled_at && <div className="t-sub">called off {CX.date(h.cancelled_at)}{h.cancelled_by_name ? ` · ${h.cancelled_by_name}` : ""}</div>}
                    </td>
                    <td className="actions">
                      {!h.cancelled_at && (
                        <button type="button" className="btn sm" disabled={busy} onClick={() => cancel(h)}>
                          <CX.Icon name="x" size={14}/> Call off
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        </div>
      </div>
    </div>
  );
};

window.CockpitHolidays = HolidaysScreen;
