import { createSignal, createEffect, onCleanup, Show } from "solid-js";
import { api } from "~/lib/api";

export default function NotificationBell() {
  const [unreadCount, setUnreadCount] = createSignal(0);
  const [showDropdown, setShowDropdown] = createSignal(false);
  const [notifications, setNotifications] = createSignal<any[]>([]);

  // Poll for unread count every 30 seconds
  createEffect(() => {
    const fetchUnreadCount = async () => {
      try {
        const res = await api.get("/me/notifications/unread-count");
        setUnreadCount(res.data?.unread_count || 0);
      } catch (e) {
        // Silently fail
      }
    };

    // Initial fetch
    fetchUnreadCount();

    // Set up polling interval
    const interval = setInterval(fetchUnreadCount, 30000);

    onCleanup(() => clearInterval(interval));
  });

  // Fetch notifications when dropdown opens
  const fetchNotifications = async () => {
    try {
      const res = await api.get("/me/notifications?limit=5");
      setNotifications(res.data?.data || []);
    } catch (e) {
      setNotifications([]);
    }
  };

  const toggleDropdown = () => {
    const newState = !showDropdown();
    setShowDropdown(newState);
    if (newState) {
      fetchNotifications();
    }
  };

  const markAsRead = async (id: string) => {
    try {
      await api.patch(`/me/notifications/${id}/read`);
      // Update local state
      setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
      setUnreadCount((prev) => Math.max(0, prev - 1));
    } catch (e) {
      console.error("Failed to mark as read", e);
    }
  };

  const markAllAsRead = async () => {
    try {
      await api.patch("/me/notifications/read-all");
      setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
      setUnreadCount(0);
    } catch (e) {
      console.error("Failed to mark all as read", e);
    }
  };

  const formatTime = (date: string) => {
    const now = new Date();
    const notifDate = new Date(date);
    const diff = now.getTime() - notifDate.getTime();

    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return "Just now";
    if (minutes < 60) return `${minutes}m ago`;
    if (hours < 24) return `${hours}h ago`;
    return `${days}d ago`;
  };

  return (
    <div class="relative">
      <button
        onClick={toggleDropdown}
        class="relative p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-full transition-colors"
        aria-label="Notifications"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-6 w-6"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width={2}
            d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
          />
        </svg>

        {/* Unread Badge */}
        <Show when={unreadCount() > 0}>
          <span class="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/4 -translate-y-1/4 bg-orange-500 rounded-full">
            {unreadCount() > 99 ? "99+" : unreadCount()}
          </span>
        </Show>
      </button>

      {/* Dropdown */}
      <Show when={showDropdown()}>
        <>
          {/* Backdrop */}
          <div class="fixed inset-0 z-40" onClick={() => setShowDropdown(false)} />

          {/* Dropdown Panel */}
          <div class="absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-lg border z-50 overflow-hidden">
            <div class="flex justify-between items-center p-4 border-b">
              <h3 class="font-semibold">Notifications</h3>
              <Show when={unreadCount() > 0}>
                <button
                  onClick={markAllAsRead}
                  class="text-sm text-orange-600 hover:text-orange-700"
                >
                  Mark all read
                </button>
              </Show>
            </div>

            <div class="max-h-96 overflow-y-auto">
              <Show
                when={notifications().length > 0}
                fallback={
                  <div class="p-8 text-center text-gray-500">
                    <p class="text-4xl mb-2">🔔</p>
                    <p>No notifications yet</p>
                  </div>
                }
              >
                {notifications().map((notification) => (
                  <div
                    class={`p-4 border-b hover:bg-gray-50 cursor-pointer transition-colors ${
                      !notification.is_read ? "bg-orange-50" : ""
                    }`}
                    onClick={() => {
                      if (!notification.is_read) {
                        markAsRead(notification.id);
                      }
                    }}
                  >
                    <div class="flex items-start gap-3">
                      {/* Unread Dot */}
                      <div class="mt-1.5">
                        <div
                          class={`w-2 h-2 rounded-full ${
                            !notification.is_read ? "bg-orange-500" : "bg-transparent"
                          }`}
                        />
                      </div>

                      <div class="flex-1 min-w-0">
                        <p class="font-medium text-sm text-gray-900 line-clamp-1">
                          {notification.title}
                        </p>
                        <p class="text-sm text-gray-600 line-clamp-2 mt-0.5">{notification.body}</p>
                        <p class="text-xs text-gray-400 mt-1">
                          {formatTime(notification.created_at)}
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </Show>
            </div>

            <div class="p-3 border-t bg-gray-50">
              <a
                href="/dashboard/notifications"
                class="block text-center text-sm text-orange-600 hover:text-orange-700 font-medium"
                onClick={() => setShowDropdown(false)}
              >
                View all notifications
              </a>
            </div>
          </div>
        </>
      </Show>
    </div>
  );
}
