'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import Image from 'next/image';

interface MessageNotification {
  id: string;
  type: string;
  title: string;
  message: string;
  data?: string;
  isRead: boolean;
  readAt?: string;
  createdAt: string;
}

interface MessagesDropdownProps {
  onClose?: () => void;
}

export default function MessagesDropdown({ onClose }: MessagesDropdownProps) {
  const { data: session } = useSession();
  const [messageNotifications, setMessageNotifications] = useState<MessageNotification[]>([]);
  const [loading, setLoading] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    if (session?.user?.email) {
      fetchMessageNotifications();
    }
  }, [session]);

  const fetchMessageNotifications = async () => {
    try {
      setLoading(true);
      // Fetch only message-type notifications
      const response = await fetch('/api/notifications?type=message_received&limit=10');
      if (response.ok) {
        const data = await response.json();
        const notifications = data.data.notifications || [];
        setMessageNotifications(notifications);
        setUnreadCount(notifications.filter((n: MessageNotification) => !n.isRead).length);
      }
    } catch (error) {
      console.error('Error fetching message notifications:', error);
    } finally {
      setLoading(false);
    }
  };

  const markAsRead = async (notificationId: string) => {
    try {
      const response = await fetch(`/api/notifications/${notificationId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ isRead: true }),
      });

      if (response.ok) {
        setMessageNotifications(prev =>
          prev.map(notif =>
            notif.id === notificationId
              ? { ...notif, isRead: true, readAt: new Date().toISOString() }
              : notif
          )
        );
        setUnreadCount(prev => Math.max(0, prev - 1));
      }
    } catch (error) {
      console.error('Error marking notification as read:', error);
    }
  };

  const markAllAsRead = async () => {
    try {
      // Mark all message-type notifications as read
      const unreadNotifications = messageNotifications.filter(n => !n.isRead);
      
      for (const notification of unreadNotifications) {
        await fetch(`/api/notifications/${notification.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ isRead: true }),
        });
      }

      setMessageNotifications(prev =>
        prev.map(notif => ({
          ...notif,
          isRead: true,
          readAt: new Date().toISOString()
        }))
      );
      setUnreadCount(0);
    } catch (error) {
      console.error('Error marking all notifications as read:', error);
    }
  };

  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInMinutes = Math.floor((now.getTime() - date.getTime()) / (1000 * 60));

    if (diffInMinutes < 1) return 'Just now';
    if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
    if (diffInMinutes < 1440) return `${Math.floor(diffInMinutes / 60)}h ago`;
    return `${Math.floor(diffInMinutes / 1440)}d ago`;
  };

  const handleNotificationClick = (notification: MessageNotification) => {
    if (!notification.isRead) {
      markAsRead(notification.id);
    }
    
    // Parse data to get navigation information
    try {
      const notificationData = notification.data ? JSON.parse(notification.data) : null;
      if (notificationData?.senderId) {
        // Navigate to messages with the sender
        const userRole = (session?.user as any)?.role?.toLowerCase() || '';
        window.location.href = `/${userRole}/messages?contactId=${notificationData.senderId}`;
      }
    } catch (error) {
      console.error('Error parsing notification data:', error);
      // Default navigation to messages
      const userRole = (session?.user as any)?.role?.toLowerCase() || '';
      window.location.href = `/${userRole}/messages`;
    }
  };

  const viewAllMessages = () => {
    const userRole = (session?.user as any)?.role?.toLowerCase() || '';
    window.location.href = `/${userRole}/messages`;
  };

  if (!session?.user) {
    return null;
  }

  return (
    <div className="notification-wrap message-wrap">
      <div className="dropdown">
        <a 
          className="dropdown-toggle" 
          href="#" 
          role="button" 
          data-bs-toggle="dropdown" 
          aria-expanded="false"
        >
          <Image 
            src="/assets/image/message-chat.svg" 
            alt="messages"
            width={20}
            height={20}
          />
          {unreadCount > 0 && <span className="count-no">{unreadCount}</span>}
        </a>
        <ul className="dropdown-menu dropdown-menu-end p-0" data-bs-popper="static">
          <li className="dropdown-menu-header border-bottom">
            <div className="dropdown-header d-flex align-items-center py-3">
              <h6 className="mb-0 me-auto">Messages</h6>
              <div className="d-flex align-items-center h6 mb-0">
                {unreadCount > 0 && (
                  <>
                    <span className="badge bg-label-primary me-2">{unreadCount} New</span>
                    <button
                      className="btn btn-sm btn-link text-primary p-0"
                      onClick={markAllAsRead}
                      disabled={loading}
                    >
                      Mark all read
                    </button>
                  </>
                )}
              </div>
            </div>
          </li>
          <li className="dropdown-notifications-list scrollable-container ps">
            <ul className="list-group list-group-flush">
              {loading ? (
                <li className="p-4 text-center">
                  <div className="spinner-border spinner-border-sm" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                </li>
              ) : messageNotifications.length === 0 ? (
                <li className="p-4 text-center text-muted">
                  <img src="/assets/image/message-chat.svg" alt="" width="48" height="48" className="mb-2 opacity-50" />
                  <p className="mb-0">No messages yet</p>
                </li>
              ) : (
                messageNotifications.map((notification) => (
                  <li 
                    key={notification.id} 
                    className={`list-group-item list-group-item-action dropdown-notifications-item waves-effect cursor-pointer ${!notification.isRead ? 'bg-light' : ''}`}
                    onClick={() => handleNotificationClick(notification)}
                  >
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <Image 
                            src="/assets/image/messageicon.svg" 
                            alt="Message"
                            width={40}
                            height={40}
                            className="rounded-circle"
                          />
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className={`small mb-1 ${!notification.isRead ? 'fw-bold' : ''}`}>
                          {notification.title}
                        </h6>
                        <small className="mb-1 d-block text-body">{notification.message}</small>
                        <small className="text-muted">{formatTimeAgo(notification.createdAt)}</small>
                      </div>
                      {!notification.isRead && (
                        <div className="flex-shrink-0 dropdown-notifications-actions">
                          <button type="button" className="dropdown-notifications-read">
                            <span className="badge-dot"></span>
                          </button>
                        </div>
                      )}
                    </div>
                  </li>
                ))
              )}
            </ul>
          </li>
          <li className="border-top">
            <div className="d-grid p-4">
              <button 
                type="button" 
                className="custom-btn primary-fill"
                onClick={viewAllMessages}
              >
                <small className="align-middle">View all Messages</small>
              </button>
            </div>
          </li>
        </ul>
      </div>
    </div>
  );
}