'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { Bell, X, Check, CheckCheck, AlertTriangle, ShoppingBag, XCircle, RotateCcw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { notificationApi } from '@/lib/api';
import type { AppNotification } from '@/types';

const POLL_INTERVAL = 30000; // 30 seconds

const typeIcons: Record<string, typeof Bell> = {
  low_stock: AlertTriangle,
  new_order: ShoppingBag,
  order_void: XCircle,
  order_refund: RotateCcw,
};

const colorMap: Record<string, string> = {
  info: 'text-blue-500 bg-blue-50',
  success: 'text-emerald-600 bg-emerald-50',
  warning: 'text-amber-600 bg-amber-50',
  danger: 'text-red-500 bg-red-50',
};

function timeAgo(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const diffMs = now.getTime() - date.getTime();
  const diffMin = Math.floor(diffMs / 60000);

  if (diffMin < 1) return 'Baru saja';
  if (diffMin < 60) return `${diffMin} menit lalu`;
  const diffHour = Math.floor(diffMin / 60);
  if (diffHour < 24) return `${diffHour} jam lalu`;
  const diffDay = Math.floor(diffHour / 24);
  if (diffDay < 7) return `${diffDay} hari lalu`;
  return date.toLocaleDateString('id-ID', { day: 'numeric', month: 'short' });
}

export default function NotificationBell() {
  const [notifications, setNotifications] = useState<AppNotification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);

  const fetchNotifications = useCallback(async () => {
    try {
      const data = await notificationApi.getAll();
      setNotifications(data.notifications);
      setUnreadCount(data.unread_count);
    } catch {
      // Silently fail — notification is non-critical
    }
  }, []);

  // Initial fetch + polling
  useEffect(() => {
    // Stagger initial fetch by 1500ms to clear the critical path for the page loading
    const initialTimeout = setTimeout(fetchNotifications, 1500);

    const interval = setInterval(fetchNotifications, POLL_INTERVAL);
    return () => {
      clearTimeout(initialTimeout);
      clearInterval(interval);
    };
  }, [fetchNotifications]);

  // Close panel on outside click
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    }
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen]);

  const handleMarkAsRead = async (id: number) => {
    try {
      await notificationApi.markAsRead(id);
      setNotifications((prev) =>
        prev.map((n) => (n.id === id ? { ...n, is_read: true } : n))
      );
      setUnreadCount((prev) => Math.max(0, prev - 1));
    } catch {
      // ignore
    }
  };

  const handleMarkAllAsRead = async () => {
    setLoading(true);
    try {
      await notificationApi.markAllAsRead();
      setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
      setUnreadCount(0);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative" ref={panelRef}>
      {/* Bell Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative flex h-9 w-9 items-center justify-center rounded-xl bg-white border border-brand-100 text-brand-500 hover:bg-brand-50 hover:text-brand-700 transition-colors cursor-pointer"
        aria-label="Notifikasi"
        title="Notifikasi"
      >
        <Bell className="h-[18px] w-[18px]" />
        {unreadCount > 0 && (
          <span className="absolute -top-1 -right-1 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white leading-none">
            {unreadCount > 99 ? '99+' : unreadCount}
          </span>
        )}
      </button>

      {/* Notification Panel */}
      {isOpen && (
        <div
          className="absolute right-0 top-full mt-2 w-80 sm:w-96 rounded-2xl bg-white border border-brand-100 overflow-hidden z-50"
          style={{ boxShadow: '0 8px 30px rgba(69,26,3,0.12)' }}
        >
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b border-brand-50">
            <h3 className="text-sm font-bold text-brand-800">Notifikasi</h3>
            <div className="flex items-center gap-2">
              {unreadCount > 0 && (
                <button
                  onClick={handleMarkAllAsRead}
                  disabled={loading}
                  className="flex items-center gap-1 text-[11px] text-brand-400 hover:text-brand-600 transition-colors cursor-pointer disabled:opacity-50"
                >
                  <CheckCheck className="h-3.5 w-3.5" />
                  <span>Tandai semua</span>
                </button>
              )}
              <button
                onClick={() => setIsOpen(false)}
                className="flex h-6 w-6 items-center justify-center rounded-lg text-brand-300 hover:bg-brand-50 hover:text-brand-500 transition-colors cursor-pointer"
              >
                <X className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>

          {/* Notification List */}
          <div className="max-h-80 overflow-y-auto">
            {notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-10 text-brand-300">
                <Bell className="h-8 w-8 mb-2 opacity-40" />
                <p className="text-xs">Belum ada notifikasi</p>
              </div>
            ) : (
              notifications.map((notif) => {
                const IconComponent = typeIcons[notif.type] || Bell;
                const colorClass = colorMap[notif.color] || colorMap.info;

                return (
                  <div
                    key={notif.id}
                    className={cn(
                      'flex gap-3 px-4 py-3 border-b border-brand-50/50 transition-colors',
                      !notif.is_read ? 'bg-amber-50/30' : 'bg-white'
                    )}
                  >
                    {/* Icon */}
                    <div className={cn('flex h-8 w-8 shrink-0 items-center justify-center rounded-lg', colorClass)}>
                      <IconComponent className="h-4 w-4" />
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <p className={cn('text-xs leading-snug', !notif.is_read ? 'font-semibold text-brand-800' : 'text-brand-600')}>
                          {notif.title}
                        </p>
                        {!notif.is_read && (
                          <button
                            onClick={() => handleMarkAsRead(notif.id)}
                            className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-brand-300 hover:bg-brand-100 hover:text-brand-500 transition-colors cursor-pointer"
                            title="Tandai dibaca"
                          >
                            <Check className="h-3 w-3" />
                          </button>
                        )}
                      </div>
                      <p className="text-[11px] text-brand-400 mt-0.5 line-clamp-2">{notif.message}</p>
                      <p className="text-[10px] text-brand-300 mt-1">{timeAgo(notif.created_at)}</p>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>
      )}
    </div>
  );
}
