import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import { useSocket } from '../context/SocketContext';
import { api } from '../context/AuthContext';
import { Bell, Loader2, Check, X, Mail, MessageSquare, CreditCard, Star, AlertCircle, Calendar, Clock } from 'lucide-react';
import { format, parseISO } from 'date-fns';

const typeIcons = {
  booking: Calendar,
  message: MessageSquare,
  payment: CreditCard,
  review: Star,
  system: AlertCircle,
};

export default function Notifications() {
  const { user } = useAuth();
  const { notifications, unreadCount, markRead, markAllRead } = useSocket();
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [filter, setFilter] = useState('all');

  useEffect(() => {
    const params = new URLSearchParams({ page, limit: 20 });
    if (filter !== 'all') params.set('type', filter);
    if (filter === 'unread') params.set('unreadOnly', 'true');
    setLoading(true);
    api.get(`/notifications?${params}`).then(res => {
      setPages(res.data.pages);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [page, filter]);

  const handleMarkAllRead = async () => {
    try {
      await api.put('/notifications/read-all');
      markAllRead();
    } catch {
      // fallback handled by socket
    }
  };

  if (loading) {
    return (
      <div className="container py-8">
        <h1 className="text-2xl font-bold mb-6">Notifications</h1>
        <div className="space-y-4">
          {[1,2,3,4,5].map(i => (
            <div key={i} className="card animate-pulse p-4">
              <div className="flex gap-4">
                <div className="w-10 h-10 bg-gray-200 rounded-full" />
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-gray-200 rounded w-1/2" />
                  <div className="h-4 bg-gray-200 rounded w-1/3" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  const filteredNotifications = notifications.filter(n => {
    if (filter === 'unread') return !n.read;
    if (filter !== 'all') return n.type === filter;
    return true;
  });

  return (
    <div className="container py-8">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Notifications</h1>
          <p className="text-gray-600">{unreadCount} unread</p>
        </div>
        {unreadCount > 0 && (
          <button onClick={handleMarkAllRead} className="btn-secondary text-sm">
            Mark all as read
          </button>
        )}
      </div>

      <div className="card">
        <div className="border-b border-gray-100 px-4 py-3 overflow-x-auto">
          <nav className="flex gap-2 min-w-max" role="tablist">
            {['all', 'unread', 'booking', 'message', 'payment', 'review', 'system'].map(f => (
              <button
                key={f}
                role="tab"
                aria-selected={filter === f}
                onClick={() => { setFilter(f); setPage(1); }}
                className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${filter === f ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
              >
                {f === 'all' ? 'All' : f === 'unread' ? 'Unread' : f.charAt(0).toUpperCase() + f.slice(1)}
              </button>
            ))}
          </nav>
        </div>

        {filteredNotifications.length === 0 ? (
          <div className="p-12 text-center">
            <Bell className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900">No notifications</h3>
            <p className="text-gray-500 mt-1">{filter !== 'all' ? `No ${filter} notifications` : 'You are all caught up!'}</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {filteredNotifications.map(notif => {
              const Icon = typeIcons[notif.type] || Bell;
              return (
                <div
                  key={notif._id}
                  className={`p-4 hover:bg-gray-50 transition-colors ${!notif.read ? 'bg-primary-50/30' : ''}`}
                >
                  <div className="flex gap-4">
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${!notif.read ? 'bg-primary-100 text-primary-600' : 'bg-gray-100 text-gray-500'}`}>
                      <Icon className="w-5 h-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-4">
                        <div>
                          <p className={`font-medium ${!notif.read ? 'text-gray-900' : 'text-gray-700'}`}>{notif.title}</p>
                          {notif.message && <p className="text-sm text-gray-600 mt-1">{notif.message}</p>}
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-gray-500 whitespace-nowrap">{format(parseISO(notif.createdAt), 'MMM d, h:mm a')}</span>
                          {!notif.read && (
                            <button onClick={() => markRead(notif._id)} className="p-1 text-gray-400 hover:text-primary-600" aria-label="Mark as read">
                              <Check className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </div>
                      {notif.data?.bookingId && (
                        <a href={`/bookings/${notif.data.bookingId}`} className="mt-2 inline-block text-sm text-primary-600 hover:underline">
                          View Booking
                        </a>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {pages > 1 && (
          <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-center gap-2">
            <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="btn-secondary text-sm">Previous</button>
            <span className="text-sm text-gray-600">Page {page} of {pages}</span>
            <button onClick={() => setPage(p => Math.min(pages, p + 1))} disabled={page === pages} className="btn-secondary text-sm">Next</button>
          </div>
        )}
      </div>
    </div>
  );
}