"use client";

import { useState, useEffect } from "react";
import { formatDistanceToNow } from "date-fns";
import { Bell, Check, CheckCheck, MessageSquare, UserPlus, Briefcase } from "lucide-react";
import { useRouter } from "next/navigation";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";

import { useGetNotifications } from "@/features/notifications/api/use-get-notifications";
import { useMarkNotificationsRead } from "@/features/notifications/api/use-mark-notifications-read";
import { useGetUnreadCount } from "@/features/notifications/api/use-get-unread-count";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";

interface Notification {
  id: string;
  type: "MENTION" | "TASK_ASSIGNED" | "WORKSPACE_ADDED" | "COMMENT_REPLY";
  title: string;
  message: string;
  isRead: boolean;
  createdAt: string;
  task?: {
    id: string;
    name: string;
  };
  comment?: {
    id: string;
    content: string;
  };
  workspace: {
    id: string;
    name: string;
  };
  data?: any;
}

const NotificationIcon = ({ type }: { type: string }) => {
  switch (type) {
    case "MENTION":
      return <MessageSquare className="h-4 w-4 text-blue-500" />;
    case "TASK_ASSIGNED":
      return <Briefcase className="h-4 w-4 text-green-500" />;
    case "WORKSPACE_ADDED":
      return <UserPlus className="h-4 w-4 text-purple-500" />;
    case "COMMENT_REPLY":
      return <MessageSquare className="h-4 w-4 text-orange-500" />;
    default:
      return <Bell className="h-4 w-4 text-gray-500" />;
  }
};

export const NotificationsDropdown = () => {
  const router = useRouter();
  const workspaceId = useWorkspaceId();
  const [isOpen, setIsOpen] = useState(false);
  
  const { data: notifications = [], refetch } = useGetNotifications({ workspaceId });
  const { data: unreadData, refetch: refetchCount } = useGetUnreadCount({ workspaceId });
  const { mutate: markAsRead } = useMarkNotificationsRead();

  const unreadCount = unreadData?.count || 0;

  const handleNotificationClick = (notification: Notification) => {
    // Mark as read if not already read
    if (!notification.isRead) {
      markAsRead({ json: { notificationIds: [notification.id] } });
    }

    // Navigate to the relevant page
    if (notification.task) {
      if (notification.comment) {
        // Navigate to task and scroll to comment
        router.push(`/workspaces/${notification.workspace.id}/tasks/${notification.task.id}?comment=${notification.comment.id}`);
      } else {
        // Navigate to task
        router.push(`/workspaces/${notification.workspace.id}/tasks/${notification.task.id}`);
      }
    } else if (notification.type === "WORKSPACE_ADDED") {
      // Navigate to workspace
      router.push(`/workspaces/${notification.workspace.id}`);
    }

    setIsOpen(false);
  };

  const handleMarkAllAsRead = () => {
    const unreadIds = notifications
      .filter((n: Notification) => !n.isRead)
      .map((n: Notification) => n.id);
    
    if (unreadIds.length > 0) {
      markAsRead({ json: { notificationIds: unreadIds } });
    }
  };

  // Refresh notifications when dropdown opens
  useEffect(() => {
    if (isOpen) {
      refetch();
      refetchCount();
    }
  }, [isOpen, refetch, refetchCount]);

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="sm" className="relative h-8 w-8 p-0">
          <Bell className="h-4 w-4" />
          {unreadCount > 0 && (
            <Badge 
              className="absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs bg-red-500 hover:bg-red-500"
            >
              {unreadCount > 99 ? "99+" : unreadCount}
            </Badge>
          )}
        </Button>
      </DropdownMenuTrigger>
      
      <DropdownMenuContent 
        align="end" 
        className="w-80 p-0"
        onCloseAutoFocus={(e) => e.preventDefault()}
      >
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-semibold">Notifications</h3>
          {unreadCount > 0 && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleMarkAllAsRead}
              className="text-xs"
            >
              <CheckCheck className="h-3 w-3 mr-1" />
              Mark all read
            </Button>
          )}
        </div>

        <ScrollArea className="max-h-96">
          {notifications.length === 0 ? (
            <div className="p-4 text-center text-gray-500 text-sm">
              No notifications yet
            </div>
          ) : (
            <div className="divide-y">
              {notifications.map((notification: Notification) => (
                <div
                  key={notification.id}
                  onClick={() => handleNotificationClick(notification)}
                  className={`p-4 hover:bg-gray-50 cursor-pointer transition-colors ${
                    !notification.isRead ? "bg-blue-50 border-l-2 border-l-blue-500" : ""
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5">
                      <NotificationIcon type={notification.type} />
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <div className="font-medium text-sm text-gray-900">
                          {notification.title}
                        </div>
                        <div className="text-xs text-gray-500 whitespace-nowrap">
                          {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true })}
                        </div>
                      </div>
                      
                      <div className="text-sm text-gray-600 mt-1">
                        {notification.message}
                      </div>

                      {notification.task && (
                        <div className="text-xs text-blue-600 mt-2 font-medium">
                          📋 {notification.task.name}
                        </div>
                      )}
                      
                      {notification.workspace && (
                        <div className="text-xs text-gray-500 mt-1">
                          in {notification.workspace.name}
                        </div>
                      )}
                    </div>

                    {!notification.isRead && (
                      <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0" />
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </ScrollArea>

        {notifications.length > 0 && (
          <>
            <Separator />
            <div className="p-2">
              <Button
                variant="ghost"
                size="sm"
                className="w-full text-xs"
                onClick={() => {
                  router.push("/notifications");
                  setIsOpen(false);
                }}
              >
                View all notifications
              </Button>
            </div>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}; 