"use client";

import { useState, useRef, useEffect } from "react";
import { useTranslations, useLocale } from "next-intl";
import { useRouter } from "@/i18n/navigation";
import { useQueryClient } from "@tanstack/react-query";
import {
  usePMNotificationControllerGetNotificationsV1 as usePMNotificationsGet,
  usePMNotificationControllerGetUnreadCountV1 as usePMNotificationsUnreadCount,
  usePMNotificationControllerMarkAsReadV1 as usePMNotificationsMarkAsRead,
  usePMNotificationControllerMarkAllAsReadV1 as usePMNotificationsMarkAllAsRead,
} from "@/api/user/practice-manager-notifications/practice-manager-notifications";

const NOTIFICATION_TITLE_ES: Record<string, string> = {
  "Subscription Cancelled": "Suscripción Cancelada",
  "Subscription Canceled": "Suscripción Cancelada",
  "New Subscription": "Nueva Suscripción",
  "Subscription Renewed": "Suscripción Renovada",
  "Subscription Expired": "Suscripción Expirada",
  "Subscription Updated": "Suscripción Actualizada",
  "Screening Completed": "Evaluación Completada",
  "Screening Complete": "Evaluación Completa",
  "New User": "Nuevo Usuario",
  "New User Registration": "Nuevo Registro de Usuario",
  "New Lead": "Nuevo Prospecto",
  "New Support Ticket": "Nuevo Ticket de Soporte",
  "Support Ticket Updated": "Ticket de Soporte Actualizado",
  "New Client Added": "Nuevo Cliente Agregado",
  "Client Added": "Cliente Agregado",
  "System Notification": "Notificación del Sistema",
};

export default function NotificationDropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const t = useTranslations("practiceManager");
  const locale = useLocale();
  const router = useRouter();
  const queryClient = useQueryClient();

  // Fetch notifications from API (latest 5 for dropdown)
  const { data: notificationsData, isLoading } = usePMNotificationsGet(
    { limit: 5 }
  );
  const rawData = notificationsData as any;
  const notifications: any[] =
    Array.isArray(rawData?.data) ? rawData.data :
    Array.isArray(rawData?.data?.data) ? rawData.data.data :
    Array.isArray(rawData?.data?.items) ? rawData.data.items :
    Array.isArray(rawData) ? rawData : [];

  // Fetch unread count from API
  const { data: unreadData } = usePMNotificationsUnreadCount();
  const unreadCount: number = (unreadData as any)?.data?.unread_count ?? (unreadData as any)?.unread_count ?? 0;

  // Mark as read mutation
  const markAsReadMutation = usePMNotificationsMarkAsRead({
    mutation: {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['/v1/practice-manager/notifications'] });
        queryClient.invalidateQueries({ queryKey: ['/v1/practice-manager/notifications/unread-count'] });
      },
    },
  });

  // Mark all as read mutation
  const markAllAsReadMutation = usePMNotificationsMarkAllAsRead({
    mutation: {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['/v1/practice-manager/notifications'] });
        queryClient.invalidateQueries({ queryKey: ['/v1/practice-manager/notifications/unread-count'] });
      },
    },
  });

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const formatTimeAgo = (dateStr: string): string => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMins < 1) {
      return t("notifications.justNow");
    }
    if (diffMins < 60) {
      return `${diffMins} ${t("notifications.minutesAgo")}`;
    }
    if (diffHours < 24) {
      return `${diffHours} ${t("notifications.hoursAgo")}`;
    }
    return `${diffDays} ${t("notifications.daysAgo")}`;
  };

  const handleMarkAsRead = (id: string) => {
    markAsReadMutation.mutate({ id });
  };

  const handleMarkAllAsRead = () => {
    markAllAsReadMutation.mutate();
  };

  const handleNotificationClick = (notification: any) => {
    if (!notification.is_read) {
      handleMarkAsRead(String(notification.uuid || notification.id));
    }
    setIsOpen(false);

    // Navigate based on notification type
    const data = notification.data || {};
    switch (notification.type) {
      case "screening_complete": {
        const reportUuid = data.screening_uuid || data.screening_id;
        if (reportUuid) {
          router.push(`/practice-manager/report/${reportUuid}`);
        } else {
          router.push("/practice-manager/dashboard");
        }
        break;
      }
      case "system":
        router.push("/practice-manager/patients");
        break;
      case "client_added":
        router.push("/practice-manager/patients");
        break;
      case "subscription":
        router.push("/practice-manager/subscription");
        break;
      default:
        router.push("/practice-manager/dashboard");
        break;
    }
  };

  // Navigate to view all notifications
  const handleViewAllNotifications = () => {
    setIsOpen(false);
    router.push("/practice-manager/notifications");
  };

  // Bell icon for all notification types (matching Figma design)
  const NotificationIcon = () => (
    <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0">
      <svg className="w-5 h-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
      </svg>
    </div>
  );

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Bell Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition cursor-pointer"
      >
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            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>
        {/* Badge */}
        {unreadCount > 0 && (
          <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] flex items-center justify-center px-1 text-[10px] font-bold text-white bg-red-500 rounded-full">
            {unreadCount > 9 ? "9+" : unreadCount}
          </span>
        )}
      </button>

      {/* Dropdown */}
      {isOpen && (
        <div className="fixed left-2 right-2 top-16 sm:absolute sm:left-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-96 bg-white rounded-2xl shadow-xl border border-gray-100 z-50 overflow-hidden">
          {/* Header - Title + Close Button */}
          <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
            <h3 className="text-base font-semibold text-gray-900">
              {t("notifications.title")}
            </h3>
            <button
              onClick={() => setIsOpen(false)}
              className="text-gray-400 hover:text-gray-600 transition cursor-pointer"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Notification List */}
          <div className="max-h-96 overflow-y-auto">
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#3B9EC9]"></div>
              </div>
            ) : notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 px-4">
                <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                  <svg className="w-8 h-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                  </svg>
                </div>
                <p className="text-sm font-medium text-gray-900 mb-1">
                  {t("notifications.noNotifications")}
                </p>
                <p className="text-xs text-gray-500">
                  {t("notifications.noNotificationsDesc")}
                </p>
              </div>
            ) : (
              <div>
                {notifications.map((notification: any) => (
                  <button
                    key={notification.id}
                    onClick={() => handleNotificationClick(notification)}
                    className="w-full flex items-start gap-3 px-4 py-4 text-left hover:bg-gray-50 transition cursor-pointer border-b border-gray-100 last:border-0"
                  >
                    {/* Bell Icon */}
                    <NotificationIcon />

                    {/* Content - Title and Message */}
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-gray-900">
                        {locale === 'es' ? ((notification as any).title_es || NOTIFICATION_TITLE_ES[notification.title] || notification.title) : notification.title}
                      </p>
                      <p className="text-sm text-gray-500 mt-0.5">
                        {locale === 'es' ? ((notification as any).message_es || notification.message) : notification.message}
                      </p>
                    </div>

                    {/* Right Side - Unread Dot and Time */}
                    <div className="flex flex-col items-end gap-1 flex-shrink-0">
                      {!notification.is_read && (
                        <span className="w-2 h-2 rounded-full bg-red-500"></span>
                      )}
                      <p className="text-xs text-gray-400">
                        {notification.created_at ? formatTimeAgo(notification.created_at) : ""}
                      </p>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Footer - Mark all as read + View All Button */}
          {notifications.length > 0 && (
            <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100">
              {/* Mark all as read */}
              <button
                onClick={handleMarkAllAsRead}
                className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 transition cursor-pointer"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" />
                </svg>
                {t("notifications.markAllRead")}
              </button>

              {/* View All Button */}
              <button
                onClick={handleViewAllNotifications}
                className="px-4 py-2 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
              >
                {t("notifications.viewAll")}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
