import { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { AnimatePresence, motion } from 'framer-motion';
import { Bell, MessageSquare, Star, Info, CheckCheck } from 'lucide-react';
import { notifications } from '../api/client';

interface Notification {
  id: string;
  type: 'new_message' | 'stars_purchase' | 'system';
  title: string;
  body: string;
  characterId?: string;
  telegramUserId?: number;
  read: boolean;
  link?: string;
  createdAt: string;
}

const ICON_MAP: Record<Notification['type'], { icon: typeof MessageSquare; color: string; bg: string }> = {
  new_message: { icon: MessageSquare, color: 'text-indigo-400', bg: 'bg-indigo-500/15' },
  stars_purchase: { icon: Star, color: 'text-amber-400', bg: 'bg-amber-500/15' },
  system: { icon: Info, color: 'text-slate-400', bg: 'bg-slate-500/15' },
};

function timeAgo(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diff = Math.max(0, now - then);
  const seconds = Math.floor(diff / 1000);
  if (seconds < 60) return 'Az önce';
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes} dk önce`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours} sa önce`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days} gün önce`;
  return new Date(dateStr).toLocaleDateString('tr-TR');
}

export default function NotificationDropdown() {
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const navigate = useNavigate();
  const ref = useRef<HTMLDivElement>(null);

  // Fetch unread count
  const fetchUnreadCount = useCallback(async () => {
    try {
      const res = await notifications.getUnreadCount();
      setUnreadCount(res.data?.unreadCount ?? 0);
    } catch {
      // Sessiz hata — sonraki polling'de tekrar dener
    }
  }, []);

  // Fetch notification list
  const fetchList = useCallback(async () => {
    try {
      const res = await notifications.list({ limit: 50 });
      const data = res.data?.notifications ?? res.data ?? [];
      setItems(Array.isArray(data) ? data : []);
    } catch {
      // Sessiz hata
    }
  }, []);

  // Poll unread count every 30 seconds
  useEffect(() => {
    fetchUnreadCount();
    const interval = setInterval(fetchUnreadCount, 30_000);
    return () => clearInterval(interval);
  }, [fetchUnreadCount]);

  // Fetch full list when dropdown opens
  useEffect(() => {
    if (open) {
      fetchList();
    }
  }, [open, fetchList]);

  // Click outside handler
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (open) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [open]);

  // Mark single notification as read + navigate
  const handleClick = async (item: Notification) => {
    if (!item.read) {
      try {
        await notifications.markAsRead(item.id);
        setItems(prev => prev.map(n => n.id === item.id ? { ...n, read: true } : n));
        setUnreadCount(prev => Math.max(0, prev - 1));
      } catch {
        // Sessiz hata
      }
    }
    if (item.link) {
      navigate(item.link);
    }
    setOpen(false);
  };

  // Mark all as read
  const handleMarkAllRead = async () => {
    try {
      await notifications.markAllAsRead();
      setItems(prev => prev.map(n => ({ ...n, read: true })));
      setUnreadCount(0);
    } catch {
      // Sessiz hata
    }
  };

  return (
    <div ref={ref} className="relative">
      {/* Bell button */}
      <button
        onClick={() => setOpen(o => !o)}
        className="relative p-2 rounded-xl text-slate-500 hover:text-slate-300 hover:bg-white/[0.04] transition-all cursor-pointer"
      >
        <Bell className="w-5 h-5" />
        {unreadCount > 0 && (
          <span className="absolute top-1 right-1 min-w-[18px] h-[18px] flex items-center justify-center rounded-full bg-indigo-500 text-[10px] font-bold text-white px-1 leading-none">
            {unreadCount > 99 ? '99+' : unreadCount}
          </span>
        )}
      </button>

      {/* Dropdown panel */}
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -8, scale: 0.96 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.96 }}
            transition={{ duration: 0.15 }}
            className="absolute right-0 top-full mt-2 w-[360px] bg-[#12121a] border border-white/[0.08] rounded-2xl shadow-2xl overflow-hidden z-50"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-white/[0.06]">
              <span className="text-sm font-semibold text-slate-200">Bildirimler</span>
              {unreadCount > 0 && (
                <button
                  onClick={handleMarkAllRead}
                  className="flex items-center gap-1.5 text-[11px] text-indigo-400 hover:text-indigo-300 transition-colors cursor-pointer"
                >
                  <CheckCheck className="w-3.5 h-3.5" />
                  Tümünü okundu işaretle
                </button>
              )}
            </div>

            {/* Notification list */}
            <div className="max-h-[400px] overflow-y-auto">
              {items.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-10 text-slate-600">
                  <Bell className="w-8 h-8 mb-2 opacity-40" />
                  <span className="text-sm">Henüz bildirim yok</span>
                </div>
              ) : (
                items.map(item => {
                  const { icon: TypeIcon, color, bg } = ICON_MAP[item.type] ?? ICON_MAP.system;
                  return (
                    <button
                      key={item.id}
                      onClick={() => handleClick(item)}
                      className={`w-full flex items-start gap-3 px-4 py-3 text-left transition-colors cursor-pointer hover:bg-white/[0.03] ${
                        !item.read ? 'bg-indigo-500/[0.04]' : ''
                      }`}
                    >
                      <div className={`flex items-center justify-center w-8 h-8 rounded-lg shrink-0 mt-0.5 ${bg}`}>
                        <TypeIcon className={`w-4 h-4 ${color}`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className={`text-[13px] font-medium truncate ${!item.read ? 'text-slate-100' : 'text-slate-400'}`}>
                            {item.title}
                          </span>
                          {!item.read && (
                            <span className="w-1.5 h-1.5 rounded-full bg-indigo-500 shrink-0" />
                          )}
                        </div>
                        <p className="text-[12px] text-slate-500 truncate mt-0.5">{item.body}</p>
                        <span className="text-[11px] text-slate-600 mt-1 block">{timeAgo(item.createdAt)}</span>
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
