"use client";

import { X, ChevronRight, Briefcase, FileText, Bookmark, Eye, Mail } from "lucide-react";
import Image from "next/image";
import { useState, useEffect } from "react";
import { notificationService, Notification } from "@/services/notification.service";
import { useAuthStore } from "@/store/auth.store";
import { formatDistanceToNow } from "date-fns";

interface NotificationSidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

export function NotificationSidebar({ isOpen, onClose }: NotificationSidebarProps) {
  const [filter, setFilter] = useState<"All" | "Unread">("All");
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  const user = useAuthStore((state) => state.user);

  useEffect(() => {
    if (isOpen && user?.id) {
      fetchNotifications();
    }
  }, [isOpen, user?.id]);

  const fetchNotifications = async () => {
    if (!user?.id) return;
    try {
      setLoading(true);
      const res = await notificationService.getNotifications(user.id);
      setNotifications(res.notifications || []);
    } catch (error) {
      console.error("Failed to fetch notifications:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleNotificationClick = async (notif: Notification) => {
    if (notif.isRead === 0 && user?.id) {
      try {
        await notificationService.markAsRead(notif.id, user.id);
        // Optimistically update UI
        setNotifications((prev) => 
          prev.map((n) => n.id === notif.id ? { ...n, isRead: 1 } : n)
        );
      } catch (error) {
        console.error("Failed to mark as read:", error);
      }
    }
  };

  const getIconForType = (type: string) => {
    switch (type.toLowerCase()) {
      case "job": return Briefcase;
      case "application": return FileText;
      case "saved": return Bookmark;
      case "view": return Eye;
      case "welcome": return Mail;
      default: return Mail;
    }
  };

  const filteredNotifications = notifications.filter(
    (n) => filter === "All" || (filter === "Unread" && n.isRead === 0)
  );

  return (
    <>
      {/* Backdrop */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/20 z-40 transition-opacity"
          onClick={onClose}
        />
      )}

      {/* Sidebar */}
      <div
        className={`fixed top-0 right-0 h-screen w-full sm:w-[50vw] max-w-[500px] bg-[#fdfdfd] z-50 transform transition-transform duration-300 ease-in-out shadow-2xl flex flex-col ${isOpen ? "translate-x-0" : "translate-x-full"
          }`}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 bg-white">
          <h2 className="text-xl font-bold text-gray-900">Notification</h2>

          <div className="flex items-center gap-6">
            <div className="flex bg-[#f5f5f5] rounded-full p-1">
              <button
                onClick={() => setFilter("All")}
                className={`px-4 py-1.5 text-xs font-semibold rounded-full transition-colors ${filter === "All" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"}`}
              >
                All
              </button>
              <button
                onClick={() => setFilter("Unread")}
                className={`px-4 py-1.5 text-xs font-semibold rounded-full transition-colors ${filter === "Unread" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"}`}
              >
                Unread
              </button>
            </div>

            <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600 transition-colors">
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 bg-[#fdfdfd]">
          {loading ? (
            <div className="flex justify-center items-center h-full">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#ff6b00]"></div>
            </div>
          ) : filteredNotifications.length > 0 ? (
            <div className="flex flex-col gap-4">
              {filteredNotifications.map((notif) => {
                const Icon = getIconForType(notif.type);
                return (
                  <div 
                    key={notif.id} 
                    onClick={() => handleNotificationClick(notif)}
                    className="bg-white rounded-xl p-5 border border-gray-100 shadow-[0_2px_10px_rgba(0,0,0,0.02)] flex items-start gap-4 hover:border-gray-200 transition-colors cursor-pointer group"
                  >
                    {/* Unread indicator */}
                    <div className="flex-shrink-0 mt-3">
                      <div className={`w-2 h-2 rounded-full ${notif.isRead === 0 ? 'bg-[#ff6b00]' : 'bg-gray-300'}`}></div>
                    </div>

                    {/* Icon */}
                    <div className="flex-shrink-0 mt-1 text-gray-400 group-hover:text-gray-600 transition-colors">
                      <Icon className="w-6 h-6 stroke-[1.5]" />
                    </div>

                    {/* Text content */}
                    <div className="flex-1 min-w-0 pr-4">
                      <p className="text-[13px] font-medium text-gray-800 leading-relaxed mb-2">{notif.message}</p>
                      <span className={`text-[10px] font-bold ${notif.isRead === 0 ? 'text-[#ff6b00]' : 'text-gray-400'}`}>
                        {formatDistanceToNow(new Date(notif.createdAt), { addSuffix: true })}
                      </span>
                    </div>

                    {/* Arrow */}
                    <div className="flex-shrink-0 self-center text-gray-300 group-hover:text-gray-500 transition-colors">
                      <ChevronRight className="w-5 h-5" />
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-center mt-[-40px]">
              <div className="relative w-36 h-36 sm:w-40 sm:h-40 mb-6">
                <Image
                  src="/images/notification.png"
                  alt="No notifications"
                  fill
                  className="object-contain"
                  unoptimized
                  onError={(e) => {
                    e.currentTarget.style.display = 'none';
                  }}
                />
              </div>
              <h3 className="text-lg font-bold text-[#ff6b00] mb-2">No notification to show</h3>
              <p className="text-xs text-gray-500 max-w-[280px] leading-relaxed">
                You currently have no notifications. We will notify you when something new happens!
              </p>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
