'use client';

import React, { useState, useEffect } from 'react';
import { 
  Bell, BellOff, CheckCircle, Mail, 
  Building, Users, AlertCircle, MessageSquare,
  ChevronRight, Clock, X, Trash2, 
  Eye, EyeOff, RefreshCw, Filter, Search,
  Calendar, User, University, FileText,
  Check, Loader2, Info
} from 'lucide-react';
import Heading from '../../atoms/Heading';
import { useUserStore } from '../../../../store/useUserStore';

// Icon mapping based on notification type
const getNotificationIcon = (type, isRead) => {
  const IconComponent = {
    university: University,
    application: FileText,
    student: Users,
    system: AlertCircle,
    email: Mail,
    default: Bell
  }[type] || Bell;

  return <IconComponent size={20} className={isRead ? 'text-gray-400' : 'text-[#0B6D76]'} />;
};

// Type badge colors
const getTypeBadgeColor = (type) => {
  const colors = {
    university: 'bg-purple-100 text-purple-700',
    application: 'bg-blue-100 text-blue-700',
    student: 'bg-emerald-100 text-emerald-700',
    system: 'bg-amber-100 text-amber-700',
    email: 'bg-cyan-100 text-cyan-700',
    default: 'bg-gray-100 text-gray-700'
  };
  return colors[type] || colors.default;
};

// Type display names
const getTypeDisplayName = (type) => {
  const names = {
    university: 'University',
    application: 'Application',
    student: 'Student',
    system: 'System',
    email: 'Message',
    default: 'Notification'
  };
  return names[type] || names.default;
};

const ConsultantNotification = () => {
  const { user } = useUserStore();
  const [notifications, setNotifications] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filter, setFilter] = useState('all'); // 'all', 'unread', 'type'
  const [searchTerm, setSearchTerm] = useState('');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [selectedType, setSelectedType] = useState('all');

  // Fetch notifications
  const fetchNotifications = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/frontend/notifications');
      
      if (!response.ok) {
        throw new Error('Failed to fetch notifications');
      }
      
      const data = await response.json();
      
      if (data.success) {
        setNotifications(data.data.notifications);
      }
    } catch (error) {
      console.error('Error fetching notifications:', error);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };

  // Mark all as read
  const markAllAsRead = async () => {
    try {
      const response = await fetch('/api/frontend/notifications', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ markAllAsRead: true })
      });

      if (response.ok) {
        fetchNotifications(); // Refresh list
      }
    } catch (error) {
      console.error('Error marking all as read:', error);
    }
  };

  // Delete notification
  const deleteNotification = async (id) => {
    try {
      const response = await fetch(`/api/frontend/notifications?id=${id}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        setNotifications(prev => prev.filter(n => n.id !== id));
      }
    } catch (error) {
      console.error('Error deleting notification:', error);
    }
  };

  // Clear all notifications
  const clearAllNotifications = async () => {
    if (!confirm('Are you sure you want to clear all notifications?')) return;
    
    try {
      const response = await fetch('/api/frontend/notifications', {
        method: 'DELETE'
      });

      if (response.ok) {
        setNotifications([]);
      }
    } catch (error) {
      console.error('Error clearing notifications:', error);
    }
  };

  // Filter notifications
  const filteredNotifications = notifications.filter(notification => {
    // Filter by read status
    if (filter === 'unread' && notification.isRead) return false;
    
    // Filter by type
    if (selectedType !== 'all' && notification.type !== selectedType) return false;
    
    // Filter by search term
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      return (
        notification.title?.toLowerCase().includes(searchLower) ||
        notification.description?.toLowerCase().includes(searchLower) ||
        notification.name?.toLowerCase().includes(searchLower) ||
        notification.email?.toLowerCase().includes(searchLower)
      );
    }
    
    return true;
  });

  // Get unique notification types
  const notificationTypes = [...new Set(notifications.map(n => n.type))];

  // Calculate stats
  const unreadCount = notifications.filter(n => !n.isRead).length;
  const totalCount = notifications.length;

  // Initial fetch
  useEffect(() => {
    fetchNotifications();
  }, []);

  // Auto-refresh every 30 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      if (!isLoading) {
        fetchNotifications();
      }
    }, 30000);

    return () => clearInterval(interval);
  }, [isLoading]);

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* Header Section */}
        <div className="mb-10">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-6">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
                <Bell size={28} className="text-white" />
              </div>
              <div>
                <Heading level={3} className="text-3xl font-bold text-gray-900">
                  Notifications Center
                </Heading>
                <p className="text-gray-600 mt-2">
                  Stay updated with your latest alerts and messages
                </p>
              </div>
            </div>
            
            {/* Stats Badges */}
            <div className="flex flex-wrap gap-3">
              <div className="px-4 py-2 bg-white rounded-xl border border-gray-200 shadow-sm">
                <div className="flex items-center gap-2">
                  <Bell size={16} className="text-[#0B6D76]" />
                  <span className="text-gray-700 font-medium">Total:</span>
                  <span className="font-bold text-gray-900">{totalCount}</span>
                </div>
              </div>
              
              <div className="px-4 py-2 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl border border-blue-200 shadow-sm">
                <div className="flex items-center gap-2">
                  <Bell size={16} className="text-blue-600" />
                  <span className="text-blue-700 font-medium">Unread:</span>
                  <span className="font-bold text-blue-800">{unreadCount}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Quick Actions Bar */}
          <div className="bg-gradient-to-r from-white to-gray-50 rounded-2xl p-4 border border-gray-200/80 shadow-sm mb-6">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <button
                  onClick={fetchNotifications}
                  disabled={isRefreshing}
                  className="px-4 py-2 bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white rounded-xl hover:shadow-lg transition-all flex items-center gap-2 disabled:opacity-50"
                >
                  {isRefreshing ? (
                    <Loader2 size={18} className="animate-spin" />
                  ) : (
                    <RefreshCw size={18} />
                  )}
                  {isRefreshing ? 'Refreshing...' : 'Refresh'}
                </button>
                
                <button
                  onClick={markAllAsRead}
                  disabled={unreadCount === 0}
                  className="px-4 py-2 bg-gradient-to-r from-emerald-500 to-green-600 text-white rounded-xl hover:shadow-lg transition-all flex items-center gap-2 disabled:opacity-50"
                >
                  <Check size={18} />
                  Mark All as Read
                </button>
              </div>
              
              <div className="flex items-center gap-3">
                <button
                  onClick={clearAllNotifications}
                  disabled={totalCount === 0}
                  className="px-4 py-2 bg-gradient-to-r from-rose-500 to-pink-600 text-white rounded-xl hover:shadow-lg transition-all flex items-center gap-2 disabled:opacity-50"
                >
                  <Trash2 size={18} />
                  Clear All
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Sidebar Filters */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl shadow-lg border border-gray-200 p-5 sticky top-6">
              <div className="mb-6">
                <h3 className="font-bold text-gray-900 text-lg mb-4 flex items-center gap-2">
                  <Filter size={20} />
                  Filters
                </h3>
                
                {/* Search */}
                <div className="relative mb-4">
                  <Search size={18} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search notifications..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6D76] focus:border-[#0B6D76] text-gray-700"
                  />
                </div>

                {/* Filter by Status */}
                <div className="mb-6">
                  <h4 className="text-sm font-semibold text-gray-700 mb-3">Status</h4>
                  <div className="space-y-2">
                    {[
                      { id: 'all', label: 'All Notifications', count: totalCount },
                      { id: 'unread', label: 'Unread Only', count: unreadCount }
                    ].map((status) => (
                      <button
                        key={status.id}
                        onClick={() => setFilter(status.id)}
                        className={`w-full flex items-center justify-between px-3 py-2 rounded-lg transition-all ${
                          filter === status.id 
                            ? 'bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white' 
                            : 'text-gray-700 hover:bg-gray-100'
                        }`}
                      >
                        <span className="flex items-center gap-2">
                          {filter === status.id ? <Check size={16} /> : <div className="w-4" />}
                          {status.label}
                        </span>
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                          filter === status.id 
                            ? 'bg-white/20 text-white' 
                            : 'bg-gray-100 text-gray-700'
                        }`}>
                          {status.count}
                        </span>
                      </button>
                    ))}
                  </div>
                </div>

                {/* Filter by Type */}
                <div>
                  <h4 className="text-sm font-semibold text-gray-700 mb-3">Notification Type</h4>
                  <div className="space-y-2">
                    <button
                      onClick={() => setSelectedType('all')}
                      className={`w-full flex items-center justify-between px-3 py-2 rounded-lg transition-all ${
                        selectedType === 'all' 
                          ? 'bg-gradient-to-r from-blue-500 to-cyan-600 text-white' 
                          : 'text-gray-700 hover:bg-gray-100'
                      }`}
                    >
                      <span className="flex items-center gap-2">
                        {selectedType === 'all' ? <Check size={16} /> : <div className="w-4" />}
                        All Types
                      </span>
                    </button>
                    
                    {notificationTypes.map((type) => {
                      const typeCount = notifications.filter(n => n.type === type).length;
                      const unreadTypeCount = notifications.filter(n => n.type === type && !n.isRead).length;
                      
                      return (
                        <button
                          key={type}
                          onClick={() => setSelectedType(type)}
                          className={`w-full flex items-center justify-between px-3 py-2 rounded-lg transition-all ${
                            selectedType === type 
                              ? 'bg-gradient-to-r from-blue-500 to-cyan-600 text-white' 
                              : 'text-gray-700 hover:bg-gray-100'
                          }`}
                        >
                          <span className="flex items-center gap-2">
                            {selectedType === type ? <Check size={16} /> : <div className="w-4" />}
                            {getTypeDisplayName(type)}
                          </span>
                          <div className="flex items-center gap-2">
                            {unreadTypeCount > 0 && (
                              <span className={`px-1.5 py-0.5 rounded-full text-xs font-medium ${
                                selectedType === type 
                                  ? 'bg-white/30 text-white' 
                                  : 'bg-blue-100 text-blue-700'
                              }`}>
                                {unreadTypeCount}
                              </span>
                            )}
                            <span className={`px-1.5 py-0.5 rounded-full text-xs font-medium ${
                              selectedType === type 
                                ? 'bg-white/20 text-white' 
                                : 'bg-gray-100 text-gray-700'
                            }`}>
                              {typeCount}
                            </span>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </div>
              </div>

              {/* Stats Summary */}
              <div className="pt-6 border-t border-gray-200">
                <h3 className="font-bold text-gray-900 text-lg mb-3">Summary</h3>
                <div className="space-y-3">
                  {notificationTypes.map((type) => {
                    const count = notifications.filter(n => n.type === type).length;
                    if (count === 0) return null;
                    
                    return (
                      <div key={type} className="flex items-center justify-between">
                        <span className="text-sm text-gray-600 flex items-center gap-2">
                          {getNotificationIcon(type, true)}
                          {getTypeDisplayName(type)}
                        </span>
                        <span className="font-medium text-gray-900">{count}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>

          {/* Notifications List */}
          <div className="lg:col-span-3">
            <div className="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden">
              {/* List Header */}
              <div className="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
                <div className="flex items-center justify-between">
                  <h3 className="text-xl font-bold text-gray-900">
                    {filteredNotifications.length} Notification{filteredNotifications.length !== 1 ? 's' : ''}
                  </h3>
                  <div className="text-sm text-gray-500">
                    {unreadCount > 0 ? `${unreadCount} unread` : 'All read'}
                  </div>
                </div>
              </div>

              {/* Notifications Content */}
              <div className="p-6">
                {isLoading ? (
                  <div className="flex flex-col items-center justify-center py-12">
                    <div className="w-12 h-12 border-4 border-[#0B6D76] border-t-transparent rounded-full animate-spin mb-4"></div>
                    <p className="text-gray-600">Loading notifications...</p>
                  </div>
                ) : filteredNotifications.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12">
                    <div className="w-20 h-20 bg-gradient-to-r from-gray-100 to-gray-200 rounded-full flex items-center justify-center mb-4">
                      <BellOff size={32} className="text-gray-400" />
                    </div>
                    <h4 className="text-xl font-bold text-gray-900 mb-2">No notifications</h4>
                    <p className="text-gray-600 text-center max-w-md">
                      {searchTerm || selectedType !== 'all' || filter !== 'all'
                        ? 'No notifications match your current filters'
                        : 'You\'re all caught up! No new notifications.'}
                    </p>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {filteredNotifications.map((notification) => (
                      <div
                        key={notification.id}
                        className={`group relative rounded-xl border transition-all hover:shadow-md ${
                          notification.isRead 
                            ? 'bg-white border-gray-200' 
                            : 'bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200'
                        }`}
                      >
                        <div className="p-5">
                          <div className="flex items-start gap-4">
                            {/* Icon */}
                            <div className={`p-3 rounded-lg ${
                              notification.isRead 
                                ? 'bg-gray-100' 
                                : 'bg-gradient-to-r from-[#0B6D76] to-teal-600'
                            }`}>
                              {getNotificationIcon(notification.type, notification.isRead)}
                            </div>

                            {/* Content */}
                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between mb-2">
                                <div>
                                  <h4 className={`font-bold ${
                                    notification.isRead ? 'text-gray-800' : 'text-gray-900'
                                  }`}>
                                    {notification.title}
                                  </h4>
                                  
                                  {/* Sender info for emails */}
                                  {notification.type === 'email' && notification.name && (
                                    <div className="flex items-center gap-2 mt-1">
                                      <User size={14} className="text-gray-400" />
                                      <span className="text-sm text-gray-600">
                                        {notification.name}
                                        {notification.email && ` • ${notification.email}`}
                                      </span>
                                    </div>
                                  )}
                                </div>
                                
                                <div className="flex items-center gap-2">
                                  {/* Type badge */}
                                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getTypeBadgeColor(notification.type)}`}>
                                    {getTypeDisplayName(notification.type)}
                                  </span>
                                  
                                  {/* Time */}
                                  <div className="flex items-center gap-1 text-sm text-gray-500">
                                    <Clock size={14} />
                                    {notification.timeAgo}
                                  </div>
                                </div>
                              </div>

                              <p className={`text-gray-600 mb-3 ${
                                notification.isRead ? '' : 'font-medium'
                              }`}>
                                {notification.description}
                              </p>

                              {/* Footer with actions */}
                              <div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
                                <div className="flex items-center gap-3">
                                  <button
                                    onClick={() => deleteNotification(notification.id)}
                                    className="p-1.5 text-gray-400 hover:text-rose-600 transition-colors"
                                    title="Delete notification"
                                  >
                                    <Trash2 size={16} />
                                  </button>
                                  
                                  <span className={`px-2 py-1 rounded-full text-xs ${
                                    notification.isRead 
                                      ? 'bg-gray-100 text-gray-600' 
                                      : 'bg-blue-100 text-blue-700 font-medium'
                                  }`}>
                                    {notification.isRead ? 'Read' : 'New'}
                                  </span>
                                </div>
                                
                                <div className="flex items-center gap-2 text-sm text-gray-500">
                                  <Calendar size={14} />
                                  {new Date(notification.createdAt).toLocaleDateString('en-US', {
                                    month: 'short',
                                    day: 'numeric',
                                    year: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit'
                                  })}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>

                        {/* Hover actions */}
                        <div className="absolute top-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity">
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => deleteNotification(notification.id)}
                              className="p-2 bg-white rounded-lg shadow-sm border border-gray-200 hover:bg-rose-50 hover:text-rose-600 transition-colors"
                              title="Delete"
                            >
                              <X size={16} />
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Help Info */}
            <div className="mt-6 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-2xl p-5 border border-blue-200">
              <div className="flex items-start gap-3">
                <Info size={20} className="text-blue-600 mt-0.5" />
                <div>
                  <h4 className="font-bold text-blue-800 mb-1">About Notifications</h4>
                  <p className="text-blue-700 text-sm">
                    Notifications are automatically generated for important updates related to your account, 
                    universities, applications, and messages.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConsultantNotification;