"use client";

import { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { getNotifications, markNotificationRead, markAllNotificationsRead, NotificationItem as NotifData } from "@/services/userPanelService";
import NotificationItem from "@/components/notifications/NotificationItem";
import NotificationsEmpty from "@/components/empty-states/NotificationsEmpty";
import { Button } from "@/components/ui/button";
import { FiCheckCircle } from "react-icons/fi";

const NotificationsPage = () => {
    const { token, user, updateUser, refreshUser } = useAuth();
    const [notifications, setNotifications] = useState<NotifData[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (!token) { setLoading(false); return; }
        getNotifications(token).then((data) => {
            setNotifications(data);
            setLoading(false);
        });
    }, [token]);

    const handleMarkRead = async (id: number) => {
        if (!token) return;

        // Optimistic Update
        const currentCount = user?.notifications_count || 0;
        if (currentCount > 0) {
            updateUser({ notifications_count: currentCount - 1 });
        }

        const ok = await markNotificationRead(token, id);
        if (ok) {
            setNotifications((prev) =>
                prev.map((n) => (n.id === id ? { ...n, read: true } : n))
            );
            // Verify with server
            refreshUser();
        } else {
            // Rollback on failure if needed (optional for simple counts)
            refreshUser();
        }
    };

    const handleMarkAllRead = async () => {
        if (!token) return;

        // Optimistic Update
        updateUser({ notifications_count: 0 });

        const ok = await markAllNotificationsRead(token);
        if (ok) {
            setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
            // Verify with server
            refreshUser();
        } else {
            // Rollback
            refreshUser();
        }
    };

    if (loading) {
        return (
            <div className="flex-1 flex flex-col">
                <h4 className="mb-2 text-[#1D293D] text-lg font-medium">الإشعارات</h4>
                <div className="flex-1 flex items-center justify-center">
                    <div className="w-8 h-8 border-2 border-[#0092B8] border-t-transparent rounded-full animate-spin" />
                </div>
            </div>
        );
    }

    return (
        <div className="flex-1 flex flex-col">
            <div className="flex items-center justify-between mb-2">
                <h4 className="text-[#1D293D] text-lg font-medium">الإشعارات</h4>
                {notifications.length > 0 && (
                    <Button
                        variant="ghost"
                        className="text-sm text-[#0092B8] hover:text-[#007a9d]"
                        onClick={handleMarkAllRead}
                    >
                        <FiCheckCircle className="ml-1" />
                        تعليم الكل كمقروء
                    </Button>
                )}
            </div>
            {notifications.length > 0 ? (
                <div className="flex-1 overflow-auto flex flex-col gap-2 md:px-20">
                    {notifications.map((notification) => (
                        <div
                            key={notification.id}
                            onClick={() => !notification.read && handleMarkRead(notification.id)}
                            className="cursor-pointer transition-opacity"
                        >
                            <NotificationItem
                                title={notification.title}
                                description={notification.message}
                            />
                        </div>
                    ))}
                </div>
            ) : (
                <NotificationsEmpty />
            )}
        </div>
    );
};

export default NotificationsPage;