import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { safeHtml } from "@/lib/safe-html";
import { formatTime as i18nFormatTime } from "@/lib/i18n-format";

/**
 * Convert an HH:mm:ss DB string to the same 12-hour locale-aware format
 * used by the on-screen schedule. Mirrors the helper in the main page so
 * the print/PDF view stays in sync (e.g. "3:15 PM" / "3:15 م"). Falls
 * back to the raw HH:mm slice if the string somehow fails to parse.
 */
function formatPrintTime(t: string, lang: "ar" | "en"): string {
  const hhmm = t.slice(0, 5);
  const parsed = new Date(`1970-01-01T${hhmm}:00`);
  if (Number.isNaN(parsed.getTime())) return hhmm;
  return i18nFormatTime(parsed, lang, {
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
  });
}

type Attendee = {
  id: number;
  name: string;
  title: string | null;
  attendanceType: "internal" | "external" | "online";
  sortOrder: number;
  // Optional so older API snapshots without the column still parse;
  // missing values are treated as "person" downstream.
  kind?: "person" | "subheading";
};

type Meeting = {
  id: number;
  dailyNumber: number;
  titleAr: string;
  titleEn: string | null;
  meetingDate: string;
  startTime: string | null;
  endTime: string | null;
  location: string | null;
  meetingUrl: string | null;
  platform: string | null;
  status: string;
  isHighlighted: number;
  notes: string | null;
  attendees?: Attendee[];
};

type DayResponse = { date: string; meetings: Meeting[] };

function getQuery(): { date: string; lang: "ar" | "en" } {
  const params = new URLSearchParams(window.location.search);
  const date =
    params.get("date") || new Date().toISOString().slice(0, 10);
  const lang = params.get("lang") === "en" ? "en" : "ar";
  return { date, lang };
}

const PRINT_KEYS = {
  title: "executiveMeetings.print.title",
  no: "executiveMeetings.print.no",
  meeting: "executiveMeetings.print.meeting",
  attendees: "executiveMeetings.print.attendees",
  time: "executiveMeetings.print.time",
  location: "executiveMeetings.print.location",
  none: "executiveMeetings.print.none",
  print: "executiveMeetings.print.print",
  back: "executiveMeetings.print.back",
  loading: "executiveMeetings.print.loading",
} as const;

export default function ExecutiveMeetingsPrintPage() {
  const { date, lang } = useMemo(getQuery, []);
  const [data, setData] = useState<DayResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const isRtl = lang === "ar";
  const { t: i18nT, i18n } = useTranslation();
  useEffect(() => {
    if (i18n.language !== lang) void i18n.changeLanguage(lang);
  }, [lang, i18n]);
  const t = {
    title: i18nT(PRINT_KEYS.title),
    no: i18nT(PRINT_KEYS.no),
    meeting: i18nT(PRINT_KEYS.meeting),
    attendees: i18nT(PRINT_KEYS.attendees),
    time: i18nT(PRINT_KEYS.time),
    location: i18nT(PRINT_KEYS.location),
    none: i18nT(PRINT_KEYS.none),
    print: i18nT(PRINT_KEYS.print),
    back: i18nT(PRINT_KEYS.back),
    loading: i18nT(PRINT_KEYS.loading),
  };

  useEffect(() => {
    document.documentElement.dir = isRtl ? "rtl" : "ltr";
    document.documentElement.lang = lang;
    document.title = `${t.title} — ${date}`;
  }, [isRtl, lang, date, t.title]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch(`/api/executive-meetings?date=${date}`, {
          credentials: "include",
        });
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}`);
        }
        const json = (await res.json()) as DayResponse;
        if (!cancelled) setData(json);
      } catch (err) {
        if (!cancelled)
          setError(err instanceof Error ? err.message : String(err));
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [date]);

  const meetings = data?.meetings ?? [];

  return (
    <div
      className="min-h-screen bg-white text-[#0B1E3F]"
      data-testid="em-print-page"
    >
      <style>{`
        @media print {
          .no-print { display: none !important; }
          body { background: white; }
          @page { size: A4; margin: 14mm; }
          /* On A4 the table always fits the page; drop the screen-only
             scroll guard so the layout stays identical to today and the
             # column can shrink to its natural width. */
          .em-print-scroll { overflow: visible !important; }
          .em-print-table { min-width: 0 !important; }
          .em-print-table th:first-child { width: auto !important; }
        }
        /* Screen-only horizontal scroll guard — prevents the table from
           breaking the page layout on phones (<640px). */
        .em-print-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .em-print-table {
          border-collapse: collapse;
          width: 100%;
          min-width: 640px;
        }
        .em-print-table th, .em-print-table td {
          border: 1px solid #d1d5db;
          padding: 8px 10px;
          text-align: center;
          vertical-align: middle;
          /* Long Arabic names have few break opportunities; force wrap so
             the cell never overflows its border. */
          word-break: break-word;
          overflow-wrap: anywhere;
          white-space: normal;
        }
        .em-print-table th {
          background: #0B1E3F;
          color: white;
          font-weight: 600;
        }
        .em-print-table tr.hl td { background: #fecaca; }
        .em-print-attendees {
          display: flex;
          flex-direction: column;
          gap: 2px;
          text-align: center;
          line-height: 1.4;
        }
        .em-print-attendees .em-print-attendee-num {
          color: #6b7280;
          margin-inline-end: 4px;
        }
        /* Subheading rows: bold separator labels between persons. */
        .em-print-attendees .em-print-subheading {
          font-weight: 700;
          color: #0B1E3F;
          margin-top: 4px;
          padding-top: 2px;
          border-top: 1px dashed #cbd5e1;
        }
        .em-print-attendees .em-print-subheading:first-child {
          margin-top: 0;
          padding-top: 0;
          border-top: 0;
        }
      `}</style>

      <div className="no-print flex items-center justify-between px-6 py-3 border-b border-gray-200 bg-gray-50">
        <div className="text-sm text-gray-600">
          {t.title} — {date}
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => window.print()}
            className="px-3 py-1.5 rounded-md bg-[#0B1E3F] text-white text-sm"
            data-testid="em-print-now"
          >
            {t.print}
          </button>
          <button
            onClick={() => window.close()}
            className="px-3 py-1.5 rounded-md border border-gray-300 text-sm"
          >
            {t.back}
          </button>
        </div>
      </div>

      <div className="px-8 py-6 max-w-5xl mx-auto">
        <h1 className="text-2xl font-bold text-center mb-1">{t.title}</h1>
        <div className="text-center text-sm text-gray-600 mb-6">{date}</div>

        {error ? (
          <div className="text-red-600 text-sm">{error}</div>
        ) : !data ? (
          <div className="text-gray-500 text-sm">{t.loading}</div>
        ) : meetings.length === 0 ? (
          <div className="text-gray-500 text-sm text-center">{t.none}</div>
        ) : (
          <div className="em-print-scroll" data-testid="em-print-scroll">
            <table className="em-print-table" dir={isRtl ? "rtl" : "ltr"}>
              <thead>
                <tr>
                  {/* Slightly rebalanced from 8/32/40/20: give attendees the
                      most room since long Arabic names dominate the cell. */}
                  <th style={{ width: "6%" }}>{t.no}</th>
                  <th style={{ width: "30%" }}>{t.meeting}</th>
                  <th style={{ width: "44%" }}>{t.attendees}</th>
                  <th style={{ width: "20%" }}>{t.time}</th>
                </tr>
              </thead>
              <tbody>
                {meetings.map((m) => {
                  const title = isRtl
                    ? m.titleAr
                    : m.titleEn || m.titleAr;
                  const attendees = m.attendees ?? [];
                  const time =
                    m.startTime && m.endTime
                      ? `${formatPrintTime(m.startTime, lang)} – ${formatPrintTime(m.endTime, lang)}`
                      : m.startTime
                        ? formatPrintTime(m.startTime, lang)
                        : "—";
                  return (
                    <tr key={m.id} className={m.isHighlighted ? "hl" : ""}>
                      <td>{m.dailyNumber}</td>
                      <td>
                        {/* title comes from the API already sanitized by
                            sanitizeRichText (allowlist of inline tags + a
                            small set of safe styles). Render as HTML so
                            in-cell formatting (bold, color, font…) carries
                            into the printed page. */}
                        <div
                          style={{ fontWeight: 600 }}
                          dangerouslySetInnerHTML={{ __html: safeHtml(title) }}
                        />
                        {m.location ? (
                          <div style={{ fontSize: 12, color: "#4b5563" }}>
                            {m.location}
                          </div>
                        ) : null}
                      </td>
                      <td>
                        {attendees.length === 0 ? (
                          "—"
                        ) : (
                          <div
                            className="em-print-attendees"
                            data-testid={`em-print-attendees-${m.id}`}
                          >
                            {(() => {
                              // Each subheading starts a fresh numbered
                              // section. Mirrors AttendeeFlow on screen.
                              let personIdx = 0;
                              return attendees.map((a, idx) => {
                                const isSub =
                                  (a.kind ?? "person") === "subheading";
                                if (isSub) {
                                  // Reset the in-section counter so the
                                  // next person starts at 1.
                                  personIdx = 0;
                                  return (
                                    <div
                                      key={a.id ?? `sub-${idx}`}
                                      className="em-print-subheading"
                                      data-testid={`em-print-subheading-${m.id}-${idx}`}
                                    >
                                      <span
                                        dangerouslySetInnerHTML={{
                                          __html: safeHtml(a.name),
                                        }}
                                      />
                                    </div>
                                  );
                                }
                                const myIdx = personIdx;
                                personIdx += 1;
                                return (
                                  <div key={a.id ?? idx}>
                                    <span className="em-print-attendee-num">
                                      {myIdx + 1}-
                                    </span>
                                    {/* a.name comes from the API already
                                        sanitized by sanitizeRichText.
                                        a.title is *not* rich text —
                                        render it as a plain text node so
                                        an attacker who smuggles HTML into
                                        the title field cannot escape into
                                        <script> tags on the print page. */}
                                    <span
                                      dangerouslySetInnerHTML={{
                                        __html: safeHtml(a.name),
                                      }}
                                    />
                                    {a.title ? <span> ({a.title})</span> : null}
                                  </div>
                                );
                              });
                            })()}
                          </div>
                        )}
                      </td>
                      <td>{time}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
