"use client";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { useIsMobile, useResolvedAction } from "@/hooks";
import { useProject } from "@/contexts/project-context";
import { useNotificationMutations, useNotifications } from "@/hooks/use-notifications";
import { Link } from "@/i18n/routing";
import type { NotificationListItem } from "@/lib/api/types";
import { getNotificationHref, isExternalHref } from "@/lib/utils/notification-navigation";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { ArrowLeft, ArrowRight, Bell, Eye, Loader2, MoreHorizontal, Trash2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";

// Notification Bell Icon (green outline)
function NotificationBellIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
    >
      <path
        d="M8.01334 1.33334C5.66001 1.33334 3.74667 3.24668 3.74667 5.60001V7.22668C3.74667 7.66668 3.56667 8.32668 3.34001 8.70001L2.54001 10.0467C2.02667 10.9067 2.38001 11.8667 3.32001 12.1933C6.38001 13.2467 9.64001 13.2467 12.7 12.1933C13.58 11.8933 13.96 10.8467 13.48 10.0467L12.68 8.70001C12.46 8.32668 12.28 7.66668 12.28 7.22668V5.60001C12.28 3.25334 10.36 1.33334 8.01334 1.33334Z"
        stroke="currentColor"
        strokeWidth="1.2"
        strokeMiterlimit="10"
        strokeLinecap="round"
      />
      <path
        d="M9.24666 1.53334C9.04666 1.48001 8.84 1.44001 8.62666 1.41334C7.97333 1.33334 7.34666 1.38001 6.76666 1.53334C6.95333 1.06668 7.44 0.733337 8.00666 0.733337C8.57333 0.733337 9.06 1.06668 9.24666 1.53334Z"
        stroke="currentColor"
        strokeWidth="1.2"
        strokeMiterlimit="10"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M10.0133 12.4467C10.0133 13.5533 9.11999 14.4467 8.01332 14.4467C7.46332 14.4467 6.95332 14.22 6.58666 13.8533C6.21999 13.4867 5.99332 12.9767 5.99332 12.4467"
        stroke="currentColor"
        strokeWidth="1.2"
        strokeMiterlimit="10"
      />
    </svg>
  );
}

const MAX_NOTIFICATION_BADGE_COUNT = 99;
const DROPDOWN_NOTIFICATIONS_LIMIT = 15;

export function NotificationsButton() {
  const t = useTranslations();
  const locale = useLocale();
  const { formatDateTime } = useFormattedDate();
  const { projectId, isHydrated: isProjectHydrated } = useProject();
  const isMobile = useIsMobile();

  const { notifications, unreadCount, isLoading } = useNotifications({
    per_page: DROPDOWN_NOTIFICATIONS_LIMIT,
    ...(projectId ? { project_id: projectId } : {}),
  }, {
    skip: !isProjectHydrated,
  });
  const { markAsRead, markAllAsRead, clearAll, isLoading: isMutating } =
    useNotificationMutations(projectId ? { project_id: projectId } : {});
  const markReadAction = useResolvedAction(
    { actionKey: "notifications.mark_read" },
    "inline",
  );
  const [open, setOpen] = useState(false);

  const unreadBadgeLabel = unreadCount > MAX_NOTIFICATION_BADGE_COUNT
    ? `+${MAX_NOTIFICATION_BADGE_COUNT}`
    : unreadCount;

  const handleMarkAllRead = async () => {
    if (notifications.length === 0 || unreadCount === 0) return;

    try {
      await markAllAsRead();
    } catch {
      // Error toast handled in hook.
    }
  };

  const handleDeleteAll = async () => {
    if (notifications.length === 0) return;

    try {
      await clearAll();
    } catch {
      // Error toast handled in hook.
    }
  };

  const handleNotificationClick = (notification: NotificationListItem) => {
    setOpen(false);

    if (notification.read || !markReadAction.allowed) return;

    void markAsRead(notification.id).catch(() => {
      // Error toast handled in hook.
    });
  };

  const isBusy = isLoading || isMutating;
  const triggerButton = (
    <Button
      variant="ghost"
      size="icon"
      className="relative h-9 w-9 rounded-lg"
      suppressHydrationWarning
    >
      <Bell className="h-5 w-5" />
      {unreadCount > 0 && (
        <Badge
          variant="destructive"
          className="absolute -top-1 -end-1 h-5 min-w-5 px-1 flex items-center justify-center text-xs"
        >
          {unreadBadgeLabel}
        </Badge>
      )}
    </Button>
  );
  const notificationsPanel = (
    <>
      <div className="flex items-center justify-between px-4 py-4 border-b border-border">
        <h3 className="text-base font-semibold text-foreground">{t("notifications.title")}</h3>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="size-8 flex items-center justify-center border border-border rounded-lg hover:bg-muted/50 transition-colors">
              <MoreHorizontal className="size-4 " />
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-48 rounded-xl p-2">
            <DropdownMenuItem
              onClick={() => void handleMarkAllRead()}
              className="flex items-center gap-4 px-4 py-2 cursor-pointer text-nowrap"
              disabled={isBusy || notifications.length === 0 || unreadCount === 0}
            >
              <Eye className="size-5  hover:text-white!" />

              <span className="text-sm ">{t("notifications.markAllRead")}</span>
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => void handleDeleteAll()}
              className="flex items-center gap-4 px-4 py-2 cursor-pointer"
              disabled={isBusy || notifications.length === 0}
            >
              <Trash2 className="size-5 hover:text-white!" />
              <span className="text-sm ">{t("notifications.deleteAll")}</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      <div className="overflow-y-auto max-h-[350px]">
        <div className="p-2 space-y-1">
          {isLoading ? (
            <div className="py-8 flex items-center justify-center text-muted-foreground">
              <Loader2 className="size-5 animate-spin" />
            </div>
          ) : notifications.length === 0 ? (
            <div className="py-8 text-center text-sm text-muted-foreground">
              {t("notifications.empty")}
            </div>
          ) : (
            notifications.map((notification) => {
              const href = getNotificationHref(notification);
              const rawData =
                notification.raw && typeof notification.raw.data === "object" && notification.raw.data !== null
                  ? (notification.raw.data as { message?: unknown; data?: { message?: unknown } })
                  : null;
              const rawMessage =
                typeof rawData?.message === "string"
                  ? rawData.message
                  : typeof rawData?.data?.message === "string"
                    ? rawData.data.message
                    : null;
              const message =
                rawMessage && rawMessage.trim().length > 0
                  ? rawMessage
                  : notification.description;
              const className = `w-full text-start flex items-start gap-3 p-4 rounded-lg transition-colors ${!notification.read ? "bg-primary/5 dark:bg-primary/10" : "hover:bg-muted/50"
                }`;
              const content = (
                <>
                  <div className="size-8 rounded-full bg-background dark:bg-muted flex items-center justify-center shrink-0 shadow-sm border border-border/50">
                    <NotificationBellIcon className="size-4 text-primary" />
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className="flex flex-col gap-1">
                      <h4 className="text-sm font-bold text-foreground break-words">
                        {message}
                      </h4>
                      {/* <p className="text-xs text-muted-foreground break-words">
                        {notification.title}
                      </p> */}
                    </div>
                  </div>

                  <span className="text-xs text-muted-foreground whitespace-nowrap shrink-0 pt-0.5">
                    {formatDateTime(notification.createdAt)}
                  </span>
                </>
              );

              if (isExternalHref(href)) {
                return (
                  <a
                    key={notification.id}
                    href={href}
                    target="_blank"
                    rel="noreferrer"
                    onClick={() => handleNotificationClick(notification)}
                    className={className}
                  >
                    {content}
                  </a>
                );
              }

              return (
                <Link
                  key={notification.id}
                  href={href}
                  onClick={() => handleNotificationClick(notification)}
                  className={className}
                >
                  {content}
                </Link>
              );
            })
          )}
        </div>
      </div>

      <div className="bg-muted/30 border-t border-border px-6 py-3 rounded-b-2xl">
        <Link
          href="/notifications"
          onClick={() => setOpen(false)}
          className="flex items-center gap-2 text-primary font-medium hover:opacity-80 transition-opacity"
        >
          <span>{t("notifications.allNotifications")}</span>
          {locale === "ar" ? <ArrowLeft className="size-5" /> : <ArrowRight className="size-5" />}
        </Link>
      </div>
    </>
  );

  if (isMobile) {
    return (
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild suppressHydrationWarning>
          {triggerButton}
        </DialogTrigger>
        <DialogContent
          showCloseButton={false}
          className="top-15! translate-y-0! w-[calc(100vw-2rem)] max-w-[420px] overflow-hidden rounded-2xl border-border p-0 gap-0 shadow-lg"
        >
          <DialogTitle className="sr-only">{t("notifications.title")}</DialogTitle>
          {notificationsPanel}
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild suppressHydrationWarning>
        {triggerButton}
      </PopoverTrigger>

      <PopoverContent
        align={locale === "ar" ? "end" : "start"}
        dir={locale === "ar" ? "rtl" : "ltr"}
        className="w-[380px] p-0 rounded-2xl border-border shadow-lg"
        sideOffset={8}
      >
        {notificationsPanel}
      </PopoverContent>
    </Popover>
  );
}
