import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getNonce } from '../Helpers';
import NotificationsIcon from '@mui/icons-material/Notifications';
import CloseIcon from '@mui/icons-material/Close';
import CheckIcon from '@mui/icons-material/Check';
import VisibilityIcon from '@mui/icons-material/Visibility';
import '../styles/_admin-notifications.scss';

interface Notification {
  id: number;
  form_id: string;
  form_name: string;
  submission_count: number;
  submitted_at: string;
  is_read: number;
  created_at: string;
}

const AdminNotifications: React.FC = () => {
  const navigate = useNavigate();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [showNotifications, setShowNotifications] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isDismissingAll, setIsDismissingAll] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [dismissedNotifications, setDismissedNotifications] = useState<number[]>([]);

  // Load dismissed notifications from localStorage on component mount
  useEffect(() => {
    const savedDismissed = localStorage.getItem('dismissedNotifications');
    if (savedDismissed) {
      try {
        const dismissedIds = JSON.parse(savedDismissed);
        setDismissedNotifications(Array.isArray(dismissedIds) ? dismissedIds : []);
      } catch (error) {
        console.error('Error loading dismissed notifications:', error);
        setDismissedNotifications([]);
      }
    }
  }, []);

  // Fetch notifications on component mount and periodically
  useEffect(() => {
    fetchNotifications();

    // Set up periodic checking for new notifications (every 30 seconds)
    const fetchInterval = setInterval(fetchNotifications, 30000);

    // Update current time every 30 seconds to refresh "time ago" display
    const timeInterval = setInterval(() => {
      setCurrentTime(new Date());
    }, 30000);

    return () => {
      clearInterval(fetchInterval);
      clearInterval(timeInterval);
    };
  }, []);

  // Auto-show notifications when new ones arrive, auto-hide when none left
  useEffect(() => {
    if (notifications.length > 0) {
      setShowNotifications(true);

      // Auto-hide after 60 seconds (1 minute)
      const autoHideTimer = setTimeout(() => {
        setShowNotifications(false);
      }, 60000);

      return () => clearTimeout(autoHideTimer);
    } else {
      // Auto-close panel when no notifications are left
      setShowNotifications(false);
    }
  }, [notifications.length]);

  const fetchNotifications = async () => {
    setIsLoading(true);

    try {
      const response = await fetch((window as any).ajaxurl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          action: 'simpleform_get_admin_notifications',
          nonce: getNonce(),
        }),
      });

      const data = await response.json();

      if (data.success) {
        const newNotifications = data.data.notifications || [];

        // Debug: Log raw notifications from backend (remove in production)
        if (newNotifications.length > 0) {
          console.log('Raw notifications from backend:', newNotifications);
        }


        // Get current dismissed notifications from localStorage to ensure we have the latest
        const currentDismissed = JSON.parse(localStorage.getItem('dismissedNotifications') || '[]');

        // Update state if it's different from localStorage
        if (JSON.stringify(dismissedNotifications) !== JSON.stringify(currentDismissed)) {
          setDismissedNotifications(currentDismissed);
        }

        // Filter out dismissed notifications and deduplicate
        const filteredNotifications = newNotifications.filter((notification: any) => {
          // First, filter out dismissed notifications
          if (currentDismissed.includes(notification.id)) {
            return false;
          }
          return true;
        });

        // Deduplicate notifications based on ID only (each notification should be unique by ID)
        const uniqueNotifications = filteredNotifications.filter((notification: any, index: number, self: any[]) => {
          return index === self.findIndex((n: any) => n.id === notification.id);
        });

        // Sort notifications by submitted_at (most recent first) to ensure proper time display
        uniqueNotifications.sort((a: any, b: any) => {
          const dateA = new Date(a.submitted_at || a.created_at);
          const dateB = new Date(b.submitted_at || b.created_at);
          return dateB.getTime() - dateA.getTime();
        });

        // Debug: Log deduplicated notifications (remove in production)
        if (uniqueNotifications.length !== newNotifications.length) {
          console.log('Duplicates removed:', newNotifications.length - uniqueNotifications.length);
        }

        // Only update state if notifications have actually changed
        setNotifications(prevNotifications => {
          // Check if the new notifications are different from current ones
          const hasChanges = JSON.stringify(prevNotifications) !== JSON.stringify(uniqueNotifications);
          return hasChanges ? uniqueNotifications : prevNotifications;
        });
      }
    } catch (error) {
      console.error('Error fetching notifications:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const markAsRead = async (notificationId: number) => {
    try {
      // Add to dismissed notifications immediately for instant UI feedback
      const newDismissed = [...dismissedNotifications, notificationId];
      setDismissedNotifications(newDismissed);

      // Save to localStorage
      localStorage.setItem('dismissedNotifications', JSON.stringify(newDismissed));

      // Remove from current notifications list
      setNotifications(prev => prev.filter(n => n.id !== notificationId));

      // Mark as read on backend
      const response = await fetch((window as any).ajaxurl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          action: 'simpleform_mark_notification_read',
          nonce: getNonce(),
          notification_id: notificationId.toString(),
        }),
      });

      const data = await response.json();

      if (!data.success) {
        console.error('Failed to mark notification as read on backend');
        // Optionally revert the local state if backend fails
      }
    } catch (error) {
      console.error('Error marking notification as read:', error);
    }
  };

  const dismissAllNotifications = async () => {
    setIsDismissingAll(true);

    try {
      // Mark all current notifications as dismissed
      const allNotificationIds = notifications.map(n => n.id);
      const newDismissed = [...dismissedNotifications, ...allNotificationIds];

      setDismissedNotifications(newDismissed);

      // Save to localStorage
      localStorage.setItem('dismissedNotifications', JSON.stringify(newDismissed));

      // Clear current notifications immediately for instant UI feedback
      setNotifications([]);

      // Close the notifications panel
      setShowNotifications(false);

      // Mark all as read on backend (in parallel)
      const markReadPromises = notifications.map(notification =>
        fetch((window as any).ajaxurl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            action: 'simpleform_mark_notification_read',
            nonce: getNonce(),
            notification_id: notification.id.toString(),
          }),
        }).catch(error => {
          console.error('Error marking notification as read:', error);
        })
      );

      // Wait for all backend calls to complete
      await Promise.all(markReadPromises);
    } catch (error) {
      console.error('Error in batch marking notifications as read:', error);
    } finally {
      setIsDismissingAll(false);
    }
  };

  const handleViewLeads = (formId: string, notificationId: number) => {
    // Mark this specific notification as read when viewing
    markAsRead(notificationId);

    // Navigate to leads page with form ID as query parameter
    navigate(`/leads?form_id=${formId}`);

    // Close notifications panel
    setShowNotifications(false);
  };

  const closeNotificationsPanel = () => {
    // Just close the panel without marking as read
    setShowNotifications(false);
  };

  const parseWordPressDate = (dateString: string): Date => {
    if (!dateString) return new Date();

    // WordPress typically returns dates in 'YYYY-MM-DD HH:MM:SS' format in local timezone
    // or sometimes with timezone info

    // First, try parsing as-is
    let date = new Date(dateString);

    if (!isNaN(date.getTime())) {
      return date;
    }

    // Try MySQL datetime format (YYYY-MM-DD HH:MM:SS) by adding 'T'
    const isoFormat = dateString.replace(' ', 'T');
    date = new Date(isoFormat);

    if (!isNaN(date.getTime())) {
      return date;
    }

    // Try adding local timezone offset
    const withTimezone = dateString + (dateString.includes('Z') || dateString.includes('+') ? '' : 'Z');
    date = new Date(withTimezone);

    if (!isNaN(date.getTime())) {
      return date;
    }

    // Fallback to current time if all parsing fails
    console.warn('Could not parse date string:', dateString);
    return new Date();
  };

  const formatTimeAgo = (dateString: string) => {
    const date = parseWordPressDate(dateString);
    const now = currentTime; // Use state-managed current time for real-time updates

    // Calculate difference in milliseconds
    const diffInMs = now.getTime() - date.getTime();
    const diffInSeconds = Math.floor(diffInMs / 1000);
    const diffInMinutes = Math.floor(diffInSeconds / 60);

    // Handle very recent submissions (less than 30 seconds)
    if (diffInSeconds < 30) return 'Just now';

    // Handle negative differences (future dates) - could be timezone issue
    if (diffInSeconds < 0) {
      console.warn('Notification date appears to be in the future. Possible timezone issue.');
      return 'Just now';
    }

    // Less than 1 minute
    if (diffInMinutes < 1) return 'Less than a minute ago';

    // Minutes
    if (diffInMinutes < 60) {
      return `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
    }

    // Hours
    const diffInHours = Math.floor(diffInMinutes / 60);
    if (diffInHours < 24) {
      return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
    }

    // Days
    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays < 7) {
      return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
    }

    // Weeks
    const diffInWeeks = Math.floor(diffInDays / 7);
    return `${diffInWeeks} week${diffInWeeks > 1 ? 's' : ''} ago`;
  };

  // Don't render anything if no notifications
  if (notifications.length === 0) {
    return null;
  }

  return (
    <div className="admin-notifications-container">
      {/* Notification Bell Icon - Only show when there are notifications */}
      <div className="notification-bell" onClick={() => setShowNotifications(!showNotifications)}>
        <NotificationsIcon />
        <span className="notification-badge">{notifications.length}</span>
      </div>

      {/* Notifications Panel */}
      {showNotifications && (
        <div className="notifications-panel">
          <div className="notifications-header">
            <h3>Form Submissions</h3>
            <div className="header-actions">
              {notifications.length > 0 && (
                <button
                  className="dismiss-all-btn"
                  onClick={dismissAllNotifications}
                  disabled={isDismissingAll}
                  title="Mark all as read"
                >
                  <CheckIcon />
                  {isDismissingAll && <span className="loading-spinner">...</span>}
                </button>
              )}
              <button
                className="close-btn"
                onClick={closeNotificationsPanel}
                title="Close notifications"
              >
                <CloseIcon />
              </button>
            </div>
          </div>

          <div className="notifications-list">
            {isLoading ? (
              <div className="loading-state">Loading notifications...</div>
            ) : (
              notifications.map((notification, index) => (
                <div key={`${notification.id}-${notification.form_id}-${index}`} className="notification-item">
                  <div className="notification-content">
                    <div className="notification-title">
                      New submission for "{notification.form_name}"
                    </div>
                    <div className="notification-meta">
                      <span className="submission-time">
                        {formatTimeAgo(notification.submitted_at || notification.created_at)}
                      </span>
                      <span className="form-id">Form ID: {notification.form_id}</span>
                      {notification.submission_count > 1 && (
                        <span className="submission-count">
                          {notification.submission_count} submissions
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="notification-actions">
                    <button
                      className="view-leads-btn"
                      onClick={() => handleViewLeads(notification.form_id, notification.id)}
                      title="View form submissions"
                    >
                      <VisibilityIcon />
                      <span>View</span>
                    </button>
                    <button
                      className="mark-read-btn"
                      onClick={() => markAsRead(notification.id)}
                      title="Mark as read"
                    >
                      <CloseIcon />
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>

          {notifications.length === 0 && !isLoading && (
            <div className="no-notifications">
              <p>No new form submissions</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default AdminNotifications;