import { useState, useEffect } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { Bell, Check, CheckCheck, Package, ShoppingBag, Sparkles, Truck, Flame, X, Clock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useStore, type InAppNotification } from "@/lib/store";
import { formatDistanceToNow } from "date-fns";

export function NotificationDrawer({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { notifications, user, fetchNotifications, markNotificationRead, markAllNotificationsRead } = useStore();
  const navigate = useNavigate();

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

  if (!open) return null;

  const unreadCount = notifications.filter((n) => !n.is_read).length;

  const getIcon = (type: string) => {
    switch (type) {
      case "loyalty_earned":
        return <Sparkles className="w-5 h-5 text-amber-500" />;
      case "order_placed":
        return <ShoppingBag className="w-5 h-5 text-orange-500" />;
      case "order_status":
        return <Truck className="w-5 h-5 text-sky-500" />;
      case "product_featured":
        return <Flame className="w-5 h-5 text-purple-500" />;
      default:
        return <Bell className="w-5 h-5 text-neutral-500" />;
    }
  };

  const handleNotificationClick = (n: InAppNotification) => {
    if (!n.is_read) {
      markNotificationRead(n.id);
    }
    onOpenChange(false);
    if (n.link) {
      navigate({ to: n.link as any });
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40 backdrop-blur-xs animate-in fade-in duration-200">
      <div 
        className="fixed inset-0" 
        onClick={() => onOpenChange(false)} 
      />
      
      <div className="relative w-full max-w-md bg-white h-full shadow-2xl flex flex-col z-10 animate-in slide-in-from-right duration-200 border-l">
        {/* Header */}
        <div className="p-4 border-b flex items-center justify-between bg-neutral-900 text-white">
          <div className="flex items-center gap-2">
            <div className="relative">
              <Bell className="w-5 h-5 text-orange-400" />
              {unreadCount > 0 && (
                <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-orange-500 rounded-full animate-ping" />
              )}
            </div>
            <h2 className="font-bold text-lg">In-App Notifications</h2>
            {unreadCount > 0 && (
              <span className="bg-orange-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                {unreadCount} new
              </span>
            )}
          </div>
          <button 
            onClick={() => onOpenChange(false)}
            className="text-neutral-400 hover:text-white p-1 rounded-lg hover:bg-neutral-800 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Toolbar */}
        <div className="px-4 py-2 bg-neutral-50 border-b flex items-center justify-between text-xs text-neutral-500">
          <span>{notifications.length} total notifications</span>
          {unreadCount > 0 && (
            <button
              onClick={() => user?.email && markAllNotificationsRead(user.email)}
              className="text-orange-600 font-semibold hover:underline flex items-center gap-1"
            >
              <CheckCheck className="w-3.5 h-3.5" /> Mark all as read
            </button>
          )}
        </div>

        {/* Notifications List */}
        <div className="flex-1 overflow-y-auto divide-y divide-neutral-100">
          {notifications.length === 0 ? (
            <div className="p-12 text-center text-neutral-400 space-y-3">
              <Bell className="w-12 h-12 mx-auto text-neutral-300 stroke-1" />
              <p className="font-medium text-sm text-neutral-600">No notifications yet</p>
              <p className="text-xs text-neutral-400">Buying, selling, and loyalty coin updates will appear here in real-time.</p>
            </div>
          ) : (
            notifications.map((n) => (
              <div
                key={n.id}
                onClick={() => handleNotificationClick(n)}
                className={`p-4 transition cursor-pointer hover:bg-orange-50/60 flex items-start gap-3 relative ${
                  !n.is_read ? "bg-amber-50/40 border-l-4 border-l-orange-500" : ""
                }`}
              >
                <div className="p-2.5 rounded-xl bg-white border shadow-xs shrink-0 mt-0.5">
                  {getIcon(n.type)}
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2 mb-1">
                    <h3 className={`text-xs font-bold text-neutral-900 truncate ${!n.is_read ? "text-orange-950 font-extrabold" : ""}`}>
                      {n.title}
                    </h3>
                    <span className="text-[10px] text-neutral-400 shrink-0 flex items-center gap-1">
                      <Clock className="w-3 h-3 text-neutral-400" />
                      {formatDistanceToNow(n.createdAt * 1000, { addSuffix: true })}
                    </span>
                  </div>

                  <p className="text-xs text-neutral-600 leading-relaxed line-clamp-2">
                    {n.message}
                  </p>

                  {n.link && (
                    <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-orange-600 mt-2 hover:underline">
                      View details →
                    </span>
                  )}
                </div>

                {!n.is_read && (
                  <span className="w-2 h-2 rounded-full bg-orange-500 shrink-0 mt-2" title="Unread" />
                )}
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        <div className="p-3 bg-neutral-50 border-t text-center text-xs text-neutral-400">
          SulejaMarket Live Notifications System
        </div>
      </div>
    </div>
  );
}
