"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  AlertTriangle,
  Bell,
  BookOpen,
  CalendarDays,
  CheckCheck,
  ChevronRight,
  Clock,
  Gift,
  GitPullRequestArrow,
  MessageSquare,
  Settings,
  Sparkles,
  Trophy,
  Users2,
  Volume2,
  VolumeX,
  X,
} from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import {
  Dropdown,
  DropdownContent,
  DropdownTrigger,
} from "@/components/ui/dropdown";
import { useNotifications } from "@/hooks/use-notifications";
import { useNotificationStore, type SmartNotification } from "@/stores/notification-store";
import { useSoundStore } from "@/stores/sound-store";
import { playNotificationPing } from "@/lib/sounds";
import { formatRelativeDate } from "@/lib/utils";
import { cn } from "@/lib/utils";
import type { Notification } from "@/types";

/* ── DB notification icon ──────────────────────────────────────────────── */

function DbNotifIcon({ n }: { n: Notification }) {
  if (n.kind === "mention")            return <MessageSquare      className="h-3.5 w-3.5 text-indigo-400" />;
  if (n.kind === "event_invite")       return <CalendarDays        className="h-3.5 w-3.5 text-violet-400" />;
  if (n.kind === "task_review" || n.kind === "project_approval")
                                       return <GitPullRequestArrow className="h-3.5 w-3.5 text-amber-400"  />;
  if (["direct_message","direct_task_request","team_message","team_task_request"].includes(n.kind ?? ""))
                                       return <MessageSquare       className="h-3.5 w-3.5 text-sky-400"   />;
  if (n.kind === "reminder_due")       return <Bell                className="h-3.5 w-3.5 text-sky-300"   />;
  return <Users2 className="h-3.5 w-3.5 text-white/30" />;
}

/* ── Smart notification icon + colors ─────────────────────────────────── */

const SMART_CFG = {
  task_overdue:          { icon: <AlertTriangle  className="h-3.5 w-3.5 text-red-400"    />, accent: "border-l-red-500/60",    bg: "bg-red-500/[0.04]",     dot: "bg-red-400"     },
  task_deadline_today:   { icon: <Clock          className="h-3.5 w-3.5 text-amber-400"  />, accent: "border-l-amber-500/60",  bg: "bg-amber-500/[0.03]",   dot: "bg-amber-400"   },
  task_deadline_tomorrow:{ icon: <Clock          className="h-3.5 w-3.5 text-sky-400"    />, accent: "border-l-sky-500/40",    bg: "bg-sky-500/[0.02]",     dot: "bg-sky-400"     },
  event_upcoming:        { icon: <CalendarDays   className="h-3.5 w-3.5 text-violet-400" />, accent: "border-l-violet-500/60", bg: "bg-violet-500/[0.04]",  dot: "bg-violet-400"  },
  journal_reminder:      { icon: <BookOpen       className="h-3.5 w-3.5 text-indigo-400" />, accent: "border-l-indigo-500/40", bg: "bg-indigo-500/[0.03]",  dot: "bg-indigo-400"  },
  reminder_due:          { icon: <Bell           className="h-3.5 w-3.5 text-sky-300"    />, accent: "border-l-sky-500/60",    bg: "bg-sky-500/[0.04]",     dot: "bg-sky-300"     },
  achievement_completed: { icon: <Trophy         className="h-3.5 w-3.5 text-amber-400"  />, accent: "border-l-amber-500/60",  bg: "bg-amber-500/[0.04]",   dot: "bg-amber-400"   },
  reward_claimable:      { icon: <Gift           className="h-3.5 w-3.5 text-emerald-400"/>, accent: "border-l-emerald-500/60",bg: "bg-emerald-500/[0.04]", dot: "bg-emerald-400" },
} as const;

/* ── Component ─────────────────────────────────────────────────────────── */

export function NotificationCenter() {
  const router = useRouter();
  const { notifications, unreadCount, loading, markAsRead, markAllAsRead } = useNotifications();
  const { smartNotifications, dismissSmartNotification, clearAllSmart } = useNotificationStore();
  const { soundsEnabled, toggleMaster, notificationSounds, toggleNotificationSounds,
          achievementSounds, toggleAchievementSounds, taskSounds, toggleTaskSounds } = useSoundStore();

  const [showSettings, setShowSettings] = useState(false);

  /* Play ping on new unread DB notifications */
  const prevUnread = useRef(unreadCount);
  useEffect(() => {
    if (unreadCount > prevUnread.current) {
      const newestUnread = notifications.find((notification) => !notification.is_read);
      if (newestUnread?.kind !== "reminder_due") {
        playNotificationPing();
      }
    }
    prevUnread.current = unreadCount;
  }, [notifications, unreadCount]);

  const totalBadge = unreadCount + smartNotifications.length;

  async function handleDbOpen(n: Notification) {
    if (!n.is_read) await markAsRead(n.id);
    router.push(n.link || "/notifications");
  }

  function handleSmartOpen(n: SmartNotification) {
    dismissSmartNotification(n.id);
    if (n.link) router.push(n.link);
  }

  return (
    <Dropdown>
      {/* ── Trigger ─────────────────────────────────────────────────── */}
      <DropdownTrigger className="relative rounded-lg p-2 text-white/25 transition-all hover:bg-white/[0.04] hover:text-white/50">
        <Bell className="h-4 w-4" />
        {totalBadge > 0 && (
          <span className={cn(
            "absolute -right-0.5 -top-0.5 flex min-w-[16px] items-center justify-center rounded-full px-1 text-[9px] font-bold text-white",
            smartNotifications.length > 0 ? "bg-violet-500" : "bg-indigo-500",
          )}>
            {totalBadge > 9 ? "9+" : totalBadge}
          </span>
        )}
      </DropdownTrigger>

      {/* ── Panel ───────────────────────────────────────────────────── */}
      <DropdownContent className="w-[380px] p-0" align="end" portal>

        {/* Header */}
        <div className="flex items-center justify-between border-b border-white/[0.05] px-4 py-3">
          <div>
            <p className="text-[13px] font-bold text-white/80">Benachrichtigungen</p>
            <p className="text-[11px] text-white/30">
              {totalBadge > 0 ? `${totalBadge} neu` : "Alles auf dem neusten Stand"}
            </p>
          </div>

          <div className="flex items-center gap-1">
            {/* Sound toggle */}
            <button
              type="button"
              onClick={() => toggleMaster()}
              title={soundsEnabled ? "Sounds stumm stellen" : "Sounds aktivieren"}
              className={cn(
                "rounded-lg p-1.5 transition-colors",
                soundsEnabled
                  ? "text-white/40 hover:bg-white/[0.05] hover:text-white/70"
                  : "text-red-400/70 hover:bg-red-500/10 hover:text-red-400",
              )}
            >
              {soundsEnabled ? <Volume2 className="h-3.5 w-3.5" /> : <VolumeX className="h-3.5 w-3.5" />}
            </button>

            {/* Mark all read */}
            {unreadCount > 0 && (
              <button
                type="button"
                onClick={() => void markAllAsRead()}
                className="flex items-center gap-1 rounded-lg px-2 py-1.5 text-[11px] font-medium text-white/30 transition-colors hover:bg-white/[0.04] hover:text-white/60"
              >
                <CheckCheck className="h-3.5 w-3.5" />
                Alle lesen
              </button>
            )}

            {/* Settings gear */}
            <button
              type="button"
              onClick={() => setShowSettings((v) => !v)}
              className={cn(
                "rounded-lg p-1.5 transition-colors",
                showSettings
                  ? "bg-violet-500/15 text-violet-300"
                  : "text-white/30 hover:bg-white/[0.04] hover:text-white/60",
              )}
            >
              <Settings className="h-3.5 w-3.5" />
            </button>
          </div>
        </div>

        {/* Settings panel */}
        {showSettings && (
          <div className="border-b border-white/[0.05] bg-white/[0.015] px-4 py-3 space-y-2.5">
            <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-white/25">Sound-Einstellungen</p>
            {[
              { label: "Master (alle Sounds)", on: soundsEnabled,        toggle: toggleMaster },
              { label: "Benachrichtigungen",   on: notificationSounds,   toggle: toggleNotificationSounds },
              { label: "Achievements",         on: achievementSounds,    toggle: toggleAchievementSounds  },
              { label: "Aufgaben",             on: taskSounds,            toggle: toggleTaskSounds         },
            ].map(({ label, on, toggle }) => (
              <div key={label} className="flex items-center justify-between gap-3">
                <p className="text-[12px] text-white/55">{label}</p>
                <button
                  type="button"
                  onClick={toggle}
                  className={cn(
                    "relative h-5 w-9 rounded-full border transition-colors",
                    on
                      ? "border-violet-500/40 bg-violet-500/25"
                      : "border-white/[0.08] bg-white/[0.04]",
                  )}
                >
                  <span className={cn(
                    "absolute top-0.5 h-4 w-4 rounded-full border transition-all",
                    on
                      ? "left-4 border-violet-400/60 bg-violet-400"
                      : "left-0.5 border-white/20 bg-white/25",
                  )} />
                </button>
              </div>
            ))}
          </div>
        )}

        {/* Scrollable list */}
        <div className="max-h-[440px] overflow-y-auto">

          {/* ── Smart notifications ──────────────────────────────── */}
          {smartNotifications.length > 0 && (
            <div>
              <div className="flex items-center justify-between px-4 py-2">
                <div className="flex items-center gap-1.5">
                  <Sparkles className="h-3 w-3 text-violet-400/70" />
                  <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-violet-300/50">
                    Smart
                  </p>
                </div>
                <button
                  type="button"
                  onClick={clearAllSmart}
                  className="text-[10px] text-white/20 transition-colors hover:text-white/45"
                >
                  Alle schließen
                </button>
              </div>

              {smartNotifications.slice(0, 6).map((notif) => {
                const cfg = SMART_CFG[notif.type] ?? SMART_CFG.journal_reminder;
                return (
                  <div
                    key={notif.id}
                    className={cn(
                      "group relative flex items-start gap-3 border-b border-l-2 border-b-white/[0.03] px-4 py-3 transition-colors hover:bg-white/[0.025]",
                      cfg.accent,
                      cfg.bg,
                    )}
                  >
                    {/* Icon */}
                    <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-xl bg-white/[0.05]">
                      {cfg.icon}
                    </div>

                    {/* Content */}
                    <button
                      type="button"
                      onClick={() => handleSmartOpen(notif)}
                      className="min-w-0 flex-1 text-left"
                    >
                      <div className="flex items-start justify-between gap-2">
                        <p className="text-[12px] font-semibold text-white/80">{notif.title}</p>
                        <span className={cn("mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full", cfg.dot)} />
                      </div>
                      <p className="mt-0.5 line-clamp-1 text-[11px] text-white/35">
                        {notif.body}
                      </p>
                      {notif.link && (
                        <div className="mt-1 flex items-center gap-0.5 text-[10px] text-white/20 opacity-0 transition-opacity group-hover:opacity-100">
                          Öffnen <ChevronRight className="h-2.5 w-2.5" />
                        </div>
                      )}
                    </button>

                    {/* Dismiss X */}
                    <button
                      type="button"
                      onClick={() => dismissSmartNotification(notif.id)}
                      className="shrink-0 rounded-md p-1 text-white/15 opacity-0 transition-all group-hover:opacity-100 hover:bg-white/[0.05] hover:text-white/40"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </div>
                );
              })}
            </div>
          )}

          {/* ── DB notifications ─────────────────────────────────── */}
          {smartNotifications.length > 0 && notifications.length > 0 && (
            <div className="flex items-center gap-2 px-4 py-2">
              <div className="h-px flex-1 bg-white/[0.04]" />
              <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-white/20">
                Posteingang
              </p>
              <div className="h-px flex-1 bg-white/[0.04]" />
            </div>
          )}

          {loading ? (
            <div className="py-8 text-center text-[13px] text-white/20">Lädt…</div>
          ) : notifications.length === 0 && smartNotifications.length === 0 ? (
            <div className="flex flex-col items-center gap-3 py-10">
              <div className="flex h-10 w-10 items-center justify-center rounded-2xl border border-white/[0.06] bg-white/[0.02]">
                <Bell className="h-4.5 w-4.5 text-white/20" />
              </div>
              <p className="text-[13px] text-white/25">Keine Benachrichtigungen</p>
              <p className="text-[11px] text-white/15">Du bist auf dem neusten Stand.</p>
            </div>
          ) : (
            notifications.slice(0, 8).map((n) => (
              <button
                key={n.id}
                type="button"
                onClick={() => void handleDbOpen(n)}
                className={cn(
                  "flex w-full items-start gap-3 border-b border-white/[0.03] px-4 py-3 text-left transition-colors hover:bg-white/[0.025]",
                  !n.is_read && "bg-indigo-500/[0.035]",
                )}
              >
                <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white/[0.05]">
                  {n.kind !== "reminder_due" && n.actor ? (
                    <Avatar
                      src={n.actor.avatar_url}
                      name={n.actor.full_name || n.actor.email}
                      size="sm"
                    />
                  ) : (
                    <DbNotifIcon n={n} />
                  )}
                </div>

                <div className="min-w-0 flex-1">
                  <div className="flex items-start justify-between gap-2">
                    <p className="text-[12px] font-medium text-white/75">{n.title}</p>
                    {!n.is_read && (
                      <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-indigo-400" />
                    )}
                  </div>
                  {n.body && (
                    <p className="mt-0.5 line-clamp-2 text-[11px] text-white/30">{n.body}</p>
                  )}
                  <div className="mt-1.5 flex items-center gap-1.5 text-[10px] text-white/20">
                    <DbNotifIcon n={n} />
                    <span>{formatRelativeDate(n.created_at)}</span>
                  </div>
                </div>
              </button>
            ))
          )}
        </div>

        {/* Footer */}
        <div className="border-t border-white/[0.05] px-4 py-2.5">
          <button
            type="button"
            onClick={() => router.push("/notifications")}
            className="w-full rounded-xl py-2 text-[11px] text-white/25 transition-colors hover:bg-white/[0.03] hover:text-white/50"
          >
            Alle anzeigen
          </button>
        </div>
      </DropdownContent>
    </Dropdown>
  );
}
