import type { Metadata } from "next";
import { Megaphone } from "lucide-react";
import { Button } from "@/components/Button";
import { listNotificationsForAdmin } from "@/lib/notifications/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  StatusBadge,
  ConfirmButton,
  EmptyState,
  KpiCard,
} from "@/components/admin";
import {
  createNotification,
  updateNotification,
  deleteNotification,
} from "./actions";

export const metadata: Metadata = { title: "Notifications" };
export const dynamic = "force-dynamic";

const LEVEL_OPTIONS = [
  { value: "info", label: "Info" },
  { value: "warning", label: "Warning" },
  { value: "success", label: "Success" },
];

function toDatetimeLocal(date: Date | null | undefined): string {
  if (!date) return "";
  const d = new Date(date);
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(
    d.getHours(),
  )}:${pad(d.getMinutes())}`;
}

export default async function AdminNotificationsPage() {
  const rows = await listNotificationsForAdmin();
  const active = rows.filter((r) => r.active).length;
  const scheduled = rows.filter((r) => r.startsAt && r.startsAt > new Date()).length;

  return (
    <>
      <AdminHeading
        eyebrow="Overview"
        title="Notifications"
        lede="Site-wide banners shown above the header on public pages."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total" value={rows.length} Icon={Megaphone} tone="ink" />
        <KpiCard label="Active" value={active} tone="emerald" />
        <KpiCard label="Scheduled" value={scheduled} tone="blue" />
        <KpiCard label="Inactive" value={rows.length - active} tone="slate" />
      </div>

      <div className="mb-6">
        <FormSection
          title="New notification"
          description="Shown as a banner across the top of the site."
        >
          <form action={createNotification} className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Title"
              name="title"
              type="text"
              required
              minLength={2}
              maxLength={200}
              wrapClassName="md:col-span-2"
            />
            <TextareaField
              label="Body"
              name="body"
              rows={3}
              maxLength={2000}
              wrapClassName="md:col-span-2"
            />
            <InputField label="Link URL (optional)" name="href" type="text" maxLength={400} />
            <SelectField
              label="Level"
              name="level"
              defaultValue="info"
              options={LEVEL_OPTIONS}
            />
            <InputField label="Starts at (optional)" name="startsAt" type="datetime-local" />
            <InputField label="Ends at (optional)" name="endsAt" type="datetime-local" />
            <div className="md:col-span-2">
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create notification
              </Button>
            </div>
          </form>
        </FormSection>
      </div>

      {rows.length === 0 ? (
        <EmptyState
          Icon={Megaphone}
          title="No notifications yet"
          description="Create a new banner using the form above."
        />
      ) : (
        <ul className="space-y-4">
          {rows.map((n) => (
            <li key={n.id}>
              <FormSection
                title={n.title}
                description={n.body.slice(0, 120) + (n.body.length > 120 ? "…" : "")}
                actions={
                  <div className="flex items-center gap-2">
                    <StatusBadge label={n.level} />
                    <StatusBadge
                      label={n.active ? "Active" : "Inactive"}
                      tone={n.active ? "success" : "muted"}
                      dot
                    />
                  </div>
                }
              >
                <form action={updateNotification} className="grid gap-4 md:grid-cols-2">
                  <input type="hidden" name="id" value={n.id} />
                  <InputField
                    label="Title"
                    name="title"
                    required
                    defaultValue={n.title}
                    wrapClassName="md:col-span-2"
                  />
                  <TextareaField
                    label="Body"
                    name="body"
                    rows={3}
                    defaultValue={n.body}
                    wrapClassName="md:col-span-2"
                  />
                  <InputField
                    label="Link URL"
                    name="href"
                    defaultValue={n.href ?? ""}
                  />
                  <SelectField
                    label="Level"
                    name="level"
                    defaultValue={n.level}
                    options={LEVEL_OPTIONS}
                  />
                  <InputField
                    label="Starts at"
                    name="startsAt"
                    type="datetime-local"
                    defaultValue={toDatetimeLocal(n.startsAt)}
                  />
                  <InputField
                    label="Ends at"
                    name="endsAt"
                    type="datetime-local"
                    defaultValue={toDatetimeLocal(n.endsAt)}
                  />
                  <label className="flex items-center gap-2.5 text-[13px] md:col-span-2">
                    <input
                      type="checkbox"
                      name="active"
                      defaultChecked={n.active}
                      className="h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)] focus:ring-[var(--color-blue)]"
                    />
                    <span className="font-semibold text-[var(--color-ink)]">
                      Show this banner live
                    </span>
                  </label>
                  <div className="flex flex-wrap gap-2 md:col-span-2">
                    <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                      Save
                    </Button>
                  </div>
                </form>
                <form action={deleteNotification} className="mt-4 border-t border-[var(--color-line)] pt-4">
                  <input type="hidden" name="id" value={n.id} />
                  <ConfirmButton
                    label="Delete"
                    confirmLabel="Click again to delete"
                    tone="danger"
                  />
                </form>
              </FormSection>
            </li>
          ))}
        </ul>
      )}
    </>
  );
}
