import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Bell, Check, Heart, Star, MessageSquare, Tag, Shield, AlertTriangle, Ban, UserCheck, FileCheck, CalendarCheck, CalendarX, DollarSign, Home } from 'lucide-react';
import { Button } from '../components/ui/Button';
import { api } from '../api/client';
import { formatDate } from '../utils/format';
import type { NotificationType, Notification, PaginatedResponse } from '../types';

const iconMap: Record<NotificationType, typeof Bell> = {
  NEW_OFFER: Tag,
  OFFER_ACCEPTED: Check,
  OFFER_DECLINED: Bell,
  ITEM_SOLD: Star,
  NEW_MESSAGE: MessageSquare,
  ITEM_FAVORITED: Heart,
  LISTING_APPROVED: FileCheck,
  LISTING_REJECTED: AlertTriangle,
  MODERATION_WARNING: Shield,
  ACCOUNT_BANNED: Ban,
  ACCOUNT_UNBANNED: UserCheck,
  REPORT_RESOLVED: Check,
  BOOKING_REQUEST: CalendarCheck,
  BOOKING_CONFIRMED: CalendarCheck,
  BOOKING_REJECTED: CalendarX,
  BOOKING_CANCELLED: CalendarX,
  BOOKING_STARTED: Home,
  BOOKING_COMPLETED: Check,
  RENTAL_REVIEW: Star,
  PAYOUT_SENT: DollarSign,
  PAYOUT_FAILED: AlertTriangle,
};

const iconColorMap: Record<NotificationType, string> = {
  NEW_OFFER: 'text-primary-500 bg-primary-50',
  OFFER_ACCEPTED: 'text-green-500 bg-green-50',
  OFFER_DECLINED: 'text-red-500 bg-red-50',
  ITEM_SOLD: 'text-yellow-500 bg-yellow-50',
  NEW_MESSAGE: 'text-blue-500 bg-blue-50',
  ITEM_FAVORITED: 'text-pink-500 bg-pink-50',
  LISTING_APPROVED: 'text-green-500 bg-green-50',
  LISTING_REJECTED: 'text-red-500 bg-red-50',
  MODERATION_WARNING: 'text-orange-500 bg-orange-50',
  ACCOUNT_BANNED: 'text-red-500 bg-red-50',
  ACCOUNT_UNBANNED: 'text-green-500 bg-green-50',
  REPORT_RESOLVED: 'text-blue-500 bg-blue-50',
  BOOKING_REQUEST: 'text-primary-500 bg-primary-50',
  BOOKING_CONFIRMED: 'text-green-500 bg-green-50',
  BOOKING_REJECTED: 'text-red-500 bg-red-50',
  BOOKING_CANCELLED: 'text-orange-500 bg-orange-50',
  BOOKING_STARTED: 'text-blue-500 bg-blue-50',
  BOOKING_COMPLETED: 'text-green-500 bg-green-50',
  RENTAL_REVIEW: 'text-yellow-500 bg-yellow-50',
  PAYOUT_SENT: 'text-green-500 bg-green-50',
  PAYOUT_FAILED: 'text-red-500 bg-red-50',
};

export function NotificationsPage() {
  const navigate = useNavigate();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchNotifications = () => {
    api.get<PaginatedResponse<Notification>>('/notifications')
      .then(res => setNotifications(res.data))
      .catch(() => setNotifications([]))
      .finally(() => setLoading(false));
  };

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

  const handleMarkAllRead = async () => {
    await api.patch('/notifications/read-all');
    fetchNotifications();
  };

  const handleNotificationClick = (notif: Notification) => {
    if (notif.type === 'NEW_OFFER' || notif.type === 'OFFER_ACCEPTED' || notif.type === 'OFFER_DECLINED') {
      navigate('/dashboard/offers');
    } else if (notif.type === 'NEW_MESSAGE') {
      navigate('/dashboard/messages', { state: { conversationId: (notif.data as { conversationId?: string })?.conversationId } });
    } else if (notif.type === 'ITEM_FAVORITED' || notif.type === 'ITEM_SOLD') {
      const listingId = (notif.data as { listingId?: string })?.listingId;
      if (listingId) navigate(`/listings/${listingId}`);
    } else if (notif.type === 'BOOKING_REQUEST' || notif.type === 'BOOKING_CANCELLED') {
      navigate('/landlord/bookings');
    } else if (notif.type === 'BOOKING_CONFIRMED' || notif.type === 'BOOKING_REJECTED' || notif.type === 'BOOKING_COMPLETED') {
      navigate('/dashboard/bookings');
    } else if (notif.type === 'PAYOUT_SENT' || notif.type === 'PAYOUT_FAILED') {
      navigate('/landlord/payouts');
    } else if (notif.type === 'RENTAL_REVIEW') {
      navigate('/landlord/reviews');
    }
  };

  if (loading) return <div className="text-center text-gray-500 py-12">Loading notifications...</div>;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Notifications</h1>
        </div>
        <Button variant="ghost" size="sm" onClick={handleMarkAllRead}>Mark All As Read</Button>
      </div>

      {notifications.length === 0 ? (
        <p className="text-center text-gray-400 py-12">No notifications</p>
      ) : (
        <div className="space-y-2">
          {notifications.map(notif => {
            const Icon = iconMap[notif.type] || Bell;
            const colorClass = iconColorMap[notif.type] || 'text-gray-500 bg-gray-50';

            return (
              <button key={notif.id} onClick={() => handleNotificationClick(notif)}
                className={`w-full flex items-center gap-4 p-4 rounded-2xl border transition-colors text-left cursor-pointer ${notif.isRead ? 'bg-white border-gray-100 hover:bg-gray-50' : 'bg-primary-50/50 border-primary-100 hover:bg-primary-50'}`}>
                <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${colorClass}`}>
                  <Icon className="w-5 h-5" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className={`text-sm ${notif.isRead ? 'text-gray-600' : 'text-gray-900 font-medium'}`}>{notif.body}</p>
                  <p className="text-xs text-gray-400 mt-1">{formatDate(notif.createdAt)}</p>
                </div>
                {(notif.type === 'NEW_OFFER' || notif.type === 'OFFER_ACCEPTED') && (
                  <span className="text-xs font-medium text-primary-600 flex-shrink-0">
                    View Offer
                  </span>
                )}
                {!notif.isRead && <div className="w-2 h-2 bg-primary-500 rounded-full flex-shrink-0" />}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
