"use client";

import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useNotificationStore, Notification } from "@/hooks/useNotificationStore";
import { useAuthStore } from "@/hooks/useAuthStore";
import { Bell, UserPlus, Info, CheckCheck, AtSign } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "@/components/ui/popover";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";

export function NotificationBell() {
  const { notifications, unreadCount, fetchNotifications, markAsRead, markAllAsRead } = useNotificationStore();
  const { user } = useAuthStore();
  const router = useRouter();

  useEffect(() => {
    if (user) {
      fetchNotifications();
    }
  }, [user, fetchNotifications]);

  const getIcon = (type: string) => {
    switch (type) {
      case 'mention': return <AtSign className="h-4 w-4 text-primary" aria-hidden="true" />;
      case 'assignment': return <UserPlus className="h-4 w-4 text-emerald-500" aria-hidden="true" />;
      default: return <Info className="h-4 w-4 text-blue-500" aria-hidden="true" />;
    }
  };

  return (
    <Popover>
      <Tooltip>
        <TooltipTrigger asChild>
          <PopoverTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="relative text-muted-foreground hover:bg-muted/50 transition-all focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2"
              aria-label={`Benachrichtigungen${unreadCount > 0 ? ` (${unreadCount} ungelesen)` : ""}`}
            >
              <Bell className="h-5 w-5" />
              {unreadCount > 0 && (
                <span className="absolute top-2 right-2.5 flex h-2.5 w-2.5">
                  <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-red-500 border-2 border-background"></span>
                </span>
              )}
            </Button>
          </PopoverTrigger>
        </TooltipTrigger>
        <TooltipContent side="bottom">Benachrichtigungen</TooltipContent>
      </Tooltip>
      <PopoverContent className="w-80 p-0" align="end">
        <div className="flex items-center justify-between p-4 border-b border-border bg-muted/10">
          <h4 className="text-sm font-semibold text-foreground">Benachrichtigungen</h4>
          {unreadCount > 0 && (
            <Button variant="ghost" size="sm" className="h-7 text-xs font-semibold gap-1" onClick={() => markAllAsRead()}>
              <CheckCheck className="h-3 w-3" /> Alle lesen
            </Button>
          )}
        </div>
        <ScrollArea className="h-80">
          {notifications.length === 0 ? (
            <div className="py-12 text-center text-xs text-muted-foreground">
              Keine neuen Benachrichtigungen.
            </div>
          ) : (
            <div className="divide-y divide-border">
              {notifications.map((n) => (
                <div
                  key={n.id}
                  role="button"
                  tabIndex={0}
                  aria-label={`${n.title}. ${n.content}. ${!n.read ? 'Ungelesen' : ''}`}
                  className={cn(
                    "p-4 hover:bg-muted/30 transition-colors relative group cursor-pointer focus-visible:bg-muted/50 focus-visible:outline-none",
                    !n.read && "bg-primary/5"
                  )}
                  onClick={() => {
                    if (!n.read) markAsRead(n.id);
                    if (n.link) router.push(n.link);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      if (!n.read) markAsRead(n.id);
                      if (n.link) router.push(n.link);
                    }
                  }}
                >
                  <div className="flex gap-3">
                    <div className="mt-1">{getIcon(n.type)}</div>
                    <div className="space-y-1 flex-1">
                      <p className="text-xs font-bold leading-none text-foreground">{n.title}</p>
                      <p className="text-xs text-muted-foreground leading-relaxed">{n.content}</p>
                      <p className="text-xs text-muted-foreground pt-1">
                        {new Date(n.created_at).toLocaleString()}
                      </p>
                    </div>
                  </div>
                  {!n.read && (
                    <span className="absolute top-4 right-4 h-1.5 w-1.5 rounded-full bg-primary"></span>
                  )}
                </div>
              ))}
            </div>
          )}
        </ScrollArea>
      </PopoverContent>
    </Popover>
  );
}
