"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { apiFetch } from "@/lib/apiClient";
import type { Notification } from "@/types";

const TYPE_ICON: Record<string, string> = {
  PAYMENT_RECEIVED: "💰",
  MILESTONE_REACHED: "🏆",
  BOOKING_CONFIRMED: "✅",
  DEPOSIT_REMINDER: "🔔",
  TRIP_UPDATE: "✈️",
  GENERAL: "📢",
};

function groupByDate(notifications: Notification[]) {
  const today = new Date().toDateString();
  const yesterday = new Date(Date.now() - 86400000).toDateString();
  const groups: Record<string, Notification[]> = {};
  for (const n of notifications) {
    const d = new Date(n.sentAt);
    const key =
      d.toDateString() === today
        ? "Today"
        : d.toDateString() === yesterday
        ? "Yesterday"
        : d.toLocaleDateString("en-NG", { day: "numeric", month: "long", year: "numeric" });
    (groups[key] ??= []).push(n);
  }
  return groups;
}

export default function NotificationsPage() {
  const router = useRouter();
  const { isLoading, isAuthenticated } = useAuth();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [dataLoading, setDataLoading] = useState(true);
  const [markingAll, setMarkingAll] = useState(false);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) router.replace("/login");
  }, [isLoading, isAuthenticated, router]);

  useEffect(() => {
    if (!isAuthenticated) return;
    apiFetch<{ notifications: Notification[]; unreadCount: number }>("/notifications/me")
      .then((d) => { setNotifications(d.notifications); setUnreadCount(d.unreadCount); })
      .catch(console.error)
      .finally(() => setDataLoading(false));
  }, [isAuthenticated]);

  async function markAllRead() {
    setMarkingAll(true);
    try {
      await apiFetch("/notifications/read-all", { method: "PATCH" });
      setNotifications((ns) => ns.map((n) => ({ ...n, isRead: true })));
      setUnreadCount(0);
    } catch {}
    setMarkingAll(false);
  }

  async function markRead(id: string) {
    try {
      await apiFetch(`/notifications/${id}/read`, { method: "PATCH" });
      setNotifications((ns) => ns.map((n) => n.id === id ? { ...n, isRead: true } : n));
      setUnreadCount((c) => Math.max(0, c - 1));
    } catch {}
  }

  const grouped = groupByDate(notifications);

  return (
    <div className="min-h-screen" style={{ background: "#F8F8F8" }}>
      {/* Header */}
      <header className="px-5 pt-12 pb-4 sticky top-0 z-10 flex items-center justify-between bg-white shadow-sm">
        <button onClick={() => router.back()} className="flex items-center gap-2 text-[#6B7280] text-sm">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M19 12H5M12 19l-7-7 7-7"/>
          </svg>
        </button>
        <h1 className="font-bold text-[#111111]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          Al-Bakkah
        </h1>
        <span className="w-6" />
      </header>

      <div className="px-5 pt-4 pb-6 max-w-lg mx-auto">
        {/* Tabs */}
        <div className="flex border-b border-gray-200 mb-6">
          <button
            onClick={() => router.push("/transactions")}
            className="flex-1 pb-3 text-sm font-semibold text-[#6B7280]">
            Transactions
          </button>
          <button className="flex-1 pb-3 text-sm font-semibold text-[#111111] relative">
            Notifications
            <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#B8952A]" />
          </button>
        </div>

        {/* Unread summary */}
        {unreadCount > 0 && (
          <div className="flex items-center justify-between bg-white rounded-xl px-4 py-3 mb-5"
            style={{ boxShadow: "0 2px 8px rgba(0,0,0,0.04)" }}>
            <div className="flex items-center gap-2">
              <span className="w-2.5 h-2.5 rounded-full bg-[#B8952A] animate-pulse" />
              <p className="text-sm font-semibold text-[#111111]">{unreadCount} unread notification{unreadCount > 1 ? "s" : ""}</p>
            </div>
            <button onClick={markAllRead} disabled={markingAll}
              className="text-xs font-semibold text-[#B8952A] hover:underline disabled:opacity-50">
              {markingAll ? "Marking..." : "Mark all as read"}
            </button>
          </div>
        )}

        {dataLoading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => <div key={i} className="h-20 bg-white rounded-xl animate-pulse" />)}
          </div>
        ) : notifications.length === 0 ? (
          <div className="text-center py-16">
            <p className="text-4xl mb-3">🔔</p>
            <p className="text-[#6B7280] text-sm">No notifications yet</p>
          </div>
        ) : (
          <div className="space-y-8">
            {Object.entries(grouped).map(([group, items]) => (
              <div key={group}>
                <h3 className="text-[#6B7280] text-[10px] font-bold uppercase tracking-widest mb-3">{group}</h3>
                <div className="space-y-2">
                  {items.map((n) => (
                    <div key={n.id}
                      onClick={() => !n.isRead && markRead(n.id)}
                      className={`flex gap-3 p-4 rounded-xl hover:translate-x-1 transition-transform cursor-pointer ${
                        !n.isRead
                          ? "border-l-4 border-[#B8952A]"
                          : "bg-white border border-gray-100"
                      }`}
                      style={!n.isRead ? { background: "#FEFAF0" } : { boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
                      <div className="w-11 h-11 rounded-full bg-white flex items-center justify-center shrink-0 shadow-sm text-lg">
                        {TYPE_ICON[n.type] ?? "🔔"}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex justify-between items-start mb-0.5">
                          <p className="font-semibold text-[#111111] text-sm">{n.title}</p>
                          <span className="text-[10px] text-[#6B7280] shrink-0 ml-2">
                            {new Date(n.sentAt).toLocaleTimeString("en-NG", { hour: "2-digit", minute: "2-digit" })}
                          </span>
                        </div>
                        <p className="text-[#6B7280] text-xs leading-relaxed">{n.message}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
