"use client";

import { useState } from "react";
import { PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { api } from "@/lib/api";
import { useApi } from "@/lib/use-api";

type Setting = { category: string; label: string; description: string; email: boolean; customized: boolean };

/** One email on/off switch per category for the signed-in person, in this workspace. */
function Row({ s, onSaved }: { s: Setting; onSaved: () => void }) {
  const toast = useToast();
  // Optimistic: the switch moves at once and snaps back if saving fails.
  const [state, setState] = useState({ value: s.email, base: s.email });
  const value = state.base === s.email ? state.value : s.email;
  async function toggle() {
    const next = !value;
    setState({ value: next, base: s.email });
    try {
      await api.put("/notifications/settings", { [s.category]: next });
      toast("success", `${s.label} emails ${next ? "on" : "off"}`);
      onSaved();
    } catch (e) {
      setState({ value: !next, base: s.email });
      toast("error", (e as Error).message);
    }
  }
  return (
    <li className="flex items-center gap-4 px-5 py-4">
      <div className="min-w-0 flex-1">
        <p className="font-medium">{s.label}</p>
        <p className="text-[13px] text-muted">{s.description}</p>
      </div>
      <button type="button" role="switch" aria-checked={value} aria-label={`Email me about ${s.label.toLowerCase()}`} onClick={toggle} className={`relative h-6 w-11 shrink-0 rounded-full transition-colors ${value ? "bg-teal" : "bg-line"}`}>
        <span className={`absolute top-0.5 size-5 rounded-full bg-white shadow transition-transform ${value ? "translate-x-5" : "translate-x-0.5"}`} />
      </button>
    </li>
  );
}

export default function NotificationSettingsPage() {
  const { data, reload } = useApi<{ data: Setting[]; meta: { email_configured: boolean; email: string } }>("/notifications/settings");
  return (
    <>
      <PageHeader title="Notification emails" description="Everything always appears under the bell. Choose what we also email you about." />
      {!data ? (
        <Skeleton className="h-64" />
      ) : (
        <>
          {!data.meta.email_configured && <p className="mb-4 rounded-md bg-amber-soft px-4 py-3 text-sm text-amber">Email sending isn&apos;t set up on this Devwebs server yet, so notifications only appear in the app for now.</p>}
          <p className="mb-3 text-sm text-muted">Emails go to {data.meta.email}.</p>
          <Panel>
            <ul className="divide-y divide-line">
              {data.data.map((s) => (
                <Row key={s.category} s={s} onSaved={reload} />
              ))}
            </ul>
          </Panel>
        </>
      )}
    </>
  );
}
