"use client";

import { useCallback, useEffect } from "react";
import Image from "next/image";
import { Heart, MessageCircle, UserPlus, Bell, BellOff, Zap } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchNotifications,
  markAsRead,
  markAllReadLocally,
} from "@/store/slices/notificationSlice";
import type { NotificationItem } from "@/services/notificationService";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import { useTranslation } from "@/i18n";

/* ── Notification type config ───────────────────────────────────────────────── */

const TYPE_CONFIG: Record<number, { icon: React.ElementType; color: string; bg: string; labelKey: string }> = {
  1: { icon: Zap,           color: "#f59e0b", bg: "rgba(245,158,11,0.12)",  labelKey: "notif_alert"     },
  2: { icon: Heart,         color: "#f43f5e", bg: "rgba(244,63,94,0.12)",   labelKey: "notif_like"      },
  3: { icon: MessageCircle, color: "var(--accent)", bg: "rgba(var(--accent-rgb),0.12)",  labelKey: "notif_comment"   },
  4: { icon: UserPlus,      color: "#22d3ee", bg: "rgba(34,211,238,0.12)",  labelKey: "notif_subscribe" },
};

function getTypeConfig(type: number) {
  return TYPE_CONFIG[type] ?? TYPE_CONFIG[1];
}

/* ── Avatar with type badge ─────────────────────────────────────────────────── */

function NotifAvatar({ item }: { item: NotificationItem }) {
  const cfg = getTypeConfig(item.type);
  const Icon = cfg.icon;
  const initial = (item.userName || "U")[0].toUpperCase();

  return (
    <div className="relative flex-shrink-0" style={{ width: 44, height: 44 }}>
      <div
        className="w-full h-full rounded-full overflow-hidden flex items-center justify-center font-bold text-sm"
        style={{ background: "var(--deep)", color: cfg.color, border: `1.5px solid ${cfg.color}30` }}
      >
        {item.userImage && !item.userImage.includes("default.png") && !item.userImage.includes("no_img") ? (
          <Image src={item.userImage} alt={item.userName} fill className="object-cover rounded-full" unoptimized sizes="44px" />
        ) : (
          <span style={{ fontSize: 16 }}>{initial}</span>
        )}
      </div>
      {/* Type badge */}
      <div
        className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full flex items-center justify-center border-2"
        style={{ background: cfg.color, borderColor: "var(--bg)" }}
      >
        <Icon size={9} color="#fff" strokeWidth={2.5} fill={item.type === 2 ? "#fff" : "none"} />
      </div>
    </div>
  );
}

/* ── Single notification row ────────────────────────────────────────────────── */

function NotifRow({ item, index }: { item: NotificationItem; index: number }) {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const cfg = getTypeConfig(item.type);
  const hasContent = !!item.contentImage && !item.contentImage.includes("no_img");

  const handleClick = () => {
    if (!item.isRead) dispatch(markAsRead(item.id));
  };

  return (
    <div
      className="group relative flex items-start gap-3 px-4 py-3.5 cursor-pointer transition-all duration-200"
      style={{
        background: item.isRead ? "transparent" : "var(--border-soft)",
        borderLeft: `2.5px solid ${item.isRead ? "transparent" : cfg.color}`,
        animation: `notif-row-in 0.4s ease both`,
        animationDelay: `${Math.min(index * 45, 400)}ms`,
      }}
      onClick={handleClick}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLDivElement).style.background = "var(--btn-ghost-hover)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLDivElement).style.background = item.isRead ? "transparent" : "var(--border-soft)";
      }}
    >
      {/* Unread dot */}
      {!item.isRead && (
        <div
          className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full"
          style={{ background: cfg.color, left: -1 }}
        />
      )}

      <NotifAvatar item={item} />

      {/* Text */}
      <div className="flex-1 min-w-0">
        <p
          className="text-[12.5px] leading-snug"
          style={{ color: item.isRead ? "var(--text-muted)" : "var(--text-primary)", fontWeight: item.isRead ? 400 : 500 }}
        >
          {item.title}
        </p>
        {item.contentName && (
          <p
            className="text-[11px] mt-0.5 truncate"
            style={{ color: "var(--text-muted)" }}
          >
            {item.contentName}
          </p>
        )}
        <div className="flex items-center gap-1.5 mt-1.5">
          <span
            className="text-[10px] font-medium px-1.5 py-0.5 rounded"
            style={{ background: cfg.bg, color: cfg.color }}
          >
            {t(cfg.labelKey)}
          </span>
          <span className="text-[10px]" style={{ color: "var(--text-muted)" }}>
            {item.createdAt}
          </span>
        </div>
      </div>

      {/* Content thumbnail */}
      {hasContent && (
        <div
          className="flex-shrink-0 rounded-lg overflow-hidden relative"
          style={{ width: 52, height: 40, background: "var(--deep)" }}
        >
          <Image
            src={item.contentImage}
            alt={item.contentName}
            fill
            className="object-cover"
            unoptimized
            sizes="52px"
          />
        </div>
      )}
    </div>
  );
}

/* ── Skeleton ────────────────────────────────────────────────────────────────── */

function NotifSkeleton() {
  return (
    <div className="flex items-start gap-3 px-4 py-3.5 animate-pulse">
      <div className="w-11 h-11 rounded-full flex-shrink-0" style={{ background: "var(--card)" }} />
      <div className="flex-1 space-y-2 pt-0.5">
        <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "78%" }} />
        <div className="h-2 rounded-full" style={{ background: "var(--card)", width: "52%" }} />
        <div className="h-2 rounded-full" style={{ background: "var(--card)", width: "30%" }} />
      </div>
      <div className="w-12 h-10 rounded-lg flex-shrink-0" style={{ background: "var(--card)" }} />
    </div>
  );
}

/* ── Empty state ─────────────────────────────────────────────────────────────── */

function EmptyState() {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center justify-center py-24 text-center px-6">
      <div
        className="w-18 h-18 rounded-2xl flex items-center justify-center mb-5"
        style={{
          width: 72, height: 72,
          background: "var(--btn-ghost)",
          border: "1px solid var(--border)",
        }}
      >
        <BellOff size={28} strokeWidth={1.4} style={{ color: "var(--text-muted)" }} />
      </div>
      <p className="text-sm font-semibold mb-1" style={{ color: "var(--text-primary)" }}>{t("notif_allCaughtUp")}</p>
      <p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("notif_noNew")}</p>
    </div>
  );
}

/* ── Main page ───────────────────────────────────────────────────────────────── */

export default function NotificationPage() {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { items, isLoading, isLoadingMore, hasMore, currentPage, unreadCount } =
    useAppSelector((s) => s.notifications);



  useEffect(() => {
    dispatch(fetchNotifications(1));
  }, [dispatch]);

  const handleLoadMore = useCallback(() => {
    dispatch(fetchNotifications(currentPage + 1));
  }, [dispatch, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: isLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  return (
    <div className="min-h-screen" style={{ background: "var(--bg)" }}>

      {/* ── Header bar ── */}
      <div
        className="sticky top-0 z-10 flex items-center justify-between px-5 py-4"
        style={{
          background: "var(--bg)",
          borderBottom: "1px solid var(--border)",
          animation: "notif-head-in 0.35s ease both",
        }}
      >
        <div className="flex items-center gap-3">
          <div
            className="w-8 h-8 rounded-xl flex items-center justify-center"
            style={{ background: "rgba(var(--accent-rgb),0.1)", border: "1px solid rgba(var(--accent-rgb),0.2)" }}
          >
            <Bell size={15} color="var(--accent)" strokeWidth={2} />
          </div>
          <div>
            <h1 className="text-sm font-bold leading-none" style={{ color: "var(--text-primary)" }}>{t("notif_title")}</h1>
            {unreadCount > 0 && (
              <p className="text-[10px] mt-0.5" style={{ color: "var(--accent)" }}>
                {unreadCount} {t("notif_unread")}
              </p>
            )}
          </div>
        </div>

        {unreadCount > 0 && (
          <button
            className="text-[11px] font-semibold px-3 py-1.5 rounded-lg transition-all active:scale-95"
            style={{ background: "var(--btn-ghost)", color: "var(--text-muted)", border: "1px solid var(--border)" }}
            onClick={() => dispatch(markAllReadLocally())}
          >
            {t("notif_markAllRead")}
          </button>
        )}
      </div>

      {/* ── Type filter pills (visual grouping) ── */}
      {!isLoading && items.length > 0 && (
        <div
          className="flex items-center gap-2 px-4 py-3 overflow-x-auto scrollbar-hide"
          style={{ animation: "notif-head-in 0.4s ease both", animationDelay: "0.05s" }}
        >
          {Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
            const count = items.filter((n) => n.type === Number(type)).length;
            if (count === 0) return null;
            const Icon = cfg.icon;
            return (
              <div
                key={type}
                className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-full flex-shrink-0 text-[10px] font-semibold"
                style={{ background: cfg.bg, color: cfg.color, border: `1px solid ${cfg.color}25` }}
              >
                <Icon size={10} strokeWidth={2.5} fill={Number(type) === 2 ? cfg.color : "none"} />
                {t(cfg.labelKey)}
                <span
                  className="ml-0.5 px-1 rounded-full text-[9px] font-bold"
                  style={{ background: `${cfg.color}30`, color: cfg.color }}
                >
                  {count}
                </span>
              </div>
            );
          })}
        </div>
      )}

      {/* ── Divider ── */}
      {!isLoading && items.length > 0 && (
        <div style={{ height: 1, background: "var(--border-soft)" }} />
      )}

      {/* ── Content ── */}
      {isLoading ? (
        <div className="divide-y" style={{ borderColor: "var(--border-soft)" }}>
          {Array.from({ length: 8 }).map((_, i) => <NotifSkeleton key={i} />)}
        </div>
      ) : items.length === 0 ? (
        <EmptyState />
      ) : (
        <div>
          {items.map((item, i) => (
            <div key={item.id}>
              <NotifRow item={item} index={i} />
              {i < items.length - 1 && (
                <div style={{ height: 1, background: "var(--border-soft)", marginLeft: 64 }} />
              )}
            </div>
          ))}

          {/* Infinite scroll sentinel */}
          <div ref={sentinelRef} className="h-1" />

          {isLoadingMore && (
            <div className="flex justify-center py-6">
              <div className="flex gap-1.5">
                {[0, 1, 2].map((i) => (
                  <div
                    key={i}
                    className="w-1.5 h-1.5 rounded-full animate-pulse"
                    style={{ background: "var(--accent)", animationDelay: `${i * 150}ms` }}
                  />
                ))}
              </div>
            </div>
          )}

          {!hasMore && items.length > 0 && (
            <p className="text-center text-[10px] py-6" style={{ color: "var(--text-muted)" }}>
              {t("notif_seenAll")}
            </p>
          )}
        </div>
      )}
    </div>
  );
}
