"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  PageHeader,
  LoadingArea,
  Textarea,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate, formatNumber } from "@/lib/utils";
import { IconBell, IconPlus, IconTrash } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface Announcement {
  id: number;
  title: string;
  body: string | null;
  createdAt: string;
  audienceRoles: string; // ",STUDENT,PARENT,"
  reached: number;
}

/** role groups the central admin can target — pushed across every institution */
const GROUPS: { key: string; labelKey: "groupStudents" | "groupParents" | "groupTeachers" | "groupStaff" | "groupAdmins" }[] = [
  { key: "students", labelKey: "groupStudents" },
  { key: "parents", labelKey: "groupParents" },
  { key: "teachers", labelKey: "groupTeachers" },
  { key: "staff", labelKey: "groupStaff" },
  { key: "admins", labelKey: "groupAdmins" },
];

/** Central → Announcements: publish a push notification to chosen role
    groups across every institution on the platform. */
export default function CentralAnnouncementsPage() {
  const { t, locale } = useLang();
  const N = t.notifications;
  const { data, loading, reload } = useApi<{ announcements: Announcement[] }>("/api/central/announcements");

  const [form, setForm] = useState({ title: "", body: "" });
  const [groups, setGroups] = useState<string[]>(["admins"]);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  function toggleGroup(key: string) {
    setGroups((prev) => (prev.includes(key) ? prev.filter((g) => g !== key) : [...prev, key]));
  }

  async function publish(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      await api("/api/central/announcements", {
        method: "POST",
        body: JSON.stringify({ ...form, notifyGroups: groups }),
      });
      setForm({ title: "", body: "" });
      setMessage({ type: "success", text: N.announcementPublished });
      reload();
    } catch (err) {
      const code = err instanceof Error ? err.message : "";
      setMessage({
        type: "error",
        text: code === "AUDIENCE_REQUIRED" ? N.audienceRequired : t.common.tryAgain,
      });
    } finally {
      setSaving(false);
    }
  }

  async function remove(a: Announcement) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/central/announcements?id=${a.id}`, { method: "DELETE" });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  const audienceText = (csv: string) =>
    csv
      .split(",")
      .filter(Boolean)
      .map((r) => {
        const group = GROUPS.find((g) => {
          const roles: Record<string, string[]> = {
            students: ["STUDENT"],
            parents: ["PARENT"],
            teachers: ["TEACHER"],
            staff: ["STAFF", "PRINCIPAL", "VICE_PRINCIPAL", "EXECUTIVE_MEMBER"],
            admins: ["INSTITUTION_ADMIN"],
          };
          return roles[g.key]?.includes(r);
        });
        return group ? t.notifications[group.labelKey] : r;
      })
      .join(", ") || "—";

  return (
    <div>
      <PageHeader title={N.announcementsTitle} subtitle={N.announcementsSubtitle} />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <div className="row g-4">
        <div className="col-xl-5">
          <Card title={N.newAnnouncement} icon={<IconPlus className="svg-20" />}>
            <form onSubmit={publish}>
              <Input
                label={`${t.me.marksheetTitle === undefined ? "Title" : N.formTitle}`}
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
              />
              <Textarea
                label={`${N.formBody} (${t.common.optional})`}
                value={form.body}
                onChange={(e) => setForm({ ...form, body: e.target.value })}
              />
              <label className="col-form-label pt-0 f-w-600">{N.audienceLabel}</label>
              <div className="d-flex flex-wrap gap-3 mb-3">
                {GROUPS.map((g) => (
                  <div className="form-check" key={g.key}>
                    <input
                      className="form-check-input"
                      type="checkbox"
                      id={`announce-${g.key}`}
                      checked={groups.includes(g.key)}
                      onChange={() => toggleGroup(g.key)}
                    />
                    <label className="form-check-label ems-fs-13" htmlFor={`announce-${g.key}`}>
                      {t.notifications[g.labelKey]}
                    </label>
                  </div>
                ))}
              </div>
              <p className="ems-fs-11 text-muted">{N.announcementsHint}</p>
              <div className="d-flex justify-content-end">
                <Button type="submit" loading={saving} disabled={!form.title.trim() || groups.length === 0}>
                  <IconBell className="svg-16" />
                  <span className="ms-1">{N.publish}</span>
                </Button>
              </div>
            </form>
          </Card>
        </div>

        <div className="col-xl-7">
          <Card title={N.announcementsTitle} icon={<IconBell className="svg-20" />}>
            {loading ? (
              <LoadingArea label={t.common.loading} />
            ) : (data?.announcements ?? []).length === 0 ? (
              <EmptyState icon={<IconBell />} title={N.noAnnouncements} />
            ) : (
              <div className="table-responsive">
                <table className="table table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{N.formTitle}</th>
                      <th>{N.audienceLabel}</th>
                      <th className="text-center">{N.reached}</th>
                      <th>{t.common.date}</th>
                      <th className="text-end">{t.common.actions}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data?.announcements ?? []).map((a) => (
                      <tr key={a.id}>
                        <td className="f-w-600 ems-fs-13">
                          {a.title}
                          {a.body && <div className="ems-fs-11 text-muted">{a.body}</div>}
                        </td>
                        <td className="ems-fs-12">{audienceText(a.audienceRoles)}</td>
                        <td className="text-center ems-fs-13">{formatNumber(a.reached, locale)}</td>
                        <td className="ems-fs-12 text-muted">{formatDate(a.createdAt, locale)}</td>
                        <td className="text-end">
                          <button
                            type="button"
                            className="btn btn-soft-danger btn-sm"
                            onClick={() => remove(a)}
                            title={t.common.delete}
                          >
                            <IconTrash className="svg-14" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}
