'use client';

import { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
import { useAuth } from './AuthContext';
import { useSocket, SOCKET_EVENTS } from './SocketContext';
import { api } from '@/lib/api';

export interface AppNotification {
  id: string;
  type: string;
  title: string;
  message: string;
  data?: {
    conversationId?: string;
    jobId?: string;
    hireInvitationId?: string;
    workerId?: string;
    customerId?: string;
    href?: string;
    isVerified?: boolean;
    isAvailable?: boolean;
  } | null;
  isRead: boolean;
  createdAt: string;
}

interface NotificationContextType {
  unreadCount: number;
  refreshUnreadCount: () => Promise<void>;
  markAsRead: (id: string) => Promise<void>;
  markAllAsRead: () => Promise<void>;
}

const NotificationContext = createContext<NotificationContextType | undefined>(undefined);

export function NotificationProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();
  const { socket } = useSocket();
  const [unreadCount, setUnreadCount] = useState(0);

  const refreshUnreadCount = useCallback(async () => {
    if (!user) {
      setUnreadCount(0);
      return;
    }
    try {
      const res = await api<{ data: { count: number } }>('/notifications/unread-count');
      setUnreadCount(res.data.count);
    } catch {
      setUnreadCount(0);
    }
  }, [user]);

  useEffect(() => {
    refreshUnreadCount();
  }, [refreshUnreadCount]);

  // Refresh count when user returns to the tab
  useEffect(() => {
    const onFocus = () => refreshUnreadCount();
    window.addEventListener('focus', onFocus);
    return () => window.removeEventListener('focus', onFocus);
  }, [refreshUnreadCount]);

  useEffect(() => {
    if (!socket || !user) return;

    const onNotification = (payload?: { type?: string }) => {
      if (payload?.type === 'MESSAGE_RECEIVED') return;
      setUnreadCount((c) => c + 1);
    };

    socket.on(SOCKET_EVENTS.NOTIFICATION, onNotification);
    return () => {
      socket.off(SOCKET_EVENTS.NOTIFICATION, onNotification);
    };
  }, [socket, user]);

  const markAsRead = async (id: string) => {
    await api(`/notifications/${id}/read`, { method: 'PATCH' });
    setUnreadCount((c) => Math.max(0, c - 1));
  };

  const markAllAsRead = async () => {
    await api('/notifications/read-all', { method: 'PATCH' });
    setUnreadCount(0);
  };

  return (
    <NotificationContext.Provider
      value={{ unreadCount, refreshUnreadCount, markAsRead, markAllAsRead }}
    >
      {children}
    </NotificationContext.Provider>
  );
}

export function useNotifications() {
  const context = useContext(NotificationContext);
  if (!context) throw new Error('useNotifications must be used within NotificationProvider');
  return context;
}
