import { createSignal, For, Show, onMount, onCleanup } from "solid-js";
import { Bell, Check, CheckCheck, X } from "lucide-solid";

import {
  apiListNotifications,
  apiMarkNotificationRead,
  apiMarkAllNotificationsRead,
  apiUnreadNotificationCount
} from "~/lib/api-integrations";
import type { Notification } from "~/lib/types-integrations";
import { formatPrettyDate } from "~/lib/utils";

export function NotificationsDropdown() {
  const [open, setOpen] = createSignal(false);
  const [notifications, setNotifications] = createSignal<Notification[]>([]);
  const [unreadCount, setUnreadCount] = createSignal(0);
  const [loading, setLoading] = createSignal(false);

  const loadNotifications = async () => {
    setLoading(true);
    try {
      const [notifs, count] = await Promise.all([
        apiListNotifications(),
        apiUnreadNotificationCount()
      ]);
      setNotifications(notifs);
      setUnreadCount(count);
    } catch (e) {
      console.error("Failed to load notifications", e);
    }
    setLoading(false);
  };

  const markRead = async (id: string) => {
    await apiMarkNotificationRead(id);
    setNotifications(notifications().map(n => n.id === id ? { ...n, read: true } : n));
    setUnreadCount(Math.max(0, unreadCount() - 1));
  };

  const markAllRead = async () => {
    await apiMarkAllNotificationsRead();
    setNotifications(notifications().map(n => ({ ...n, read: true })));
    setUnreadCount(0);
  };

  const handleClickOutside = (e: MouseEvent) => {
    const target = e.target as HTMLElement;
    if (!target.closest(".notifications-dropdown")) {
      setOpen(false);
    }
  };

  onMount(() => {
    loadNotifications();
    document.addEventListener("click", handleClickOutside);
  });

  onCleanup(() => {
    document.removeEventListener("click", handleClickOutside);
  });

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case "task_assigned": return "📋";
      case "task_completed": return "✅";
      case "mention": return "💬";
      case "comment": return "💭";
      case "invite_accepted": return "👋";
      default: return "🔔";
    }
  };

  return (
    <div class="relative notifications-dropdown">
      <button
        onClick={(e) => {
          e.stopPropagation();
          setOpen(!open());
          if (!open()) return;
          loadNotifications();
        }}
        class="relative flex h-11 w-11 items-center justify-center rounded-xl text-[var(--text-muted)] transition-all duration-200 hover:bg-[var(--bg-subtle)] hover:text-[var(--text)] hover:shadow-md hover:scale-105"
        aria-label="Notifications"
      >
        <Bell size={19} />
        <Show when={unreadCount() > 0}>
          <span class="absolute -top-0.5 -right-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-[var(--accent)] text-white text-xs font-bold">
            {unreadCount() > 9 ? "9+" : unreadCount()}
          </span>
        </Show>
      </button>

      <Show when={open()}>
        <div class="absolute right-0 top-full mt-2 w-80 rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-xl z-50">
          {/* Header */}
          <div class="flex items-center justify-between px-4 py-3 border-b border-[var(--border)]">
            <h3 class="font-semibold">Notifications</h3>
            <Show when={unreadCount() > 0}>
              <button
                onClick={markAllRead}
                class="flex items-center gap-1 text-xs text-[var(--accent)] hover:underline"
              >
                <CheckCheck size={14} />
                Mark all read
              </button>
            </Show>
          </div>

          {/* List */}
          <div class="max-h-96 overflow-y-auto">
            <Show when={loading()}>
              <div class="px-4 py-8 text-center text-sm text-[var(--text-muted)]">
                Loading...
              </div>
            </Show>
            <Show when={!loading() && notifications().length === 0}>
              <div class="px-4 py-8 text-center text-sm text-[var(--text-muted)]">
                No notifications
              </div>
            </Show>
            <For each={notifications()}>
              {notification => (
                <div
                  class={`px-4 py-3 border-b border-[var(--border)] last:border-b-0 transition-colors ${
                    !notification.read ? "bg-[var(--accent-muted)]" : ""
                  }`}
                >
                  <div class="flex items-start gap-3">
                    <span class="text-lg">{getNotificationIcon(notification.type)}</span>
                    <div class="flex-1 min-w-0">
                      <p class="text-sm font-medium">{notification.title}</p>
                      <Show when={notification.body}>
                        <p class="text-xs text-[var(--text-muted)] mt-0.5 line-clamp-2">
                          {notification.body}
                        </p>
                      </Show>
                      <p class="text-xs text-[var(--text-subtle)] mt-1">
                        {formatPrettyDate(notification.createdAt)}
                      </p>
                    </div>
                    <Show when={!notification.read}>
                      <button
                        onClick={() => markRead(notification.id)}
                        class="p-1 rounded text-[var(--text-muted)] hover:text-[var(--accent)]"
                        title="Mark as read"
                      >
                        <Check size={14} />
                      </button>
                    </Show>
                  </div>
                </div>
              )}
            </For>
          </div>
        </div>
      </Show>
    </div>
  );
}