"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { ReactNode, useEffect, useState, useRef } from "react";
import { useAuth, getToken } from "@/lib/auth";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "/api";

const navItems = [
  { href: "/", label: "Dashboard", icon: "◈" },
  { href: "/stock-in", label: "Stock In", icon: "↑" },
  { href: "/stock-out", label: "Stock Out", icon: "↓" },
  { href: "/inventory", label: "Inventory", icon: "▦" },
  { href: "/expiry", label: "Expiry Tracking", icon: "⏱" },
  { href: "/warehouses", label: "Warehouses", icon: "⊡" },
  { href: "/items", label: "Items", icon: "◉" },
  { href: "/approvals", label: "Approvals", icon: "✓" },
  { href: "/access-control", label: "Access Control", icon: "◇" },
  { href: "/reports", label: "Reports", icon: "≡" },
];

const roleLabel: Record<string, string> = {
  store_keeper: "Store Keeper",
  store_manager: "Store Manager",
  super_admin: "Super Admin",
};

type Notification = {
  id: string;
  type: string;
  message: string;
  documentId: string | null;
  read: boolean;
  createdAt: string;
};

export function AppShell({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const { user, loading, logout } = useAuth();

  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [notifOpen, setNotifOpen] = useState(false);
  const notifRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!user) return;
    fetchNotifications();
    const interval = setInterval(fetchNotifications, 30000);
    return () => clearInterval(interval);
  }, [user]); // eslint-disable-line react-hooks/exhaustive-deps

  // Close notification dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (notifRef.current && !notifRef.current.contains(event.target as Node)) {
        setNotifOpen(false);
      }
    }

    if (notifOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [notifOpen]);

  async function fetchNotifications() {
    const token = getToken();
    if (!token) return;
    try {
      const res = await fetch(`${BASE_URL}/notifications`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) return;
      const data = (await res.json()) as Notification[];
      setNotifications(data);
      setUnreadCount(data.filter((n) => !n.read).length);
    } catch {
      // silent
    }
  }

  async function markAllRead() {
    const token = getToken();
    if (!token) return;
    await fetch(`${BASE_URL}/notifications/read-all`, {
      method: "PATCH",
      headers: { Authorization: `Bearer ${token}` },
    });
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    setUnreadCount(0);
  }

  async function markOneRead(id: string) {
    const token = getToken();
    if (!token) return;
    await fetch(`${BASE_URL}/notifications/${id}/read`, {
      method: "PATCH",
      headers: { Authorization: `Bearer ${token}` },
    });
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, read: true } : n))
    );
    setUnreadCount((c) => Math.max(0, c - 1));
  }

  if (pathname === "/login") return <>{children}</>;

  if (loading) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh" }}>
        <p style={{ color: "var(--muted)", fontSize: "0.9rem" }}>Loading…</p>
      </div>
    );
  }

  if (!user) return null;

  const isManager = user.role === "store_manager" || user.role === "super_admin";

  return (
    <div className="app-shell">
      <aside className="sidebar">
        <div className="sidebar-brand">
          <h1>Manual Stock Management</h1>
        </div>
        <nav className="nav">
          {navItems
            .filter((item) => {
              // Hide Approvals from store keepers
              if (item.href === "/approvals" && !isManager) return false;
              if (item.href === "/access-control" && !isManager) return false;
              return true;
            })
            .map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={pathname === item.href ? "active" : undefined}
              >
                <span style={{ fontSize: "1rem", lineHeight: 1 }}>{item.icon}</span>
                {item.label}
                {item.href === "/approvals" && unreadCount > 0 && (
                  <span className="nav-badge">{unreadCount}</span>
                )}
              </Link>
            ))}
        </nav>

        <div className="sidebar-user">
          <div className="sidebar-user-info">
            <strong>{user.name}</strong>
            <span>{roleLabel[user.role] ?? user.role}</span>
          </div>
          <button className="sidebar-logout" onClick={logout} title="Sign out">⎋</button>
        </div>
      </aside>

      <main className="content">
        <div className="content-inner">
          <div className="topbar">
            <div className="topbar-title">
              <p>Operations Workspace</p>
            </div>
            <div className="topbar-actions">
              {/* Notification bell */}
              <div ref={notifRef} style={{ position: "relative" }}>
                <button
                  className="notif-bell"
                  onClick={() => {
                    setNotifOpen((o) => !o);
                    if (!notifOpen && unreadCount > 0) markAllRead();
                  }}
                  aria-label="Notifications"
                >
                  🔔
                  {unreadCount > 0 && (
                    <span className="notif-count">{unreadCount > 9 ? "9+" : unreadCount}</span>
                  )}
                </button>

                {notifOpen && (
                  <div className="notif-dropdown">
                    <div className="notif-header">
                      <strong>Notifications</strong>
                      {notifications.length > 0 && (
                        <button className="notif-clear" onClick={markAllRead}>
                          Mark all read
                        </button>
                      )}
                    </div>
                    <div className="notif-list">
                      {notifications.length === 0 && (
                        <p className="notif-empty">No notifications yet.</p>
                      )}
                      {notifications.map((n) => (
                        <div
                          key={n.id}
                          className={`notif-item ${!n.read ? "notif-unread" : ""}`}
                          onClick={() => { if (!n.read) markOneRead(n.id); }}
                        >
                          <span
                            className={`notif-dot ${
                              n.type === "approved"
                                ? "notif-dot-ok"
                                : n.type === "rejected"
                                ? "notif-dot-danger"
                                : "notif-dot-warn"
                            }`}
                          />
                          <div className="notif-body">
                            <p>{n.message}</p>
                            <span>
                              {new Date(n.createdAt).toLocaleString("en-AE", {
                                day: "2-digit",
                                month: "short",
                                hour: "2-digit",
                                minute: "2-digit",
                              })}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {isManager && (
                <a className="button secondary" href="/approvals">
                  Approvals {unreadCount > 0 && `(${unreadCount})`}
                </a>
              )}
              <a className="button" href="/stock-in">Stock In</a>
            </div>
          </div>
          {children}
        </div>
      </main>
    </div>
  );
}
