"use client";

import { useCallback, useEffect, useState } from "react";
import { useBrand } from "@/context/brand-context";
import { Bell, Check, AlertCircle, Info, CheckCircle2, AlertTriangle } from "lucide-react";

interface Notif { id: string; title: string; message: string; type: string; severity: string; channel: string; isRead: boolean; createdAt: string; metadata?: { link?: string } | null }

const SEV_ICON: Record<string, typeof AlertCircle> = { critical: AlertCircle, high: AlertTriangle, medium: Info, low: Info };
const SEV_COLOR: Record<string, string> = { critical: "text-red-500", high: "text-orange-500", medium: "text-blue-500", low: "text-slate-400" };

export default function NotificationsPage() {
  const { brand } = useBrand();
  const [items, setItems] = useState<Notif[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<"all" | "unread">("all");

  const load = useCallback(async () => {
    if (!brand?.id) return;
    setLoading(true);
    const res = await fetch(`/api/notifications?brandId=${brand.id}&unreadOnly=${filter === "unread"}&limit=30&page=${page}`);
    if (res.ok) { const d = await res.json(); setItems(d.notifications ?? []); setTotal(d.total ?? 0); }
    setLoading(false);
  }, [brand.id, filter, page]);
  useEffect(() => { load(); }, [load]);

  async function markRead(ids: string[]) {
    await fetch("/api/notifications/read", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }) });
    setItems((prev) => prev.map((n) => ids.includes(n.id) ? { ...n, isRead: true } : n));
  }

  async function markAllRead() {
    await fetch("/api/notifications/read", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ all: true, brandId: brand.id }) });
    setItems((prev) => prev.map((n) => ({ ...n, isRead: true })));
  }

  const pages = Math.ceil(total / 30);

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="flex items-start justify-between">
        <div><h1 className="text-2xl font-bold text-slate-900">Notifications</h1><p className="text-slate-500 text-sm mt-1">{total} total</p></div>
        <div className="flex items-center gap-2">
          <div className="flex bg-slate-100 rounded-lg p-0.5">
            {(["all", "unread"] as const).map((f) => <button key={f} onClick={() => { setFilter(f); setPage(1); }} className={`px-3 py-1.5 rounded-md text-xs font-semibold capitalize ${filter === f ? "bg-white text-slate-900 shadow-sm" : "text-slate-500"}`}>{f}</button>)}
          </div>
          <button onClick={markAllRead} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50"><Check className="w-3 h-3" /> Mark All Read</button>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-32"><div className="w-6 h-6 border-4 border-brand-100 border-t-brand-600 rounded-full animate-spin" /></div>
      ) : items.length === 0 ? (
        <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
          <Bell className="w-12 h-12 text-slate-200 mx-auto mb-3" />
          <p className="text-sm font-semibold text-slate-700">No notifications</p>
        </div>
      ) : (
        <div className="bg-white rounded-xl border border-slate-200 divide-y divide-slate-100 overflow-hidden">
          {items.map((n) => {
            const Icon = SEV_ICON[n.severity] || Info;
            return (
              <div key={n.id} className={`px-5 py-4 flex items-start gap-3 ${!n.isRead ? "bg-brand-50/20" : ""}`}>
                <Icon className={`w-4 h-4 mt-0.5 shrink-0 ${SEV_COLOR[n.severity] || SEV_COLOR.medium}`} />
                <div className="flex-1 min-w-0">
                  <p className={`text-sm ${n.isRead ? "text-slate-700" : "text-slate-900 font-semibold"}`}>{n.title}</p>
                  <p className="text-xs text-slate-500 mt-0.5">{n.message}</p>
                  <div className="flex items-center gap-3 mt-1.5 text-[10px] text-slate-400">
                    <span>{new Date(n.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}</span>
                    <span className="uppercase font-bold tracking-widest">{n.channel}</span>
                    {n.metadata?.link && <a href={n.metadata.link} className="text-brand-600 font-semibold hover:underline">View</a>}
                  </div>
                </div>
                {!n.isRead && <button onClick={() => markRead([n.id])} className="p-1 rounded-md hover:bg-slate-100 text-slate-400" title="Mark read"><CheckCircle2 className="w-4 h-4" /></button>}
              </div>
            );
          })}
        </div>
      )}

      {pages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Prev</button>
          <span className="text-xs text-slate-500">Page {page} of {pages}</span>
          <button disabled={page >= pages} onClick={() => setPage(page + 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Next</button>
        </div>
      )}
    </div>
  );
}
