import { useNotifications } from "@/hooks/useNotifications";
import { useScreenContext } from "@/src/contexts/ScreenContext";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import { FaRegBell } from "react-icons/fa";

const DropdownNotification = () => {
  const { notifications, notificar, error } = useNotifications();

  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showOnlyUnread, setShowOnlyUnread] = useState(false);

  const notReads: number = notifications?.filter(
    (notification) => notification.status_notificacao == "não lida"
  ).length;

  const trigger = useRef<any>(null);
  const dropdown = useRef<any>(null);

  useEffect(() => {
    const clickHandler = ({ target }: MouseEvent) => {
      if (!dropdown.current) return;
      if (
        !dropdownOpen ||
        dropdown.current.contains(target) ||
        trigger.current.contains(target)
      )
        return;
      setDropdownOpen(false);
    };
    document.addEventListener("click", clickHandler);
    return () => document.removeEventListener("click", clickHandler);
  });

  useEffect(() => {
    const keyHandler = ({ keyCode }: KeyboardEvent) => {
      if (!dropdownOpen || keyCode !== 27) return;
      setDropdownOpen(false);
    };
    document.addEventListener("keydown", keyHandler);
    return () => document.removeEventListener("keydown", keyHandler);
  });

  const route = useRouter();
  const { isMobile } = useScreenContext();

  // "2026-06-17 07:09:13" -> Date local (evita parsing ambíguo do new Date())
  const parseDataHora = (value: string): Date | null => {
    if (!value) return null;
    const [datePart, timePart = "00:00:00"] = value.split(" ");
    const [year, month, day] = datePart.split("-").map(Number);
    const [hour, minute, second] = timePart.split(":").map(Number);
    if (!year || !month || !day) return null;
    return new Date(year, month - 1, day, hour || 0, minute || 0, second || 0);
  };

  const isSameDay = (a: Date, b: Date) =>
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate();

  const getGroupLabel = (dateStr: string): string => {
    const date = parseDataHora(dateStr);
    if (!date) return "Anteriores";

    const today = new Date();
    const yesterday = new Date();
    yesterday.setDate(today.getDate() - 1);

    if (isSameDay(date, today)) return "Hoje";
    if (isSameDay(date, yesterday)) return "Ontem";

    return date.toLocaleDateString("pt-BR", {
      day: "2-digit",
      month: "long",
      year: date.getFullYear() !== today.getFullYear() ? "numeric" : undefined,
    });
  };

  const formatHour = (dateStr: string): string => {
    const date = parseDataHora(dateStr);
    if (!date) return "";
    return date.toLocaleTimeString("pt-BR", {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getInitials = (text: string) =>
    text
      ?.split(" ")
      .slice(0, 2)
      .map((w) => w[0]?.toUpperCase())
      .join("") || "?";

  const visibleNotifications = (notifications ?? [])
    .filter((n) => (showOnlyUnread ? n.status_notificacao === "não lida" : true))
    .slice(0, 15);

  // Agrupa mantendo a ordem original (assumindo que a API já retorna ordenado por data desc)
  const groupedNotifications = visibleNotifications.reduce(
    (groups: Record<string, typeof visibleNotifications>, notification: any) => {
      const label = getGroupLabel(notification.data_hora_criacao_formatada);
      if (!groups[label]) groups[label] = [];
      groups[label].push(notification);
      return groups;
    },
    {}
  );

  return (
    <li className="relative">
      <div
        ref={trigger}
        onClick={() => setDropdownOpen(!dropdownOpen)}
        className="cursor-pointer relative flex h-8.5 w-8.5 items-center justify-center rounded-full border-[0.5px] border-stroke bg-gray hover:text-primary dark:border-strokedark dark:bg-meta-4 dark:text-white"
      >
        <span
          className={`absolute -top-0.5 right-0 z-1 h-2 w-2 rounded-full bg-meta-1 ${!!notReads === false ? "hidden" : "inline"
            }`}
        >
          <span className="absolute -z-1 inline-flex h-full w-full animate-ping rounded-full bg-meta-1 opacity-75"></span>
        </span>
        <FaRegBell
          id={!!notReads ? "bell-area" : "bell-area-empty"}
          title="Notificações"
          size={19}
        />
      </div>

      <div
        id="notificationsDropdown"
        ref={dropdown}
        onFocus={() => setDropdownOpen(true)}
        onBlur={() => setDropdownOpen(false)}
        className={`${isMobile ? "left-0 right-0 mx-auto fixed" : "absolute"
          } -right-27 mt-2.5 flex w-[430px] flex-col rounded-2xl border border-stroke bg-white shadow-lg m-0 dark:border-strokedark dark:bg-boxdark sm:right-0 overflow-hidden ${dropdownOpen === true ? "block" : "hidden"
          }`}
      >
        {/* Header */}
        <div
          id="notificationsDropdownHead"
          className="px-5 pt-4 pb-3 flex items-center justify-between bg-white dark:bg-boxdark"
        >
          <span className="font-bold text-[17px] text-black dark:text-white">
            Notificações
          </span>

          <label className="flex items-center gap-2 cursor-pointer select-none">
            <span className="text-sm text-primary font-medium">
              Mostrar apenas não lidas
            </span>
            <span
              onClick={() => setShowOnlyUnread((prev) => !prev)}
              className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${showOnlyUnread ? "bg-primary" : "bg-gray-300 dark:bg-meta-4"
                }`}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${showOnlyUnread ? "translate-x-4" : "translate-x-0.5"
                  }`}
              />
            </span>
          </label>
        </div>

        {/* Lista agrupada */}
        <div
          id="notificationsDropdownBody"
          className="max-h-[380px] overflow-y-auto overflow-x-hidden w-full"
        >
          {Object.keys(groupedNotifications).length === 0 && (
            <div className="px-5 py-8 text-center text-sm text-body-color dark:text-gray-400">
              Nenhuma notificação
            </div>
          )}

          {Object.entries(groupedNotifications).map(([label, items]) => (
            <div key={label}>
              {/* Cabeçalho do grupo (Hoje / Ontem / data) */}
              <div className="px-5 py-2 flex items-center justify-between border-b border-stroke dark:border-strokedark bg-gray-50 dark:bg-white/5">
                <span className="text-xs font-medium text-body-color dark:text-gray-400 capitalize">
                  {label}
                </span>
                {label === "Hoje" && (
                  <button
                    className="text-xs font-medium text-primary hover:underline"
                    onClick={() => {
                      // aqui entraria a chamada para marcar todas como lidas
                    }}
                  >
                    Marcar todas como lidas
                  </button>
                )}
              </div>

              <ul className="flex flex-col gap-1 px-2 py-2">
                {items.map((notification: any, index) => {
                  const isUnread = notification.status_notificacao === "não lida";
                  return (
                    <li
                      key={index}
                      className={`flex flex-row items-start gap-3 relative cursor-pointer p-3 rounded-xl transition-colors ${isUnread
                        ? "bg-blue-50 hover:bg-blue-100 dark:bg-white/5 dark:hover:bg-white/10"
                        : "hover:bg-black/5 dark:hover:bg-white/5"
                        }`}
                      onClick={() => {
                        setDropdownOpen(false);
                        route.push(
                          `notifications?id=${notification.id_notificacao}`
                        );
                      }}
                    >
                      {/* Avatar */}
                      <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary font-bold text-xs">
                        {getInitials(notification.tipo_notificacao)}
                      </span>

                      <div className="relative w-full pr-4">
                        <div className="flex items-center gap-2">
                          <h4 className="font-semibold text-sm text-black dark:text-white">
                            {notification.titulo_notificacao}
                          </h4>
                          <span className="text-xs text-body-color dark:text-gray-400 whitespace-nowrap">
                            {formatHour(notification.data_hora_criacao_formatada)}
                          </span>
                        </div>
                        <p className="text-sm text-body-color dark:text-gray-300 mt-0.5 line-clamp-2">
                          {notification.conteudo_notificacao || notification.tipo_notificacao}
                        </p>
                      </div>

                      {/* Dot de não lida */}
                      {isUnread && (
                        <span className="absolute top-3 right-2 h-2.5 w-2.5 rounded-full bg-blue-500" />
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </div>

        {/* Footer */}
        <div
          id="notificationsDropdownFooter"
          className="p-3 flex items-center justify-center relative border-t border-stroke dark:border-strokedark"
        >
          <button
            className="rounded-full px-5 py-2 text-primary  text-sm font-bold hover:opacity-90 transition-opacity"
            onClick={() => {
              setDropdownOpen(!dropdownOpen);
              route.push("notifications");
            }}
          >
            Ver Todas Notificações
          </button>
          <button
            className="absolute right-3 h-4 w-4 bg-primary rounded-full hover:bg-transparent"
            onClick={() =>
              notificar({
                conteudo_notificacao: "Texto de exemplo de notificação",
                tipo_notificacao: "teste",
                titulo_notificacao: "Nova notificação",
              })
            }
          ></button>
        </div>
      </div>
    </li>
  );
};

export default DropdownNotification;