"use client";

/**
 * Settings → Alerts (ST-14, plan C): the design's `AlertRules` on `/alerts/rules`. Saved by its own button, not the
 * page's save bar, because the rules are a table of their own. SMS and email show "Not connected" until the messaging
 * integration (plan M); the bell in the top bar is the only channel today.
 */

import * as React from "react";

import { AlertRules, type AlertRule } from "@/components/medora/settings-ops";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "@/components/ui/toast";
import { AlertsApi, type AlertRuleRow } from "@/lib/api";
import { Loading } from "@/components/medora/loading";

const apiError = (e: unknown, fallback: string): string => {
  const m = (e as { response?: { data?: { message?: string | string[] } } })?.response?.data?.message;
  return Array.isArray(m) ? m.join(" ") : m || fallback;
};

const toRule = (r: AlertRuleRow): AlertRule => ({ id: r.kind, name: r.name, when: r.when, threshold: r.threshold, unit: r.unit, roles: r.roles, channels: r.channels, on: r.on });

export function AlertsSection({ readOnly }: { readOnly: boolean }) {
  const [saved, setSaved] = React.useState<AlertRule[] | null>(null);
  const [rules, setRules] = React.useState<AlertRule[]>([]);
  const [roles, setRoles] = React.useState<string[]>([]);
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    AlertsApi.rules()
      .then((d) => {
        setSaved(d.rules.map(toRule));
        setRules(d.rules.map(toRule));
        setRoles(d.roles);
      })
      .catch((e) => {
        setSaved([]);
        toast.add({ type: "error", title: "Couldn't load alert rules", description: apiError(e, "Try again.") });
      });
  }, []);

  if (saved === null)
    return (
      <Loading what="alerts" columns={6} rows={5} />
    );
  const dirty = JSON.stringify(saved) !== JSON.stringify(rules);

  const save = async () => {
    setSaving(true);
    try {
      const d = await AlertsApi.saveRules(rules.map((r) => ({ kind: r.id, on: r.on, threshold: r.threshold, roles: r.roles, channels: r.channels })));
      setSaved(d.rules.map(toRule));
      setRules(d.rules.map(toRule));
      toast.add({ title: "Alert rules saved", description: "The top bar shows the change within five minutes." });
    } catch (e) {
      toast.add({ type: "error", title: "Alert rules not saved", description: apiError(e, "Try again.") });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-3">
      <fieldset disabled={readOnly || saving} className="min-w-0">
        <AlertRules rules={rules} roles={roles} connected={{ sms: false, email: false }} onChange={(id, patch) => setRules((xs) => xs.map((x) => (x.id === id ? { ...x, ...patch } : x)))} />
      </fieldset>
      <p className="text-xs text-muted-foreground">Admins see every alert that is on. Counts are checked when the page asks, at most every five minutes; stock is counted across the whole pharmacy.</p>
      {!readOnly ? (
        <div className="flex gap-2">
          <Button size="sm" disabled={!dirty || saving} onClick={() => void save()}>
            {saving ? <Spinner /> : null}
            Save alert rules
          </Button>
          {dirty ? (
            <Button size="sm" variant="ghost" disabled={saving} onClick={() => setRules(saved)}>
              Discard
            </Button>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
