"use client";

import { useCallback, useEffect, useState } from "react";
import { useBrand } from "@/context/brand-context";
import { Bell, Phone, Loader2, Check, Mail } from "lucide-react";

interface Rule { id: string; name: string; type: string; severity: string; channels: string[]; isActive: boolean }

interface EmailPrefs {
  signalAlerts: boolean;
  weeklyDigest: boolean;
  auditCompletion: boolean;
  reportReady: boolean;
  teamActivity: boolean;
}

const EMAIL_PREF_DEFS: Array<{ key: keyof EmailPrefs; label: string; desc: string }> = [
  { key: "signalAlerts",    label: "Signal alerts",       desc: "Critical and high-severity findings as they're detected." },
  { key: "weeklyDigest",    label: "Weekly digest",       desc: "Monday-morning summary of last week's highlights across all brands you can see." },
  { key: "auditCompletion", label: "Audit completion",    desc: "When a Technical / Content / CWI audit finishes." },
  { key: "reportReady",     label: "Report ready",        desc: "When a scheduled or on-demand report is generated and ready to download." },
  { key: "teamActivity",    label: "Team activity",       desc: "When a teammate invites, removes, or changes access for a member." },
];

export default function NotificationsTab() {
  const { brand } = useBrand();
  const [rules, setRules] = useState<Rule[]>([]);
  const [loading, setLoading] = useState(true);
  const [prefs, setPrefs] = useState<EmailPrefs | null>(null);
  const [savingPref, setSavingPref] = useState<keyof EmailPrefs | null>(null);
  const [smsPhone, setSmsPhone] = useState("");
  const [smsStatus, setSmsStatus] = useState<"none" | "pending" | "verified">("none");
  const [smsCode, setSmsCode] = useState("");
  const [toast, setToast] = useState<string | null>(null);

  const show = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 2000); };

  const load = useCallback(async () => {
    setLoading(true);
    // Two independent fetches — the per-brand alert rules (which
    // also power SMS + in-app alerts) and the per-user email prefs
    // (which live on User.emailPrefs and are shared across brands).
    const [rulesRes, profileRes] = await Promise.all([
      fetch(`/api/alerts/rules?brandId=${brand.id}`).catch(() => null),
      fetch("/api/me/profile").catch(() => null),
    ]);
    if (rulesRes?.ok) { const d = await rulesRes.json(); setRules(d.rules ?? []); }
    if (profileRes?.ok) {
      const d = await profileRes.json();
      if (d?.emailPrefs) setPrefs(d.emailPrefs as EmailPrefs);
    }
    setLoading(false);
  }, [brand.id]);
  useEffect(() => { load(); }, [load]);

  async function togglePref(key: keyof EmailPrefs) {
    if (!prefs) return;
    const next: EmailPrefs = { ...prefs, [key]: !prefs[key] };
    // Optimistic update — revert on failure so the switch position
    // always reflects the server state.
    setPrefs(next);
    setSavingPref(key);
    try {
      const res = await fetch("/api/me/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ emailPrefs: { [key]: next[key] } }),
      });
      if (res.ok) {
        const data = await res.json();
        if (data?.emailPrefs) setPrefs(data.emailPrefs as EmailPrefs);
        show(next[key] ? "Subscribed" : "Unsubscribed");
      } else {
        setPrefs(prefs);
        show("Save failed");
      }
    } catch {
      setPrefs(prefs);
      show("Save failed");
    } finally {
      setSavingPref(null);
    }
  }

  async function toggleRule(id: string, isActive: boolean) {
    await fetch(`/api/alerts/rules/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive }) });
    setRules((prev) => prev.map((r) => r.id === id ? { ...r, isActive } : r));
  }

  async function initDefaults() {
    await fetch("/api/alerts/rules/init", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id }) });
    await load();
    show("Default alert rules created!");
  }

  async function requestSms() {
    if (!smsPhone.trim()) return;
    await fetch("/api/sms/request-optin", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ phone: smsPhone.trim() }) });
    setSmsStatus("pending"); show("Verification code sent!");
  }

  async function verifySms() {
    const res = await fetch("/api/sms/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: smsCode }) });
    if (res.ok) { const d = await res.json(); if (d.verified) { setSmsStatus("verified"); show("SMS verified!"); } else show("Invalid code"); }
  }

  const SEV_CLS: Record<string, string> = { critical: "bg-red-50 text-red-700", high: "bg-orange-50 text-orange-700", medium: "bg-blue-50 text-blue-700", low: "bg-slate-100 text-slate-600" };

  return (
    <div className="space-y-6">
      {/* Email preferences — per-user, cross-brand. Rendered first
          because it's the channel most users actually think of when
          they come to this tab; the alert-rules block below is the
          more advanced per-brand signal configuration. */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Mail className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Email Preferences</h2>
          <span className="ml-auto text-[10px] text-slate-400">Applies to all brands you can access</span>
        </div>
        {loading || !prefs ? (
          <div className="px-6 py-8 text-center"><Loader2 className="w-5 h-5 text-slate-400 animate-spin mx-auto" /></div>
        ) : (
          <div className="divide-y divide-slate-100">
            {EMAIL_PREF_DEFS.map(({ key, label, desc }) => {
              const value = prefs[key];
              const saving = savingPref === key;
              return (
                <div key={key} className="px-6 py-3 flex items-center gap-3">
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-slate-800">{label}</p>
                    <p className="text-[11px] text-slate-500 mt-0.5">{desc}</p>
                  </div>
                  <button
                    onClick={() => togglePref(key)}
                    disabled={saving}
                    className={`relative w-9 h-5 rounded-full transition-colors ${value ? "bg-brand-600" : "bg-slate-200"} ${saving ? "opacity-60" : ""}`}
                  >
                    <span className={`absolute top-0.5 ${value ? "left-4" : "left-0.5"} w-4 h-4 bg-white rounded-full shadow-sm transition-all`} />
                  </button>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Alert Rules */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <div className="flex items-center gap-2"><Bell className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-800 text-sm">Alert Rules</h2></div>
          {rules.length === 0 && !loading && <button onClick={initDefaults} className="text-xs font-semibold text-brand-600 hover:text-brand-800">Create Defaults</button>}
        </div>
        {loading ? (
          <div className="px-6 py-8 text-center"><Loader2 className="w-5 h-5 text-slate-400 animate-spin mx-auto" /></div>
        ) : rules.length === 0 ? (
          <div className="px-6 py-8 text-center text-xs text-slate-400">No alert rules. Click &quot;Create Defaults&quot; to get started.</div>
        ) : (
          <div className="divide-y divide-slate-100">
            {rules.map((r) => (
              <div key={r.id} className="px-6 py-3 flex items-center gap-3">
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800">{r.name}</p>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 ${SEV_CLS[r.severity] || SEV_CLS.medium}`}>{r.severity}</span>
                    <span className="text-[10px] text-slate-400">{r.channels.join(", ")}</span>
                  </div>
                </div>
                <button onClick={() => toggleRule(r.id, !r.isActive)} className={`relative w-9 h-5 rounded-full transition-colors ${r.isActive ? "bg-brand-600" : "bg-slate-200"}`}>
                  <span className={`absolute top-0.5 ${r.isActive ? "left-4" : "left-0.5"} w-4 h-4 bg-white rounded-full shadow-sm transition-all`} />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* SMS Setup */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Phone className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">SMS Alerts</h2>
          {smsStatus === "verified" && <span className="flex items-center gap-1 text-[10px] font-bold text-green-600 ml-auto"><Check className="w-3 h-3" /> Verified</span>}
        </div>
        <div className="px-6 py-5 space-y-3">
          {smsStatus !== "verified" ? (
            <>
              <div className="flex items-center gap-2">
                <input type="tel" value={smsPhone} onChange={(e) => setSmsPhone(e.target.value)} placeholder="+15551234567" className="flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg" />
                <button onClick={requestSms} className="px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700">Send Code</button>
              </div>
              {smsStatus === "pending" && (
                <div className="flex items-center gap-2">
                  <input type="text" value={smsCode} onChange={(e) => setSmsCode(e.target.value)} placeholder="6-digit code" maxLength={6} className="w-32 px-3 py-2 text-sm border border-slate-200 rounded-lg font-mono" />
                  <button onClick={verifySms} className="px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg">Verify</button>
                </div>
              )}
              <p className="text-[10px] text-slate-400">E.164 format required. SMS is opt-in only — we never send without verification.</p>
            </>
          ) : (
            <div className="flex items-center gap-3">
              <p className="text-sm text-slate-700">SMS alerts are active for critical notifications.</p>
              <button onClick={async () => { await fetch("/api/sms/optout", { method: "POST" }); setSmsStatus("none"); show("Opted out"); }} className="text-xs text-red-600 font-semibold hover:underline">Opt Out</button>
            </div>
          )}
        </div>
      </div>

      {toast && <div className="fixed top-4 right-4 z-50 px-4 py-2 rounded-lg bg-slate-900 text-white text-xs font-semibold shadow-lg">{toast}</div>}
    </div>
  );
}
