"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useFamily } from "@/app/FamilyProvider";
import { fmtDate } from "@/lib/date-ist";

interface AppNotification {
  id: string;
  type: string;
  title: string;
  message: string;
  actionUrl?: string;
  isRead: boolean;
  scheduledFor?: string;
  createdAt: string;
  metadata?: { vaccineName?: string; dueDate?: string };
}

function notifIcon(type: string, metadata?: { dueDate?: string }): string {
  if (type.startsWith("vaccine_")) {
    const isOverdue = metadata?.dueDate && metadata.dueDate < new Date().toISOString().slice(0, 10);
    return isOverdue ? "🚨" : "💉";
  }
  if (type === "log_nudge")     return "🍼";
  if (type === "memory_nudge")  return "📸";
  if (type === "garment_nudge") return "👚";
  return "🔔";
}

function notifColor(type: string): string {
  if (type.startsWith("vaccine_")) return "bg-red-50 dark:bg-red-900/20 border-red-100 dark:border-red-800/40";
  if (type === "log_nudge")         return "bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-800/40";
  if (type === "memory_nudge")      return "bg-purple-50 dark:bg-purple-900/20 border-purple-100 dark:border-purple-800/40";
  if (type === "garment_nudge")     return "bg-pink-50 dark:bg-pink-900/20 border-pink-100 dark:border-pink-800/40";
  return "bg-white dark:bg-gray-800";
}

export default function NotificationsPage() {
  const router          = useRouter();
  const { childId }     = useFamily();
  const [items, setItems]     = useState<AppNotification[]>([]);
  const [loading, setLoading] = useState(true);
  const [markingAll, setMarkingAll] = useState(false);

  const fetchNotifications = useCallback(async () => {
    if (!childId) return;
    setLoading(true);
    try {
      const res  = await fetch(`/api/notifications?childId=${childId}`);
      const data = await res.json();
      setItems(data.notifications || []);
    } catch { /* swallow — show empty state */ }
    setLoading(false);
  }, [childId]);

  useEffect(() => { fetchNotifications(); }, [fetchNotifications]);

  const markRead = async (notif: AppNotification) => {
    if (notif.isRead) {
      // Navigate immediately if already read
      if (notif.actionUrl) router.push(notif.actionUrl);
      return;
    }
    // Optimistic update
    setItems(prev => prev.map(n => n.id === notif.id ? { ...n, isRead: true } : n));
    try {
      await fetch(`/api/notifications/${notif.id}`, { method: "PATCH" });
    } catch { /* no-op — optimistic state is fine */ }
    if (notif.actionUrl) router.push(notif.actionUrl);
  };

  const markAllRead = async () => {
    if (!childId) return;
    setMarkingAll(true);
    setItems(prev => prev.map(n => ({ ...n, isRead: true })));
    try {
      await fetch("/api/notifications", {
        method:  "PATCH",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ childId }),
      });
    } catch { /* optimistic update already done */ }
    setMarkingAll(false);
  };

  const unreadCount = items.filter(n => !n.isRead).length;

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800">

      {/* Header */}
      <div className="sticky top-0 z-20 bg-rose-50/80 dark:bg-gray-900/80 backdrop-blur-sm px-4 py-3 flex items-center gap-3 border-b border-rose-100 dark:border-gray-700">
        <button onClick={() => router.back()} className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-xl">←</button>
        <h1 className="text-xl font-bold flex-1">Notifications</h1>
        {unreadCount > 0 && (
          <span className="px-2.5 py-0.5 bg-rose-400 text-white text-xs font-bold rounded-full">
            {unreadCount}
          </span>
        )}
        {unreadCount > 0 && (
          <button
            onClick={markAllRead}
            disabled={markingAll}
            className="text-sm text-rose-500 font-medium disabled:opacity-50"
          >
            {markingAll ? "Marking…" : "Mark all read"}
          </button>
        )}
      </div>

      {/* Section hint */}
      {!loading && items.length > 0 && (
        <p className="px-4 pt-3 pb-1 text-xs text-gray-400 dark:text-gray-500">
          Tap a notification to go to the relevant page
        </p>
      )}

      {/* List */}
      <div className="px-4 py-2 space-y-2 pb-24">
        {loading ? (
          <div className="text-center py-20 text-gray-400">
            <div className="text-4xl mb-3 animate-pulse">🔔</div>
            <p className="text-sm">Loading…</p>
          </div>
        ) : items.length === 0 ? (
          <div className="text-center py-20 text-gray-400">
            <div className="text-6xl mb-4">🔔</div>
            <p className="font-semibold text-gray-600 dark:text-gray-300">All caught up!</p>
            <p className="text-sm mt-1 text-gray-400">No pending reminders right now</p>
          </div>
        ) : (
          items.map(notif => (
            <button
              key={notif.id}
              onClick={() => markRead(notif)}
              className={`w-full text-left rounded-2xl border transition-all active:scale-[0.98] ${
                notif.isRead
                  ? "bg-gray-50 dark:bg-gray-800/40 border-gray-100 dark:border-gray-700/40 opacity-60"
                  : `${notifColor(notif.type)} border shadow-sm`
              }`}
            >
              <div className="flex items-start gap-3 p-4">
                <span className="text-2xl mt-0.5 flex-shrink-0">{notifIcon(notif.type, notif.metadata)}</span>
                <div className="flex-1 min-w-0">
                  <div className={`font-semibold text-sm ${notif.isRead ? "text-gray-400 dark:text-gray-500" : "text-gray-900 dark:text-white"}`}>
                    {notif.title}
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400 mt-0.5 leading-snug">
                    {notif.message}
                  </div>
                  {notif.metadata?.dueDate && (
                    <div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                      Due: {fmtDate(notif.metadata.dueDate + "T00:00:00Z", { day: "numeric", month: "short", year: "numeric" })}
                    </div>
                  )}
                  {notif.actionUrl && !notif.isRead && (
                    <div className="text-xs text-rose-400 dark:text-rose-500 mt-1.5 font-medium">
                      Tap to open →
                    </div>
                  )}
                </div>
                {!notif.isRead && (
                  <div className="w-2.5 h-2.5 bg-rose-400 rounded-full mt-1.5 flex-shrink-0" />
                )}
              </div>
            </button>
          ))
        )}
      </div>

      {/* Legend */}
      {!loading && items.length > 0 && (
        <div className="px-4 pb-8">
          <div className="flex flex-wrap gap-x-4 gap-y-1 justify-center text-xs text-gray-400">
            <span>🚨 Vaccine overdue</span>
            <span>💉 Due today</span>
            <span>🍼 Log reminder</span>
            <span>📸 Memory nudge</span>
            <span>👚 Wardrobe nudge</span>
          </div>
        </div>
      )}
    </div>
  );
}
