import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Bell, CheckCircle2, Info, XCircle } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import api from '../services/api';
import { getPwaNotificationMessage, getPwaNotificationTarget, getPwaNotificationTitle } from './pwaNotificationUtils';

const PwaNotificationContext = createContext(null);

const toneIcons = {
  success: CheckCircle2,
  error: XCircle,
  info: Info,
};

export function PwaNotificationProvider({ children }) {
  const navigate = useNavigate();
  const [notification, setNotification] = useState(null);
  const [unreadCount, setUnreadCount] = useState(0);
  const knownNotificationIds = useRef(new Set());
  const initialized = useRef(false);
  const timerRef = useRef(null);

  const dismiss = useCallback(() => {
    setNotification(null);
    window.clearTimeout(timerRef.current);
  }, []);

  const showNotification = useCallback((payload) => {
    window.clearTimeout(timerRef.current);
    setNotification({
      id: payload.id || `local-${Date.now()}`,
      tone: payload.tone || 'info',
      title: payload.title || 'اعلان جدید',
      message: payload.message || 'رویداد تازه‌ای ثبت شد.',
      actionLabel: payload.actionLabel,
      target: payload.target,
      raw: payload.raw,
    });
    timerRef.current = window.setTimeout(() => setNotification(null), payload.duration || 5200);
  }, []);

  const showApiNotification = useCallback((item) => {
    showNotification({
      id: item.id,
      tone: 'info',
      title: getPwaNotificationTitle(item),
      message: getPwaNotificationMessage(item),
      target: getPwaNotificationTarget(item),
      raw: item,
    });
  }, [showNotification]);

  const refreshUnreadCount = useCallback(async () => {
    try {
      const { data } = await api.get('/pwa/notifications', { params: { per_page: 1 } });
      setUnreadCount(data.meta?.unread_count || 0);
      return data.meta?.unread_count || 0;
    } catch {
      return unreadCount;
    }
  }, [unreadCount]);

  const handleOpen = useCallback(() => {
    const target = notification?.target || getPwaNotificationTarget(notification?.raw);

    if (target?.available && target.path) {
      dismiss();
      navigate(target.path);
      return;
    }

    if (notification?.raw || notification?.target) {
      showNotification({
        tone: 'error',
        title: 'اعلان',
        message: 'مورد مربوط به این اعلان در دسترس نیست.',
        duration: 3200,
      });
    }
  }, [dismiss, navigate, notification, showNotification]);

  useEffect(() => {
    const fetchLatestNotifications = async () => {
      try {
        const { data } = await api.get('/pwa/notifications', { params: { per_page: 5 } });
        const items = data.data || [];
        setUnreadCount(data.meta?.unread_count || 0);

        if (!initialized.current) {
          items.forEach((item) => knownNotificationIds.current.add(item.id));
          initialized.current = true;
          return;
        }

        const newest = items.find((item) => !knownNotificationIds.current.has(item.id));
        items.forEach((item) => knownNotificationIds.current.add(item.id));

        if (newest) showApiNotification(newest);
      } catch {
        initialized.current = true;
      }
    };

    fetchLatestNotifications();
    const interval = window.setInterval(fetchLatestNotifications, 60000);
    return () => {
      window.clearInterval(interval);
      window.clearTimeout(timerRef.current);
    };
  }, [showApiNotification]);

  const value = useMemo(() => ({
    notify: showNotification,
    dismissNotification: dismiss,
    unreadCount,
    setUnreadCount,
    refreshUnreadCount,
  }), [dismiss, refreshUnreadCount, showNotification, unreadCount]);

  const Icon = toneIcons[notification?.tone] || Bell;

  return (
    <PwaNotificationContext.Provider value={value}>
      {children}
      {notification && (
        <div className={`pwa-in-app-notification ${notification.tone}`} role="status" dir="rtl">
          <button type="button" className="pwa-notification-body" onClick={handleOpen}>
            <span className="pwa-notification-symbol"><Icon size={18} /></span>
            <span className="pwa-notification-copy">
              <small>مدیریت پروژه</small>
              <strong>{notification.title}</strong>
              <span>{notification.message}</span>
              <em>همین الان</em>
            </span>
            {notification.actionLabel && <span className="pwa-notification-action">{notification.actionLabel}</span>}
          </button>
        </div>
      )}
    </PwaNotificationContext.Provider>
  );
}

export function usePwaNotification() {
  const context = useContext(PwaNotificationContext);
  if (!context) {
    return {
      notify: () => {},
      dismissNotification: () => {},
    };
  }

  return context;
}
