'use client';
import React, { useEffect, useState } from "react";
import Image from "next/image";

import DashboardLayout from "@/components/layout/DashboardLayout";
import { Modal } from "@/components/ui/modal";
import { Button } from "@/components/ui/button";
import {
    Pagination,
    PaginationContent,
    PaginationLink,
    PaginationItem,
    PaginationPrevious,
    PaginationNext,
    PaginationEllipsis,
} from "@/components/ui/pagination";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { useRouter } from "next/navigation";
import { useGlobalContext } from "@/context/Provider";
import { getValidImage } from "@/lib/utils";

interface NotificationListProps {
    title: string;
    items: NotificationItem[];
    onMarkAllRead?: () => void;
    onClearAll?: () => void;
    onDelete?: (notification: NotificationItem) => void;
}

interface ApiNotification {
    _id: string;
    notification: {
        title: string;
        body: string;
    };
    data: {
        type: string;
        redirectPath: string;
        cart_id?: string;
    };
    resturantId: {
        image: string;
    }
    userId: {
        image: string;
    };
    isRead: boolean;
    createdAt: string;
}

interface NotificationResponse {
    unread: {
        total: number;
        pageNumber: string;
        count: string;
        data: ApiNotification[];
    };
    read: {
        total: number;
        pageNumber: string;
        count: string;
        data: ApiNotification[];
    };
}

interface NotificationItem {
    id: string;
    name: string;
    avatar: string;
    message: string;
    time: string;
    redirectPath: string;
    cart_id?: string;
}


const NotificationList: React.FC<NotificationListProps> = ({
    title,
    items,
    onMarkAllRead,
    onClearAll,
    onDelete,
}) => {
    const router = useRouter();
    const { Toast } = useGlobalContext();
    const handleNotificationClick = async (item: NotificationItem) => {
        try {
            if (title === "Unread notification") {
                await apis.notificationList.markSingleRead(item.id);
            }
            // If notification has a cart_id, fetch vendor-added items and redirect to grocery page with cart pre-filled
            if (item.cart_id) {
                try {
                    const response = await apis.Grocery.getItemsForCustomer(item.cart_id);
                    if (response?.data) {
                        const cartData = response.data;
                        const restaurantId = cartData.restaurant_id?._id;
                        const otherCartItems = cartData.other_cart_items || [];

                        if (restaurantId && otherCartItems.length > 0) {
                            // Convert vendor-added items to cart format
                            const cartItems = otherCartItems.map((cartItem: any) => ({
                                id: cartItem.item_id,
                                name: cartItem.name,
                                weight: `${cartItem.quantity || ''} ${cartItem.unit || ''}`.trim(),
                                price: `$${cartItem.price}.00`,
                                image: getValidImage(cartItem.imageUrl),
                                quantity: cartItem.no_of_quantity || 1,
                                restaurantId: restaurantId,
                            }));

                            // Save cart items to localStorage for the grocery page to pick up
                            localStorage.setItem('groceryCartItems', JSON.stringify(cartItems));
                            // Set flag to auto-open cart sidebar
                            localStorage.setItem('vendorCartNotification', 'true');
                            // Store restaurant delivery info if available
                            if (cartData.restaurant_id) {
                                localStorage.setItem('restaurant_delivery_info', JSON.stringify(cartData.restaurant_id));
                            }

                            if (window.location.pathname === `/grocery/${restaurantId}`) {
                                window.dispatchEvent(new CustomEvent('vendor-cart-updated'));
                            } else {
                                router.push(`/grocery/${restaurantId}?type=grocery`);
                            }
                            return;
                        }
                    }
                } catch (cartError) {
                    console.error('Error fetching vendor cart items:', cartError);
                }
            }
            if (item?.redirectPath) {
                router.push(item.redirectPath);
            }
        } catch (error) {
            Toast.error(error);
            if (item?.redirectPath) {
                router.push(item.redirectPath);
            }
        }
    };


    return (
        <div className="mb-8">
            <div className="flex justify-between items-center mb-4">
                <h3 className="text-sm font-semibold text-gray-600">{title}</h3>
                {title === "Unread notification" && items.length > 0 && (
                    <div className="flex gap-4">
                        <button
                            className="text-xs text-primary font-medium hover:underline"
                            onClick={onMarkAllRead}
                        >
                            Mark all read
                        </button>
                        <button
                            className="text-xs text-red-500 font-medium hover:underline"
                            onClick={onClearAll}
                        >
                            Clear all
                        </button>
                    </div>
                )}
            </div>
            <div className="space-y-3">
                {items.length === 0 ? (
                    <p className="text-sm text-gray-500 text-center">No {title.toLowerCase()} available</p>
                ) : (
                    items.map((item: any) => (
                        <div
                            key={item.id}
                            className={`flex items-start justify-between p-3 rounded-lg ${title === "Previous notification" ? "bg-yellow-100" : "bg-white"
                                } shadow-sm cursor-pointer`}
                            onClick={() => handleNotificationClick(item)}
                        >
                            <div className="flex items-start gap-3">
                                {/* {item.avatar ? (
                                <div className="flex-shrink-0 w-12 h-12 rounded-full bg-white border border-gray-200 shadow-sm flex items-center justify-center">
                                    <Image
                                        src={item.avatar}
                                        alt={item.name}
                                        width={40}
                                        height={40}
                                        className="w-12 h-12 rounded-full object-cover"
                                    />
                                </div>
                                ) : null} */}
                                <div>
                                    <p className="text-sm font-medium text-gray-800">{item.message}</p>
                                    <p className="text-xs text-gray-500">{item.time}</p>
                                </div>
                            </div>
                            <div className="flex items-center">
                                {title === "Previous notification" ? (
                                    <button
                                        className="text-gray-500 hover:text-gray-700"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            onDelete?.(item);
                                        }}
                                    >
                                        ✕
                                    </button>
                                ) : (
                                    <span className="w-2 h-2 bg-brand-500 rounded-full"></span>
                                )}

                            </div>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
};

const Notification: React.FC = () => {
    const [unread, setUnread] = useState<NotificationItem[]>([]);
    const [previous, setPrevious] = useState<NotificationItem[]>([]);
    const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
    const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
    const [notificationToDelete, setNotificationToDelete] = useState<NotificationItem | null>(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const { Toast } = useGlobalContext();

    const limit = 5;

    const fetchNotifications = async (page: number) => {
        try {
            const response = await apis.notificationList.listing(`pageNumber=${page}&count=${limit}`);
            const data: NotificationResponse = response;

            const unreadNotifications: NotificationItem[] = data?.unread?.data?.map((item) => ({
                id: item._id,
                name: "",
                avatar: `${BUCKET_ROOT + (item.resturantId?.image || "")}`,
                message: item.notification.title,
                time: new Intl.DateTimeFormat('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit',
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric',
                }).format(new Date(item.createdAt)),
                redirectPath: item.data.redirectPath,
                cart_id: item.data.cart_id,
            }));

            const readNotifications: NotificationItem[] = data?.read?.data?.map((item) => ({
                id: item._id,
                name: "",
                avatar: `${BUCKET_ROOT + (item.resturantId?.image || "")}`,
                message: item.notification.title,
                time: new Intl.DateTimeFormat('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit',
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric',
                }).format(new Date(item.createdAt)),
                redirectPath: item.data.redirectPath,
                cart_id: item.data.cart_id,
            }));

            setUnread(unreadNotifications);
            setPrevious(readNotifications);

            const unreadPages = Math.ceil(data.unread.total / Number(data.unread.count));
            const readPages = Math.ceil(data.read.total / Number(data.read.count));
            setTotalPages(Math.max(unreadPages, readPages));

        } catch (error) {
            Toast.error(error);
        }
    };



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

    const handleClearAll = () => {
        setIsConfirmModalOpen(true);
    };

    const confirmClearAll = async () => {
        try {
            await apis.notificationList.deleteAll();
            await fetchNotifications(pageNumber);
        } catch (error) {
            Toast.error(error);
        }
        setIsConfirmModalOpen(false);
    };


    const handleDeleteClick = (notification: NotificationItem) => {
        setNotificationToDelete(notification);
        setIsDeleteConfirmOpen(true);
    };
    const confirmDeleteNotification = async () => {
        if (notificationToDelete) {
            try {
                await apis.notificationList.deleteSingle(notificationToDelete.id);
                await fetchNotifications(pageNumber);
            } catch (error) {
                Toast.error(error);
            }
        }
        setNotificationToDelete(null);
        setIsDeleteConfirmOpen(false);
    };


    const handleMarkAllRead = async () => {
        try {
            await apis.notificationList.markAllRead();
            await fetchNotifications(pageNumber);
        } catch (error) {
            Toast.error(error);
        }
    };

    const getPaginationRange = (currentPage: number, totalPages: number, siblingCount = 1) => {
        const totalPageNumbers = siblingCount * 2 + 5;

        if (totalPages <= totalPageNumbers) {
            return Array.from({ length: totalPages }, (_, i) => i + 1);
        }

        const leftSiblingIndex = Math.max(currentPage - siblingCount, 2);
        const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPages - 1);

        const shouldShowLeftEllipsis = leftSiblingIndex > 2;
        const shouldShowRightEllipsis = rightSiblingIndex < totalPages - 1;

        const range: (number | '...')[] = [1];

        if (shouldShowLeftEllipsis) {
            range.push('...');
        }

        for (let i = leftSiblingIndex; i <= rightSiblingIndex; i++) {
            range.push(i);
        }

        if (shouldShowRightEllipsis) {
            range.push('...');
        }

        range.push(totalPages);
        return range;
    };

    return (
        <div className="flex flex-col min-h-screen p-6 max-w-7xl mx-auto">
            <h2 className="text-2xl font-semibold mb-6 text-gray-800">
                Notification
            </h2>

            <NotificationList
                title="Unread notification"
                items={unread}
                onMarkAllRead={handleMarkAllRead}
                onClearAll={handleClearAll}
            />

            <NotificationList title="Previous notification" items={previous} onDelete={handleDeleteClick} />

            {(unread.length > 0 || previous.length > 0) && (
                <div className="pagination-container">
                    <Pagination>
                        <PaginationPrevious
                            onClick={() => setPageNumber((prev) => Math.max(prev - 1, 1))}
                            className="pagination-btn"
                        />
                        <PaginationContent>
                            {getPaginationRange(pageNumber, totalPages).map((p, index) => (
                                <PaginationItem key={index}>
                                    {p === '...' ? (
                                        <PaginationEllipsis />
                                    ) : (
                                        <PaginationLink
                                            isActive={pageNumber === p}
                                            onClick={() => setPageNumber(Number(p))}
                                            className={
                                                pageNumber === p
                                                    ? "pagination-link-active"
                                                    : "pagination-link"
                                            }
                                        >
                                            {p}
                                        </PaginationLink>
                                    )}
                                </PaginationItem>
                            ))}
                        </PaginationContent>

                        <PaginationNext
                            onClick={() => setPageNumber((prev) => Math.min(prev + 1, totalPages))}
                            className="pagination-btn"
                        />
                    </Pagination>
                </div>
            )}

            <Modal
                isOpen={isConfirmModalOpen}
                onClose={() => setIsConfirmModalOpen(false)}
                title="Confirm Clear All"
                description="Are you sure you want to clear all unread notifications? This action cannot be undone."
            >
                <div className="flex justify-end gap-4 mt-4">
                    <Button variant="ghost" onClick={() => setIsConfirmModalOpen(false)}>
                        Cancel
                    </Button>
                    <Button
                        className="bg-red-500 text-white hover:bg-red-600"
                        onClick={confirmClearAll}
                    >
                        Clear All
                    </Button>
                </div>
            </Modal>

            <Modal
                isOpen={isDeleteConfirmOpen}
                onClose={() => setIsDeleteConfirmOpen(false)}
                title="Confirm Delete"
                description="Are you sure you want to delete this notification? This action cannot be undone."
            >
                <div className="flex justify-end gap-4 mt-4">
                    <Button variant="ghost" onClick={() => setIsDeleteConfirmOpen(false)}>
                        Cancel
                    </Button>
                    <Button
                        className="bg-red-500 text-white hover:bg-red-600"
                        onClick={confirmDeleteNotification}
                    >
                        Delete
                    </Button>
                </div>
            </Modal>
        </div>
    );
};

export default function NotificationPage() {
    return (
        <DashboardLayout>
            <Notification />
        </DashboardLayout>
    );
}