"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { NotificationsBell, useNotices, type Notice } from "@/components/medora/notifications";
import { TODAY } from "@/lib/mock-data";

export const NOW = `${TODAY}T14:32:00`;

export const NOTICES: Notice[] = [
  { id: "n1", tone: "error", word: "Out of stock", text: "Amoxil 500 mg capsules ran out at Westlands Main. 3 customers asked today.", at: `${TODAY}T14:20:00`, href: "#" },
  { id: "n2", tone: "warning", word: "Approval needed", text: "Peter Kamau asked to write off 12 Augmentin 625 mg (damaged). KES 10,200.", at: `${TODAY}T13:05:00`, href: "#" },
  { id: "n3", tone: "error", word: "eTIMS rejected", text: "Sale SALE-005188 was rejected by KRA: buyer PIN not valid. Correct and resend.", at: `${TODAY}T11:48:00`, href: "#" },
  { id: "n4", tone: "warning", word: "Low stock", text: "Panadol 500 mg is at 40 tablets, below the reorder level of 200.", at: `${TODAY}T09:10:00`, href: "#", read: true },
  { id: "n5", tone: "warning", word: "Expiring", text: "4 batches expire within 60 days (KES 18,450 at cost).", at: `${TODAY}T07:00:00`, href: "#" },
  { id: "n6", tone: "error", word: "Overdue", text: "Aga Khan Hospital owes KES 84,300, over 60 days.", at: "2026-10-19T16:40:00", href: "#", read: true },
  { id: "n7", tone: "warning", word: "Low stock", text: "Brufen 400 mg was below its reorder level.", at: "2026-10-18T09:15:00", href: "#", resolved: true },
];

const MANY: Notice[] = Array.from({ length: 12 }, (_, i) => ({
  id: `m${i}`,
  tone: i % 3 ? "warning" : "error",
  word: i % 3 ? "Low stock" : "Out of stock",
  text: `Product ${i + 1} needs reordering.`,
  at: `${TODAY}T${String(13 - i).padStart(2, "0")}:00:00`,
}));

function Bar({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-card px-3 py-2">
      <span className="text-sm text-muted-foreground">{label}</span>
      {children}
    </div>
  );
}

export function NotificationsSection() {
  const admin = useNotices(NOTICES);
  const cashier = useNotices(NOTICES.filter((n) => ["n1", "n4", "n5"].includes(n.id)));
  const many = useNotices(MANY);
  const empty = useNotices([]);
  const [failed, setFailed] = React.useState(true);

  return (
    <Section
      id="notifications"
      title="Notifications"
      description="The bell in the top bar and its panel (spec 03 §3). Alerts come from Settings → 9.9: low stock, expiry, overdue balances, approvals and eTIMS rejections. Each has an icon and a word, never colour alone. The count uses the brand colour, since unread isn't a status, and caps at 9+. Opening an alert marks it read; a condition that has cleared stays listed as resolved. The panel's look and how long alerts stay are still open (OQ-11)."
    >
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Admin" description="4 unread, grouped Today and Earlier, with Alert settings in the footer">
          <Bar label="Top bar">
            <NotificationsBell items={admin.items} now={NOW} onOpenNotice={admin.open} onReadAll={admin.readAll} settingsHref="#" />
          </Bar>
        </Example>
        <Example title="Cashier" description="Only the alerts set up for the role; no settings link">
          <Bar label="Top bar">
            <NotificationsBell items={cashier.items} now={NOW} onOpenNotice={cashier.open} onReadAll={cashier.readAll} />
          </Bar>
        </Example>
        <Example title="More than 9 unread" description="Badge reads 9+; the Unread filter shows all 12">
          <Bar label="Top bar">
            <NotificationsBell items={many.items} now={NOW} onOpenNotice={many.open} onReadAll={many.readAll} settingsHref="#" />
          </Bar>
        </Example>
        <Example title="Nothing to show" description="No badge; the panel says what will appear here">
          <Bar label="Top bar">
            <NotificationsBell items={empty.items} now={NOW} onOpenNotice={empty.open} onReadAll={empty.readAll} settingsHref="#" />
          </Bar>
        </Example>
        <Example title="Loading" description="Placeholder rows while alerts load">
          <Bar label="Top bar">
            <NotificationsBell items={[]} now={NOW} state="loading" onOpenNotice={() => {}} onReadAll={() => {}} />
          </Bar>
        </Example>
        <Example title="Couldn't load" description="Says what to do; Try again succeeds here">
          <Bar label="Top bar">
            <NotificationsBell items={failed ? [] : NOTICES} now={NOW} state={failed ? "error" : "ready"} onRetry={() => setFailed(false)} onOpenNotice={() => {}} onReadAll={() => {}} />
          </Bar>
        </Example>
      </div>
      <Example title="No alerts for this role" description="When no in-app alerts are configured for a role, the bell isn't rendered at all">
        <Bar label="Top bar (no bell)">
          <span className="text-xs text-muted-foreground">–</span>
        </Bar>
      </Example>
    </Section>
  );
}
