"use client";

import { useMemo } from "react";
import { useLang } from "@/context/LanguageContext";
import { Button, Card, EmptyState, PageHeader, LoadingArea } from "@/components/ui";
import { useApi } from "@/lib/client";
import { IconCalendar } from "@/components/icons";
import { WEEK_DAYS } from "@/lib/constants";
import { esc, openPrintWindow } from "@/lib/print";

interface RoutineRow {
  id: number;
  days: string[];
  startTime: string;
  endTime: string;
  note: string | null;
  subjectName: string | null;
  subjectNameBn: string | null;
  roomName: string | null;
  roomNameBn: string | null;
  teacherName: string | null;
  teacherNameBn: string | null;
}

/** map JS getDay() (0=Sun…6=Sat) onto the BD academic week (SAT first) */
function todayKey(): string {
  return ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"][new Date().getDay()];
}

/** Student/parent: the weekly class routine — rows = time slots, columns =
    days (BD week), today's column highlighted, printable. */
export default function MeSchedulePage() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<{ routine: RoutineRow[] }>("/api/me/schedule");

  const rows = data?.routine ?? [];

  // weekly grid: rows = time slots, columns = days (same shape as the portal routine)
  const grid = useMemo(() => {
    if (rows.length === 0) return null;
    const slots = [...new Set(rows.map((r) => `${r.startTime}-${r.endTime}`))].sort();
    return slots.map((slot) => {
      const [start, end] = slot.split("-");
      const cell: Record<string, RoutineRow[]> = {};
      for (const r of rows.filter((x) => x.startTime === start && x.endTime === end)) {
        for (const d of r.days ?? []) (cell[d] ??= []).push(r);
      }
      return { start, end, cell };
    });
  }, [rows]);

  const today = todayKey();

  const subj = (r: RoutineRow) =>
    locale === "bn" && r.subjectNameBn ? r.subjectNameBn : r.subjectName ?? "—";
  const teacher = (r: RoutineRow) =>
    locale === "bn" && r.teacherNameBn ? r.teacherNameBn : r.teacherName;

  function printRoutine() {
    const L = t.portal.schedulePage;
    const body = `
<div class="doc">
  <h5 style="margin:0 0 12px">${esc(t.me.scheduleTitle)}</h5>
  <table style="width:100%;font-size:11.5px">
    <thead><tr><th style="border:1px solid #d9e1ec;padding:5px 9px;background:#f4f7fa">${esc(L.timeLabel)}</th>${WEEK_DAYS.map((d) => `<th style="border:1px solid #d9e1ec;padding:5px 9px;background:#f4f7fa">${esc(t.days[d])}</th>`).join("")}</tr></thead>
    <tbody>
      ${(grid ?? []).map(
        (slot) => `<tr>
          <td style="border:1px solid #d9e1ec;padding:5px 9px;white-space:nowrap">${slot.start.slice(0, 5)}–${slot.end.slice(0, 5)}</td>
          ${WEEK_DAYS.map((d) => `<td style="border:1px solid #d9e1ec;padding:5px 9px">${(slot.cell[d] ?? []).map(subj).join("<br>") || "—"}</td>`).join("")}
        </tr>`,
      ).join("")}
    </tbody>
  </table>
</div>`;
    openPrintWindow(t.me.scheduleTitle, locale, body);
  }

  return (
    <div>
      <PageHeader
        title={t.me.scheduleTitle}
        subtitle={t.me.scheduleSubtitle}
        action={
          grid ? (
            <Button variant="secondary" onClick={printRoutine}>
              <IconCalendar className="svg-16" />
              <span className="ms-1">{t.me.printRoutine}</span>
            </Button>
          ) : undefined
        }
      />

      {loading ? (
        <LoadingArea label={t.common.loading} />
      ) : !grid ? (
        <div className="card">
          <EmptyState icon={<IconCalendar />} title={t.me.noSchedule} />
        </div>
      ) : (
        <div className="card">
          <div className="card-body">
            <p className="ems-fs-12 text-muted mb-3">{t.me.scheduleHint}</p>
            <div className="table-responsive">
              <table className="table table-bordered align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th style={{ minWidth: 90 }}>{t.portal.schedulePage.timeLabel}</th>
                    {WEEK_DAYS.map((d) => (
                      <th key={d} className={`text-center ${d === today ? "table-primary" : ""}`}>
                        {t.days[d]}
                        {d === today && <span className="badge badge-success ms-1">{t.me.todayBadge}</span>}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {grid.map((slot, i) => (
                    <tr key={i}>
                      <td className="ems-fs-12 text-muted text-nowrap f-w-600">
                        {slot.start.slice(0, 5)}–{slot.end.slice(0, 5)}
                      </td>
                      {WEEK_DAYS.map((d) => {
                        const cells = slot.cell[d] ?? [];
                        return (
                          <td key={d} className={`align-top ${d === today ? "table-light" : ""}`}>
                            {cells.length === 0 ? (
                              <span className="text-muted">—</span>
                            ) : (
                              cells.map((r) => (
                                <div key={`${r.id}-${d}`} className="mb-1">
                                  <div className="f-w-700 ems-fs-13">{subj(r)}</div>
                                  <div className="ems-fs-11 text-muted">
                                    {r.roomName && (
                                      <span>{locale === "bn" && r.roomNameBn ? r.roomNameBn : r.roomName}</span>
                                    )}
                                    {teacher(r) && (
                                      <span>{r.roomName ? " · " : ""}{teacher(r)}</span>
                                    )}
                                  </div>
                                </div>
                              ))
                            )}
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
