"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Skeleton } from "@/components/ui";
import { SettingsTabs } from "@/components/settings-tabs";
import { useToast } from "@/components/toast";

type Prefs = Record<string, boolean>;

const ITEMS: { key: string; label: string; desc: string; group: string }[] = [
  { key: "welcome", label: "Welcome email", desc: "Sent to an affiliate when they're approved.", group: "Affiliate emails" },
  { key: "sale_notification", label: "Sale notification", desc: "Tell an affiliate when they earn a commission.", group: "Affiliate emails" },
  { key: "payout", label: "Payout confirmation", desc: "Tell an affiliate when they've been paid.", group: "Affiliate emails" },
  { key: "admin_new_affiliate", label: "New affiliate", desc: "Notify you when someone registers.", group: "Admin alerts" },
  { key: "admin_payout_request", label: "Payout request", desc: "Notify you when an affiliate requests a payout.", group: "Admin alerts" },
];

function Toggle({ on, onClick }: { on: boolean; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`relative h-6 w-11 shrink-0 rounded-full transition-colors ${on ? "bg-[var(--brand)]" : "bg-gray-300"}`}
    >
      <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-all ${on ? "left-[22px]" : "left-0.5"}`} />
    </button>
  );
}

export default function NotificationsPage() {
  const toast = useToast();
  const [prefs, setPrefs] = useState<Prefs | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    api.get("/admin/notifications").then(setPrefs);
  }, []);

  const toggle = (k: string) => setPrefs((p) => (p ? { ...p, [k]: !p[k] } : p));

  const save = async () => {
    if (!prefs) return;
    setSaving(true);
    try {
      await api.put("/admin/notifications", prefs);
      toast.success("Notification settings saved.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  if (!prefs) return <div className="space-y-4"><Skeleton className="h-8 w-40" /><Skeleton className="h-56" /></div>;

  const groups = [...new Set(ITEMS.map((i) => i.group))];

  return (
    <div className="max-w-4xl">
      <PageHeader title="Settings" subtitle="Choose which emails go out" actions={<Button onClick={save} loading={saving}>Save</Button>} />
      <SettingsTabs />

      <div className="space-y-4">
        {groups.map((g) => (
          <Card key={g} title={g}>
            <ul className="divide-y divide-gray-50">
              {ITEMS.filter((i) => i.group === g).map((i) => (
                <li key={i.key} className="flex items-center justify-between gap-4 py-3">
                  <div>
                    <p className="text-sm font-medium text-gray-800">{i.label}</p>
                    <p className="text-xs text-gray-500">{i.desc}</p>
                  </div>
                  <Toggle on={prefs[i.key] !== false} onClick={() => toggle(i.key)} />
                </li>
              ))}
            </ul>
          </Card>
        ))}
      </div>
    </div>
  );
}
