'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';

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

interface NotificationListProps {
  onClose: () => void;
}

export default function NotificationList({ onClose }: NotificationListProps) {
  const { data: session } = useSession();
  const router = useRouter();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);

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

  const fetchNotifications = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/notifications?page=${page}&limit=20`);
      if (response.ok) {
        const data = await response.json();
        // Filter out message notifications as they should only show in Messages dropdown
        const filteredNotifications = (data.data.notifications || []).filter(
          (notification: Notification) => notification.type !== 'message_received'
        );
        
        if (page === 1) {
          setNotifications(filteredNotifications);
        } else {
          setNotifications(prev => [...prev, ...filteredNotifications]);
        }
        setHasMore(data.data.pagination.hasNext);
      }
    } catch (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) {
        setNotifications(prev =>
          prev.map(notif =>
            notif.id === notificationId
              ? { ...notif, isRead: true, readAt: new Date().toISOString() }
              : notif
          )
        );
      }
    } catch (error) {
    }
  };

  const markAllAsRead = async () => {
    try {
      const response = await fetch('/api/notifications/mark-all-read', {
        method: 'PUT',
      });

      if (response.ok) {
        setNotifications(prev =>
          prev.map(notif => ({
            ...notif,
            isRead: true,
            readAt: new Date().toISOString()
          }))
        );
      }
    } catch (error) {
    }
  };

  const loadMore = () => {
    if (!loading && hasMore) {
      setPage(prev => prev + 1);
    }
  };

  const handleNotificationClick = async (notification: Notification) => {
    // Mark as read first
    if (!notification.isRead) {
      await markAsRead(notification.id);
    }

    // Handle redirect based on notification type
    if (notification.type === 'bid_received' && notification.data) {
      try {
        const data = JSON.parse(notification.data);
        const { freelancerId } = data;
        
        if (freelancerId) {
          // Redirect to messages with the freelancer preselected
          const userRole = session?.user?.role?.toLowerCase();
          if (userRole === 'client') {
            router.push(`/client/messages?contactId=${freelancerId}`);
          } else if (userRole === 'freelancer') {
            router.push(`/freelancer/messages?contactId=${freelancerId}`);
          }
          onClose(); // Close notification panel
        }
      } catch (error) {
      }
    } else if (notification.type === 'project_awarded' && notification.data) {
      try {
        const data = JSON.parse(notification.data);
        const { clientId } = data;
        
        if (clientId) {
          // Redirect to messages with the client preselected
          const userRole = session?.user?.role?.toLowerCase();
          if (userRole === 'freelancer') {
            router.push(`/freelancer/messages?contactId=${clientId}`);
          } else if (userRole === 'client') {
            router.push(`/client/messages?contactId=${clientId}`);
          }
          onClose(); // Close notification panel
        }
      } catch (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 getNotificationIcon = (type: string) => {
    switch (type) {
      case 'message_received':
        return '/assets/image/messageicon.svg';
      case 'bid_received':
      case 'project_awarded':
        return '/assets/image/briefcase.svg';
      default:
        return '/assets/image/notification.svg';
    }
  };

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

  return (
    <div className="notification-panel position-absolute top-100 end-0 bg-white border rounded shadow-lg" style={{ width: '400px', maxHeight: '500px', zIndex: 1050 }}>
      <div className="d-flex justify-content-between align-items-center p-3 border-bottom">
        <h6 className="mb-0">Notifications</h6>
        <div>
          {notifications.some(n => !n.isRead) && (
            <button
              className="btn btn-sm btn-link text-primary me-2"
              onClick={markAllAsRead}
            >
              Mark all read
            </button>
          )}
          {/* <button className="btn btn-sm btn-link text-muted" onClick={onClose}>
            ×
          </button> */}
        </div>
      </div>

      <div className="notification-list" style={{ maxHeight: '400px', overflowY: 'auto' }}>
        {loading && page === 1 ? (
          <div className="p-4 text-center">
            <div className="spinner-border spinner-border-sm" role="status">
              <span className="visually-hidden">Loading...</span>
            </div>
          </div>
        ) : notifications.length === 0 ? (
          <div className="p-4 text-center text-muted">
            <img src="/assets/image/notification.svg" alt="" width="48" height="48" className="mb-2 opacity-50" />
            <p className="mb-0">No notifications yet</p>
          </div>
        ) : (
          <>
            {notifications.map((notification) => (
              <div
                key={notification.id}
                className={`notification-item p-3 border-bottom cursor-pointer ${!notification.isRead ? 'bg-light' : ''}`}
                onClick={() => handleNotificationClick(notification)}
              >
                <div className="d-flex">
                  <img
                    src={getNotificationIcon(notification.type)}
                    alt=""
                    width="24"
                    height="24"
                    className="me-3 mt-1"
                  />
                  <div className="flex-grow-1">
                    <div className="d-flex justify-content-between align-items-start">
                      <h6 className={`mb-1 ${!notification.isRead ? 'fw-bold' : ''}`}>
                        {notification.title}
                      </h6>
                      {!notification.isRead && (
                        <span className="badge bg-primary rounded-pill ms-2" style={{ width: '8px', height: '8px', padding: 0 }}></span>
                      )}
                    </div>
                    <p className="mb-1 small text-muted">{notification.message}</p>
                    <small className="text-muted">{formatTimeAgo(notification.createdAt)}</small>
                  </div>
                </div>
              </div>
            ))}

            {hasMore && (
              <div className="p-3 text-center">
                <button
                  className="btn btn-sm btn-outline-primary"
                  onClick={loadMore}
                  disabled={loading}
                >
                  {loading ? (
                    <>
                      <span className="spinner-border spinner-border-sm me-2" role="status"></span>
                      Loading...
                    </>
                  ) : (
                    'Load more'
                  )}
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}