"use client";

import { useLang } from "@/context/LanguageContext";
import { Card, EmptyState, PageHeader, LoadingArea } from "@/components/ui";
import { useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { IconBell, IconSparkle } from "@/components/icons";

interface NoticeRow {
  id: number;
  title: string;
  titleBn: string | null;
  body: string;
  publishDate: string;
  expiryDate: string | null;
  isPinned: boolean;
  audience: string;
}

/** Student/parent: the institution's notice board (audience-aware). */
export default function MeNoticesPage() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<{ notices: NoticeRow[] }>("/api/me/notices");

  if (loading) {
    return (
      <div>
        <PageHeader title={t.me.noticesTitle} subtitle={t.me.noticesSubtitle} />
        <LoadingArea label={t.common.loading} />
      </div>
    );
  }

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

  return (
    <div>
      <PageHeader title={t.me.noticesTitle} subtitle={t.me.noticesSubtitle} />

      {notices.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconBell />} title={t.portal.noticesPage.noNotices ?? t.common.noData} />
        </div>
      ) : (
        <div className="row g-4">
          {notices.map((n) => (
            <div className="col-xl-6" key={n.id}>
              <Card
                title={(locale === "bn" && n.titleBn ? n.titleBn : n.title) || "—"}
                icon={n.isPinned ? <IconSparkle className="svg-20 text-warning" /> : <IconBell className="svg-20" />}
              >
                <p className="ems-fs-13 mb-2" style={{ whiteSpace: "pre-wrap" }}>
                  {n.body}
                </p>
                <p className="mb-0 ems-fs-11 text-muted">
                  {formatDate(n.publishDate, locale)}
                  {n.expiryDate ? ` · ${t.common.expiry}: ${formatDate(n.expiryDate, locale)}` : ""}
                  {n.isPinned ? ` · ${t.me.pinned}` : ""}
                </p>
              </Card>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
