"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Bell, Check, Clock, MoreHorizontal, Eye, Trash2 } from "lucide-react";

import Loader from "@/components/ui/Loader";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { useNotifications } from "./useNotifications";
import NotificationMessage from "./NotificationMessage";
import CommunityLoadError from "@/features/community/components/CommunityLoadError";

export default function Notification() {
  const { t } = useTranslation();
  const {
    isLoading,
    isError,
    error,
    refetch,
    deleteMutation,
    open,
    setOpen,
    selectedLanguage,
    selectedNotification,
    setSelectedNotification,
    markReadMutation,
    displayNotifications,
    openNotificationModal,
    openTarget,
    isOpeningTarget,
    markAsRead,
    markAllAsRead,
    removeNotificationHandler,
  } = useNotifications();

  const [unreadOnly, setUnreadOnly] = useState(false);
  const unreadCount = displayNotifications.filter(item => !item.read).length;
  const visible = displayNotifications.filter(item => !unreadOnly || !item.read);
  const groups = new Map<string, typeof visible>();
  for (const item of [...visible].sort((a, b) => (Date.parse(b.createdAt || "") || 0) - (Date.parse(a.createdAt || "") || 0))) {
    const date = new Date(item.createdAt || "");
    const month = Number.isFinite(date.getTime())
      ? new Intl.DateTimeFormat(selectedLanguage === "ar" ? "ar-KW-u-nu-latn" : "en-GB", { month: "long", year: "numeric", timeZone: "Asia/Kuwait" }).format(date)
      : t("COMMON.NOTIFICATIONS");
    groups.set(month, [...(groups.get(month) || []), item]);
  }

  if (isLoading) {
    return <Loader />;
  }
  if (isError) {
    return <CommunityLoadError error={error} fallbackKey="COMMON.NOTIFICATIONS_LOAD_FAILED" onRetry={() => void refetch()} />;
  }

  return (
    <div className="w-full min-h-screen bg-[#F8F7FC]" dir={selectedLanguage === "ar" ? "rtl" : "ltr"}>
      <Modal
        open={open}
        onClose={() => {
          setOpen(false);
          setSelectedNotification(null);
        }}
        title={t("COMMON.NOTIFICATION_DETAIL")}
        size="md"
      >
        {selectedNotification && (
          <div dir={selectedLanguage === "ar" ? "rtl" : "ltr"}>
            <h2 className="text-primary-5 text-lg font-bold pb-1">
              {selectedLanguage === "ar"
                ? selectedNotification.title_ar
                : selectedNotification.title_en}
            </h2>
            <p className="text-sm text-[#717171] pb-4">
              {selectedNotification.date}
            </p>
            <NotificationMessage
              message={
                selectedLanguage === "ar"
                  ? selectedNotification.message_ar
                  : selectedNotification.message_en
              }
            />
            {selectedNotification.target && (
              <div className="flex justify-center pt-6">
                <Button
                  variant="primary"
                  size="medium"
                  type="button"
                  disabled={isOpeningTarget}
                  onClick={() => openTarget(selectedNotification)}
                >
                  {t("COMMON.VIEW")}
                </Button>
              </div>
            )}
          </div>
        )}
      </Modal>

      <div className="2xl:px-5 px-3 mobilescreen:px-[13px] 2xl:w-[75%] laptopmain:w-[83%] laptop:w-[78%] laptopitm:w-[85%] lg:w-[90%] md:w-[85%] w-[90%] 2xl:py-[40px] laptopmain:py-[50px] py-[40px] mx-auto">
        <h1 className="sr-only">{t("COMMON.NOTIFICATIONS")}</h1>
        <div className="mb-7 flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-1 rounded-2xl bg-[#EEEDF5] p-1" role="group" aria-label={t("COMMON.NOTIFICATIONS")}>
            {[false, true].map(unread => <button key={String(unread)} type="button" aria-pressed={unreadOnly === unread} onClick={() => setUnreadOnly(unread)} className={`rounded-xl px-4 py-2.5 text-sm text-primary-5 ${unreadOnly === unread ? "bg-white shadow-sm" : "hover:bg-white/50"}`}>
              {unread ? `${t("COMMON.NOTIFICATIONS_UNREAD")} (${unreadCount})` : t("COMMON.ALL")}
            </button>)}
          </div>
          <button type="button" onClick={markAllAsRead} disabled={markReadMutation.isPending || unreadCount === 0} className="flex items-center gap-2 rounded-xl border border-[#DFDDEE] bg-white px-4 py-2.5 text-xs text-primary-5 hover:bg-[#F0EDFF] disabled:opacity-50">
            <Check size={15} />{t("COMMON.MARK_ALL_AS_READ")}
          </button>
        </div>
        {visible.length === 0 ? <div className="rounded-2xl border border-[#E4E1EF] bg-white p-10 text-center text-secondary-102">{t("COMMON.NO_NOTIFICATIONS")}</div> : [...groups].map(([month, items]) => (
          <section key={month} className="mb-7">
            <div className="mb-4 flex items-center gap-3"><h2 className="shrink-0 text-xs font-semibold text-[#716C88]">{month}</h2><div className="h-px flex-1 bg-[#E4E1EF]" /></div>
            <div className="space-y-2">
              {items.map(notification => (
                <article key={notification.id} className={`notification-card grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-start gap-2 rounded-2xl border px-3 py-4 sm:items-center sm:gap-3 sm:px-4 ${notification.read ? "border-[#E4E1EF] bg-white" : "border-[#DDD5FF] bg-[#F2EEFF]"}`}>
                  <button type="button" onClick={() => openNotificationModal(notification)} className="flex w-full min-w-0 items-start gap-2 !whitespace-normal text-start sm:items-center sm:gap-3">
                    <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[#ECE9FA] text-primary-5">{notification.type === "reminder" ? <Clock size={19} /> : <Bell size={19} />}</span>
                    <span className="min-w-0 flex-1 whitespace-normal"><span className="block whitespace-normal break-words [overflow-wrap:anywhere] text-sm font-semibold text-[#292346]">{selectedLanguage === "ar" ? notification.title_ar : notification.title_en}</span><span className="mt-1.5 block whitespace-normal text-xs text-[#827C94]">{notification.date}</span></span>
                  </button>
                  <div className="flex shrink-0 flex-col items-center gap-2 sm:flex-row">
                  {!notification.read && <span className="shrink-0 rounded-full bg-[#E5DDFB] px-2 py-1 text-[10px] text-[#7160AF]">{t("COMMON.NOTIFICATION_NEW")}</span>}
                  <details className="relative shrink-0">
                    <summary className="flex h-8 w-8 cursor-pointer list-none items-center justify-center rounded-full text-primary-5 hover:bg-[#E6E1F3] [&::-webkit-details-marker]:hidden" aria-label={t("COMMON.NOTIFICATION_ACTIONS")}><MoreHorizontal size={20} /></summary>
                    <div className="absolute end-0 top-10 z-20 w-52 rounded-xl border border-[#E4E1EF] bg-white p-1 shadow-lg">
                      <button type="button" disabled={markReadMutation.isPending} onClick={() => markAsRead(notification.id, notification.read)} className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-start text-xs text-primary-5 hover:bg-[#F2EEFF] disabled:opacity-50"><Eye size={16} />{t("COMMON.NOTIFICATION_TOGGLE_READ")}</button>
                      <button type="button" disabled={deleteMutation.isPending} onClick={() => removeNotificationHandler(notification.id)} className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-start text-xs text-red-600 hover:bg-red-50 disabled:opacity-50"><Trash2 size={16} />{t("COMMON.NOTIFICATION_DELETE")}</button>
                    </div>
                  </details>
                  </div>
                </article>
              ))}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}
