"use client";

import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { MoreHorizontal } from "lucide-react";
import { Shell } from "@/components/Shell";
import { NOTIFICATIONS, type NotificationType } from "@/lib/mock-notifications";
import { NotifIcon } from "@/components/notifications/NotifIcon";

type FilterTab = "all" | "unread" | "alert" | "content" | "team" | "billing";

const FILTER_TABS: { id: FilterTab; label: string }[] = [
  { id: "all", label: "Toutes" },
  { id: "unread", label: "Non lues" },
  { id: "alert", label: "Alertes" },
  { id: "content", label: "Contenus" },
  { id: "team", label: "Équipe" },
  { id: "billing", label: "Facturation" },
];

function matchesFilter(type: NotificationType, filter: FilterTab): boolean {
  if (filter === "all") return true;
  if (filter === "unread") return true;
  if (filter === "alert") return type === "alert";
  if (filter === "content") return type === "content" || type === "ranking" || type === "suggestion" || type === "report" || type === "tracking";
  if (filter === "team") return type === "team";
  if (filter === "billing") return type === "billing";
  return true;
}

export default function NotificationsPage() {
  const [notifications, setNotifications] = useState(NOTIFICATIONS);
  const [activeFilter, setActiveFilter] = useState<FilterTab>("all");

  const unreadCount = notifications.filter((n) => !n.read).length;

  const filtered = useMemo(() => {
    return notifications.filter((n) => {
      if (activeFilter === "unread") return !n.read;
      return matchesFilter(n.type, activeFilter);
    });
  }, [notifications, activeFilter]);

  function markAllRead() {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
  }

  function markRead(id: string) {
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, read: true } : n))
    );
  }

  return (
    <Shell>
      <div className="max-w-[800px] mx-auto">
        {/* Header */}
        <div className="flex items-start justify-between gap-4 mb-5">
          <div>
            <h1 className="text-[22px] font-semibold tracking-tight text-text">Notifications</h1>
            <p className="text-[13px] text-text-dim mt-1">
              <span className="text-text font-medium">{unreadCount} non lues</span>
              {" "}sur {notifications.length}
            </p>
          </div>
          {unreadCount > 0 && (
            <button
              onClick={markAllRead}
              className="px-3 py-2 rounded-lg text-[12.5px] font-medium border border-border hover:bg-bg-card-hover text-text-dim transition-colors shrink-0"
            >
              Tout marquer comme lu
            </button>
          )}
        </div>

        {/* Filtres */}
        <div className="flex items-center gap-1 overflow-x-auto pb-1 mb-5 border-b border-border">
          {FILTER_TABS.map((tab) => {
            const count =
              tab.id === "unread"
                ? unreadCount
                : tab.id === "all"
                  ? notifications.length
                  : notifications.filter((n) => matchesFilter(n.type, tab.id)).length;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveFilter(tab.id)}
                className={`relative flex items-center gap-1.5 px-3 py-2.5 text-[13px] font-medium whitespace-nowrap transition-colors ${
                  activeFilter === tab.id ? "text-text" : "text-text-dim hover:text-text"
                }`}
              >
                {tab.label}
                {count > 0 && tab.id !== "all" && (
                  <span
                    className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full min-w-[18px] text-center ${
                      tab.id === "unread"
                        ? "bg-red-500/15 text-red-400"
                        : "bg-bg text-text-dimmer"
                    }`}
                  >
                    {count}
                  </span>
                )}
                {activeFilter === tab.id && (
                  <motion.div
                    layoutId="notif-filter-underline"
                    className="absolute bottom-0 left-0 right-0 h-0.5 bg-accent rounded-full"
                  />
                )}
              </button>
            );
          })}
        </div>

        {/* Liste */}
        <motion.div layout className="space-y-1">
          <AnimatePresence mode="popLayout">
            {filtered.length === 0 ? (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="py-20 text-center text-text-dim text-[13px]"
              >
                Aucune notification dans cette catégorie.
              </motion.div>
            ) : (
              filtered.map((n) => (
                <motion.div
                  key={n.id}
                  layout
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.97 }}
                  transition={{ duration: 0.2 }}
                  onClick={() => markRead(n.id)}
                  className={`flex items-start gap-3 p-4 rounded-xl border transition-colors cursor-pointer ${
                    !n.read
                      ? "bg-accent/5 border-accent/15 hover:bg-accent/8"
                      : "bg-bg-card border-border hover:bg-bg-card-hover"
                  }`}
                >
                  <NotifIcon icon={n.icon} color={n.color} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-3">
                      <span
                        className={`text-[13.5px] leading-snug ${
                          !n.read ? "font-semibold text-text" : "font-medium text-text"
                        }`}
                      >
                        {n.title}
                      </span>
                      <div className="flex items-center gap-2 shrink-0">
                        <span className="text-[11.5px] text-text-dimmer whitespace-nowrap">{n.time}</span>
                        {!n.read && (
                          <span className="w-2 h-2 rounded-full bg-accent shrink-0" />
                        )}
                      </div>
                    </div>
                    <p className="text-[12.5px] text-text-dim mt-1 leading-snug line-clamp-2">
                      {n.body}
                    </p>
                  </div>
                  <button
                    onClick={(e) => e.stopPropagation()}
                    className="p-1.5 rounded hover:bg-bg-card-hover text-text-dimmer hover:text-text-dim transition-colors shrink-0"
                  >
                    <MoreHorizontal className="w-4 h-4" />
                  </button>
                </motion.div>
              ))
            )}
          </AnimatePresence>
        </motion.div>
      </div>
    </Shell>
  );
}
