"use client";

import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Bell, Check, CheckCircle2, MessageSquare, Briefcase, Info, X } from "lucide-react";
import Link from "next/link";
import { formatDistanceToNow } from "date-fns";

export function NotificationCenter() {
    const [isOpen, setIsOpen] = useState(false);
    const [notifications, setNotifications] = useState<any[]>([]);
    const [unreadCount, setUnreadCount] = useState(0);
    const [isLoading, setIsLoading] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    const fetchNotifications = async () => {
        setIsLoading(true);
        try {
            const res = await fetch('/api/notifications?limit=10');
            if (res.ok) {
                const data = await res.json();
                setNotifications(data.notifications);
                setUnreadCount(data.meta.unread_count);
            }
        } catch (error) {
            console.error("Failed to fetch notifications", error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        // Initial fetch
        fetchNotifications();

        // Polling every 60 seconds
        const interval = setInterval(fetchNotifications, 60000);
        return () => clearInterval(interval);
    }, []);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };

        if (isOpen) {
            document.addEventListener("mousedown", handleClickOutside);
        }
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, [isOpen]);

    const markAsRead = async (id: string) => {
        try {
            const res = await fetch(`/api/notifications/${id}/read`, { method: 'PUT' });
            if (res.ok) {
                if (id === 'all') {
                    setNotifications(prev => prev.map(n => ({ ...n, is_read: true })));
                    setUnreadCount(0);
                } else {
                    setNotifications(prev => prev.map(n => n.id === id ? { ...n, is_read: true } : n));
                    setUnreadCount(prev => Math.max(0, prev - 1));
                }
            }
        } catch (error) {
            console.error("Failed to mark as read", error);
        }
    };

    const toggleDropdown = () => {
        if (!isOpen) {
            fetchNotifications(); // Refresh on open
        }
        setIsOpen(!isOpen);
    };

    const getIcon = (type: string) => {
        switch (type) {
            case 'application': return <Briefcase className="h-5 w-5 text-blue-500" />;
            case 'message': return <MessageSquare className="h-5 w-5 text-green-500" />;
            case 'system': return <Info className="h-5 w-5 text-slate-500" />;
            case 'job_alert': return <Bell className="h-5 w-5 text-orange-500" />;
            default: return <Bell className="h-5 w-5 text-slate-500" />;
        }
    };

    return (
        <div className="relative" ref={dropdownRef}>
            <button
                onClick={toggleDropdown}
                className="relative p-2 rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-700 transition-colors focus:outline-none focus:ring-2 focus:ring-primary/20"
                aria-label="Notifications"
                aria-expanded={isOpen}
            >
                <Bell className="h-5 w-5" />
                {unreadCount > 0 && (
                    <span className="absolute right-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white ring-2 ring-white">
                        {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                )}
            </button>

            <AnimatePresence>
                {isOpen && (
                    <motion.div
                        initial={{ opacity: 0, scale: 0.95, y: 10 }}
                        animate={{ opacity: 1, scale: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.95, y: 10 }}
                        transition={{ duration: 0.15, ease: "easeOut" }}
                        className="absolute right-0 mt-2 w-80 sm:w-96 rounded-xl bg-white shadow-lg border border-slate-100 overflow-hidden z-50 origin-top-right"
                    >
                        {/* Header */}
                        <div className="flex items-center justify-between p-4 border-b border-slate-100">
                            <h3 className="font-semibold text-slate-800">Notifications</h3>
                            {unreadCount > 0 && (
                                <button
                                    onClick={() => markAsRead('all')}
                                    className="text-xs font-medium text-primary hover:text-primary/80 transition-colors flex items-center gap-1"
                                >
                                    <Check className="h-3 w-3" />
                                    Mark all read
                                </button>
                            )}
                        </div>

                        {/* Notifications List */}
                        <div className="max-h-[60vh] overflow-y-auto overscroll-contain">
                            {isLoading && notifications.length === 0 ? (
                                <div className="p-8 text-center text-slate-400">
                                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
                                    <p className="text-sm">Loading notifications...</p>
                                </div>
                            ) : notifications.length === 0 ? (
                                <div className="p-8 text-center text-slate-400 flex flex-col items-center">
                                    <Bell className="h-10 w-10 text-slate-200 mb-2" />
                                    <p className="text-sm">You have no notifications right now.</p>
                                </div>
                            ) : (
                                <div className="divide-y divide-slate-50">
                                    {notifications.map((notification) => (
                                        <div
                                            key={notification.id}
                                            className={`relative flex items-start gap-4 p-4 hover:bg-slate-50 transition-colors group ${!notification.is_read ? 'bg-primary/5' : ''}`}
                                        >
                                            <div className="relative flex-shrink-0 mt-1">
                                                {getIcon(notification.type)}
                                                {!notification.is_read && (
                                                    <span className="absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-red-500 border-2 border-white"></span>
                                                )}
                                            </div>

                                            <div className="flex-1 min-w-0">
                                                <p className={`text-sm tracking-tight ${!notification.is_read ? 'font-semibold text-slate-900' : 'font-medium text-slate-700'}`}>
                                                    {notification.title}
                                                </p>
                                                <p className="text-sm text-slate-500 mt-0.5 line-clamp-2 leading-snug">
                                                    {notification.message}
                                                </p>
                                                <p className="text-xs text-slate-400 mt-2 font-medium">
                                                    {formatDistanceToNow(new Date(notification.created_at), { addSuffix: true })}
                                                </p>

                                                {notification.link && (
                                                    <Link
                                                        href={notification.link}
                                                        className="inline-block mt-2 text-xs font-medium text-primary hover:underline"
                                                    >
                                                        View details
                                                    </Link>
                                                )}
                                            </div>

                                            {!notification.is_read && (
                                                <button
                                                    onClick={(e) => { e.preventDefault(); markAsRead(notification.id); }}
                                                    className="opacity-0 group-hover:opacity-100 transition-opacity p-1.5 text-slate-400 hover:text-primary hover:bg-primary/10 rounded-full focus:opacity-100"
                                                    title="Mark as read"
                                                >
                                                    <CheckCircle2 className="h-4 w-4" />
                                                </button>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* Footer */}
                        <div className="p-3 border-t border-slate-100 text-center bg-slate-50">
                            <Link
                                href="/dashboard/settings"
                                className="text-xs font-medium text-slate-500 hover:text-primary transition-colors inline-flex items-center gap-1"
                                onClick={() => setIsOpen(false)}
                            >
                                Notification Settings
                            </Link>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
}
