import React, { useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";

/**
 * Automated Notification Engine
 * Monitors events and triggers notifications based on configured preferences
 */

export function NotificationEngine() {
  const queryClient = useQueryClient();

  const { data: events = [] } = useQuery({
    queryKey: ['events-notifications'],
    queryFn: () => base44.entities.Event.list(),
    refetchInterval: 60000, // Check every minute
  });

  const { data: users = [] } = useQuery({
    queryKey: ['users-notifications'],
    queryFn: () => base44.entities.User.list(),
    refetchInterval: 300000, // Check every 5 minutes
  });

  const createNotification = async (userId, title, description, activityType, relatedId = null) => {
    try {
      await base44.entities.ActivityLog.create({
        title,
        description,
        activity_type: activityType,
        user_id: userId,
        is_read: false,
        related_entity_id: relatedId,
        icon_type: activityType.includes('event') ? 'calendar' : activityType.includes('invoice') ? 'invoice' : 'user',
        icon_color: 'blue',
      });
    } catch (error) {
      console.error('Failed to create notification:', error);
    }
  };

  const sendEmail = async (to, subject, body, userPreferences) => {
    if (!userPreferences?.email_notifications) return;
    
    try {
      await base44.integrations.Core.SendEmail({
        to,
        subject,
        body,
      });
    } catch (error) {
      console.error('Failed to send email:', error);
    }
  };

  // Shift assignment notifications
  useEffect(() => {
    const notifyStaffAssignments = async () => {
      for (const event of events) {
        if (!event.assigned_staff || event.assigned_staff.length === 0) continue;

        for (const staff of event.assigned_staff) {
          const user = users.find(u => u.email === staff.email);
          if (!user) continue;

          const prefs = user.notification_preferences || {};
          if (!prefs.shift_assignments) continue;

          // Check if notification already sent (within last 24h)
          const recentNotifs = await base44.entities.ActivityLog.filter({
            user_id: user.id,
            activity_type: 'staff_assigned',
            related_entity_id: event.id,
          });

          const alreadyNotified = recentNotifs.some(n => {
            const notifDate = new Date(n.created_date);
            const hoursSince = (Date.now() - notifDate.getTime()) / (1000 * 60 * 60);
            return hoursSince < 24;
          });

          if (alreadyNotified) continue;

          await createNotification(
            user.id,
            '🎯 New Shift Assignment',
            `You've been assigned to ${event.event_name} on ${new Date(event.date).toLocaleDateString()}`,
            'staff_assigned',
            event.id
          );

          await sendEmail(
            staff.email,
            `New Shift Assignment - ${event.event_name}`,
            `Hello ${staff.staff_name},\n\nYou've been assigned to work at ${event.event_name}.\n\nDate: ${new Date(event.date).toLocaleDateString()}\nLocation: ${event.event_location || event.hub}\n\nPlease confirm your availability in the KROW platform.\n\nThank you!`,
            prefs
          );
        }
      }
    };

    if (events.length > 0 && users.length > 0) {
      notifyStaffAssignments();
    }
  }, [events, users]);

  // Shift reminder (24 hours before)
  useEffect(() => {
    const sendShiftReminders = async () => {
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(0, 0, 0, 0);

      const tomorrowEnd = new Date(tomorrow);
      tomorrowEnd.setHours(23, 59, 59, 999);

      for (const event of events) {
        const eventDate = new Date(event.date);
        if (eventDate < tomorrow || eventDate > tomorrowEnd) continue;
        if (!event.assigned_staff || event.assigned_staff.length === 0) continue;

        for (const staff of event.assigned_staff) {
          const user = users.find(u => u.email === staff.email);
          if (!user) continue;

          const prefs = user.notification_preferences || {};
          if (!prefs.shift_reminders) continue;

          await createNotification(
            user.id,
            '⏰ Shift Reminder',
            `Reminder: Your shift at ${event.event_name} is tomorrow`,
            'EVENT_UPDATED',
            event.id
          );

          await sendEmail(
            staff.email,
            `Shift Reminder - Tomorrow at ${event.event_name}`,
            `Hello ${staff.staff_name},\n\nThis is a reminder that you have a shift tomorrow:\n\nEvent: ${event.event_name}\nDate: ${new Date(event.date).toLocaleDateString()}\nLocation: ${event.event_location || event.hub}\n\nSee you there!`,
            prefs
          );
        }
      }
    };

    if (events.length > 0 && users.length > 0) {
      sendShiftReminders();
    }
  }, [events, users]);

  // Client upcoming event notifications (3 days before)
  useEffect(() => {
    const notifyClientsUpcomingEvents = async () => {
      const threeDaysFromNow = new Date();
      threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3);
      threeDaysFromNow.setHours(0, 0, 0, 0);

      const threeDaysEnd = new Date(threeDaysFromNow);
      threeDaysEnd.setHours(23, 59, 59, 999);

      for (const event of events) {
        const eventDate = new Date(event.date);
        if (eventDate < threeDaysFromNow || eventDate > threeDaysEnd) continue;

        const clientUser = users.find(u => 
          u.email === event.client_email || 
          (u.role === 'client' && u.full_name === event.client_name)
        );

        if (!clientUser) continue;

        const prefs = clientUser.notification_preferences || {};
        if (!prefs.upcoming_events) continue;

        await createNotification(
          clientUser.id,
          '📅 Upcoming Event',
          `Your event "${event.event_name}" is in 3 days`,
          'EVENT_CREATED',
          event.id
        );

        await sendEmail(
          clientUser.email,
          `Upcoming Event Reminder - ${event.event_name}`,
          `Hello,\n\nThis is a reminder that your event is coming up in 3 days:\n\nEvent: ${event.event_name}\nDate: ${new Date(event.date).toLocaleDateString()}\nLocation: ${event.event_location || event.hub}\nStaff Assigned: ${event.assigned_staff?.length || 0}/${event.requested || 0}\n\nIf you need to make any changes, please log into your KROW account.`,
          prefs
        );
      }
    };

    if (events.length > 0 && users.length > 0) {
      notifyClientsUpcomingEvents();
    }
  }, [events, users]);

  // Vendor new lead notifications (new events without vendor assignment)
  useEffect(() => {
    const notifyVendorsNewLeads = async () => {
      const newEvents = events.filter(e => 
        e.status === 'DRAFT' || e.status === 'PENDING'
      );

      const vendorUsers = users.filter(u => u.role === 'vendor');

      for (const event of newEvents) {
        for (const vendor of vendorUsers) {
          const prefs = vendor.notification_preferences || {};
          if (!prefs.new_leads) continue;

          // Check if already notified
          const recentNotifs = await base44.entities.ActivityLog.filter({
            userId: vendor.id,
            activityType: 'EVENT_CREATED',
            related_entity_id: event.id,
          });

          if (recentNotifs.length > 0) continue;

          await createNotification(
            vendor.id,
            '🎯 New Lead Available',
            `New opportunity: ${event.event_name} needs ${event.requested || 0} staff`,
            'EVENT_CREATED',
            event.id
          );

          await sendEmail(
            vendor.email,
            `New Staffing Opportunity - ${event.event_name}`,
            `Hello,\n\nA new staffing opportunity is available:\n\nEvent: ${event.event_name}\nDate: ${new Date(event.date).toLocaleDateString()}\nLocation: ${event.event_location || event.hub}\nStaff Needed: ${event.requested || 0}\n\nLog in to KROW to submit your proposal.`,
            prefs
          );
        }
      }
    };

    if (events.length > 0 && users.length > 0) {
      notifyVendorsNewLeads();
    }
  }, [events, users]);

  return null; // Background service
}

export default NotificationEngine;