"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import {
  Bell, BellRing, X, Car,
  TrendingDown, Plus, Sparkles, AlertTriangle, Shield,
  Check, ExternalLink, Trash2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useNotificationStore } from "@/store/useNotificationStore";
import {
  fetchNotifications, fetchUnreadCount,
  markAllNotificationsRead, deleteNotification,
} from "@/lib/api";
import type { UserNotification, NotificationType } from "@/lib/types";

// ── Type config ────────────────────────────────────────────────────────────────

const TYPE_CONFIG: Record<NotificationType, {
  label:  string;
  icon:   React.ElementType;
  dot:    string;
  badge:  string;
  border: string;
}> = {
  price_drop:    { label: "Price Drop",       icon: TrendingDown,   dot: "bg-emerald-500", badge: "bg-emerald-50 text-emerald-700 border-emerald-200",   border: "border-l-emerald-400"  },
  new_variant:   { label: "New Variant",      icon: Plus,           dot: "bg-blue-500",    badge: "bg-blue-50 text-blue-700 border-blue-200",            border: "border-l-blue-400"     },
  facelift:      { label: "Facelift",         icon: Sparkles,       dot: "bg-violet-500",  badge: "bg-violet-50 text-violet-700 border-violet-200",      border: "border-l-violet-400"   },
  recall:        { label: "Recall",           icon: AlertTriangle,  dot: "bg-red-500",     badge: "bg-red-50 text-red-700 border-red-200",               border: "border-l-red-400"      },
  safety_update: { label: "Safety Update",    icon: Shield,         dot: "bg-amber-500",   badge: "bg-amber-50 text-amber-700 border-amber-200",         border: "border-l-amber-400"    },
};

// ── Time ago helper ────────────────────────────────────────────────────────────

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60_000);
  if (m < 1)  return "just now";
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

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

function NotifRow({
  notif,
  onDelete,
}: {
  notif:    UserNotification;
  onDelete: (id: string) => void;
}) {
  const cfg = TYPE_CONFIG[notif.type] ?? TYPE_CONFIG.safety_update;
  const Icon = cfg.icon;

  return (
    <div
      className={cn(
        "flex gap-3 px-4 py-3 hover:bg-gray-50 transition-colors border-l-4",
        cfg.border,
        !notif.read && "bg-blue-50/30"
      )}
    >
      {/* Car image or icon */}
      <div className="shrink-0 mt-0.5">
        {notif.imageUrl ? (
          <div className="w-10 h-8 rounded-lg overflow-hidden bg-gray-100">
            <Image
              src={notif.imageUrl} alt={notif.carName}
              width={40} height={32}
              className="w-full h-full object-cover"
              unoptimized
            />
          </div>
        ) : (
          <div className="w-10 h-8 rounded-lg bg-gray-100 flex items-center justify-center">
            <Car className="w-4 h-4 text-gray-400" />
          </div>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            {/* Type badge */}
            <span className={cn(
              "inline-flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded-md border mb-1",
              cfg.badge
            )}>
              <Icon className="w-2.5 h-2.5" />
              {cfg.label}
            </span>
            {/* Title */}
            <p className="text-xs font-semibold text-gray-800 leading-snug truncate">
              {notif.brand} {notif.carName}
            </p>
            {/* Message */}
            <p className="text-[11px] text-gray-500 leading-snug mt-0.5 line-clamp-2">
              {notif.message}
            </p>
          </div>

          {/* Actions */}
          <div className="flex flex-col items-end gap-1 shrink-0">
            {!notif.read && (
              <span className={cn("w-2 h-2 rounded-full", cfg.dot)} />
            )}
            <button
              onClick={(e) => { e.stopPropagation(); onDelete(notif.id); }}
              className="p-0.5 rounded hover:bg-gray-200 text-gray-300 hover:text-gray-500 transition-colors"
              title="Dismiss"
            >
              <X className="w-3 h-3" />
            </button>
          </div>
        </div>

        {/* Footer row */}
        <div className="flex items-center gap-3 mt-1.5">
          <span className="text-[10px] text-gray-400">{timeAgo(notif.createdAt)}</span>
          <Link
            href={`/cars/${notif.carSlug}`}
            className="text-[10px] font-semibold text-blue-500 hover:underline flex items-center gap-0.5"
          >
            View car <ExternalLink className="w-2.5 h-2.5" />
          </Link>
        </div>
      </div>
    </div>
  );
}

// ── Bell + dropdown ────────────────────────────────────────────────────────────

export default function NotificationBell() {
  const { sessionId, unreadCount, setUnreadCount } = useNotificationStore();
  const [open,          setOpen]          = useState(false);
  const [notifications, setNotifications] = useState<UserNotification[]>([]);
  const [loading,       setLoading]       = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Poll unread count every 60 seconds
  const pollCount = useCallback(async () => {
    if (!sessionId) return;
    const n = await fetchUnreadCount(sessionId);
    setUnreadCount(n);
  }, [sessionId, setUnreadCount]);

  useEffect(() => {
    pollCount();
    const id = setInterval(pollCount, 60_000);
    return () => clearInterval(id);
  }, [pollCount]);

  // Close on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    if (open) document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  async function handleOpen() {
    if (open) { setOpen(false); return; }
    setOpen(true);
    setLoading(true);
    const [notifs] = await Promise.all([
      fetchNotifications(sessionId, 15),
      unreadCount > 0 ? markAllNotificationsRead(sessionId) : Promise.resolve(),
    ]);
    setNotifications(notifs);
    setLoading(false);
    if (unreadCount > 0) setUnreadCount(0);
  }

  async function handleDelete(id: string) {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
    await deleteNotification(sessionId, id);
  }

  const hasRecall = notifications.some((n) => n.type === "recall");

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Bell button */}
      <motion.button
        whileHover={{ scale: 1.05 }}
        whileTap={{ scale: 0.96 }}
        onClick={handleOpen}
        aria-label="Notifications"
        className={cn(
          "relative flex items-center gap-2 p-2 sm:px-4 sm:py-2.5 rounded-2xl border bg-white/70 backdrop-blur-md transition-all duration-300",
          hasRecall
            ? "border-red-300 shadow-red-100/50 shadow-lg"
            : "border-gray-200/70 hover:border-blue-200 hover:shadow-lg hover:shadow-blue-100/50"
        )}
      >
        <AnimatePresence mode="wait">
          {unreadCount > 0 ? (
            <motion.div
              key="ringing"
              initial={{ rotate: -15 }}
              animate={{ rotate: [0, 15, -15, 10, -10, 0] }}
              transition={{ duration: 0.5, repeat: Infinity, repeatDelay: 4 }}
            >
              <BellRing className={cn(
                "w-4 h-4",
                hasRecall ? "text-red-500" : "text-blue-600"
              )} />
            </motion.div>
          ) : (
            <motion.div key="silent">
              <Bell className="w-4 h-4 text-gray-700" />
            </motion.div>
          )}
        </AnimatePresence>

        <span className="hidden lg:inline text-sm font-semibold text-gray-700">Alerts</span>

        <AnimatePresence>
          {unreadCount > 0 && (
            <motion.span
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0 }}
              transition={{ type: "spring", stiffness: 500 }}
              className={cn(
                "absolute -top-1 -right-1 min-w-[20px] h-5 px-1 text-white text-[10px] font-bold rounded-full flex items-center justify-center shadow-md",
                hasRecall ? "bg-red-500" : "bg-gradient-to-r from-blue-500 to-indigo-500"
              )}
            >
              {unreadCount > 99 ? "99+" : unreadCount}
            </motion.span>
          )}
        </AnimatePresence>
      </motion.button>

      {/* Dropdown panel */}
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: 6, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 6, scale: 0.97 }}
            transition={{ duration: 0.15 }}
            className="absolute right-0 top-full mt-2 w-[min(340px,calc(100vw-2rem))] bg-white border border-gray-200 rounded-2xl shadow-2xl shadow-black/10 z-[999] overflow-hidden"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100 bg-gray-50/60">
              <div className="flex items-center gap-2">
                <Bell className="w-4 h-4 text-gray-600" />
                <h3 className="font-bold text-gray-900 text-sm">Notifications</h3>
              </div>
              <button
                onClick={() => setOpen(false)}
                className="p-1.5 rounded-lg hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            </div>

            {/* Notification list */}
            <div className="max-h-[340px] overflow-y-auto divide-y divide-gray-100">
              {loading ? (
                <div className="flex flex-col items-center justify-center py-10 gap-2">
                  <div className="w-6 h-6 border-2 border-gray-200 border-t-blue-500 rounded-full animate-spin" />
                  <p className="text-xs text-gray-400">Loading…</p>
                </div>
              ) : notifications.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-10 gap-3 text-gray-400 px-6 text-center">
                  <Bell className="w-9 h-9" />
                  <div>
                    <p className="text-sm font-semibold text-gray-600">No notifications yet</p>
                    <p className="text-xs mt-1 leading-relaxed">
                      Watch a car to get alerts for price drops, new variants, facelifts, recalls, and safety updates.
                    </p>
                  </div>
                  <Link
                    href="/cars"
                    className="text-xs font-bold text-blue-600 hover:underline"
                    onClick={() => setOpen(false)}
                  >
                    Browse cars →
                  </Link>
                </div>
              ) : (
                <AnimatePresence initial={false}>
                  {notifications.map((n) => (
                    <motion.div
                      key={n.id}
                      layout
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: "auto" }}
                      exit={{ opacity: 0, height: 0 }}
                      transition={{ duration: 0.15 }}
                    >
                      <NotifRow notif={n} onDelete={handleDelete} />
                    </motion.div>
                  ))}
                </AnimatePresence>
              )}
            </div>

            {/* Footer */}
            <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100 bg-gray-50/40">
              <Link
                href="/notifications"
                className="flex items-center gap-1 text-xs font-bold text-blue-600 hover:underline"
                onClick={() => setOpen(false)}
              >
                View all alerts →
              </Link>
              <Link
                href="/notifications?tab=watchlist"
                className="text-xs text-gray-400 hover:text-gray-700 font-medium transition-colors"
                onClick={() => setOpen(false)}
              >
                Manage watchlist
              </Link>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
