"use client"
import React, { useEffect, useState } from 'react';
import { Card, CardContent } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import DashboardLayout from '@/app/dashboard/layout';
import { Skeleton } from '@/components/ui/skeleton';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import PaginationCompo from '@/components/common/pagination';
import DeleteDialog from '@/components/ui/deleteModal';
import {
  Bell,
  Check,
  CheckSquare,
  Trash2,
  Inbox,
  ShoppingBag,
  Clock,
  AlertCircle
} from 'lucide-react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const NotificationListing = () => {
    const { Toast } = useGlobalContext();
    const params = useParams();
    const router = useRouter();
    const searchParams = useSearchParams();
    const [loading, setLoading] = useState(false);
    const [notificationsData, setNotificationsData] = useState<any>({
        unread: { total: 0, pageNumber: "1", count: "10", data: [] },
        read: { total: 0, pageNumber: "1", count: "10", data: [] }
    });
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [deleteType, setDeleteType] = useState<'single' | 'all'>('all');
    const [deletingId, setDeletingId] = useState<string | null>(null);
    const [isDeleting, setIsDeleting] = useState(false);

    const activeTab = searchParams.get('tab') === 'read' ? 'read' : 'unread';
    const pageNum = Number(params?.pagination) || 1;

    const getNotificationListing = async (showSilent = false) => {
        try {
            if (!showSilent) {
                setLoading(true);
            }
            const query = `pageNumber=${pageNum}&count=10`;
            const apiRes = await apis.NotificationVendor.listing(query);
            if (apiRes) {
                setNotificationsData(apiRes);
            }
        } catch (error) {
            console.error("Error fetching notifications:", error);
            Toast.error(error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        getNotificationListing();
    }, [pageNum]);

    const handleSingleRead = async (id: string) => {
        try {
            await apis.NotificationVendor.singleRead(id);
            Toast.success("Notification marked as read");
            getNotificationListing(true);
        } catch (error) {
            Toast.error(error);
        }
    };

    const handleSingleDelete = (id: string) => {
        setDeletingId(id);
        setDeleteType('single');
        setShowDeleteModal(true);
    };

    const handleAllRead = async () => {
        try {
            setLoading(true);
            await apis.NotificationVendor.allRead();
            Toast.success("All notifications marked as read");
            getNotificationListing();
        } catch (error) {
            Toast.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleDeleteAll = () => {
        setDeleteType('all');
        setShowDeleteModal(true);
    };

    const confirmDelete = async () => {
        setIsDeleting(true);
        try {
            if (deleteType === 'all') {
                await apis.NotificationVendor.deleteAll();
                Toast.success("All notifications deleted");
            } else if (deleteType === 'single' && deletingId) {
                await apis.NotificationVendor.deleteSingle(deletingId);
                Toast.success("Notification deleted successfully");
            }
            await getNotificationListing(deleteType === 'single');
        } catch (error) {
            Toast.error(error);
        } finally {
            setIsDeleting(false);
            setShowDeleteModal(false);
            setDeletingId(null);
        }
    };

    const handleTabChange = (tab: 'unread' | 'read') => {
        const query = new URLSearchParams(searchParams?.toString());
        query.set("tab", tab);
        router.push(`/notifications/page/1?${query.toString()}`);
    };

    const handlePageChange = (page: number) => {
        const query = new URLSearchParams(searchParams?.toString());
        query.set("tab", activeTab);
        router.push(`/notifications/page/${page}?${query.toString()}`);
    };

    const handleNotificationClick = (item: any) => {
        const redirectPath =
            item?.data?.redirectPath ||
            item?.redirectPath ||
            item?.data?.redirect_path;

        if (!item?.isRead && item?._id) {
            handleSingleRead(item._id);
        }

        if (!redirectPath || typeof redirectPath !== 'string') {
            return;
        }

        let targetPath = redirectPath.trim();
        if (targetPath.startsWith('orderDetail')) {
            const queryString = targetPath.includes('?') ? targetPath.substring(targetPath.indexOf('?')) : '';
            const params = new URLSearchParams(queryString);
            const orderId = params.get('id') || params.get('order_id') || item?.data?.order_id;
            if (orderId) {
                targetPath = `/orders/ongoing?id=${orderId}`;
            } else {
                targetPath = `/orders/ongoing`;
            }
        } else if (!targetPath.startsWith('/')) {
            targetPath = `/${targetPath}`;
        }

        router.push(targetPath);
    };

    const activeList = activeTab === 'unread' 
        ? (notificationsData?.unread?.data || []) 
        : (notificationsData?.read?.data || []);

    const activeTotal = activeTab === 'unread' 
        ? Number(notificationsData?.unread?.total || 0) 
        : Number(notificationsData?.read?.total || 0);

    const unreadCount = Number(notificationsData?.unread?.total || 0);
    const readCount = Number(notificationsData?.read?.total || 0);

    const getNotificationIcon = (type?: string) => {
        switch (type) {
            case 'delivery_order':
            case 'takeaway_order':
                return <ShoppingBag className="h-5 w-5 text-white" />;
            default:
                return <Bell className="h-5 w-5 text-white" />;
        }
    };

    return (
        <div className="h-[calc(100vh-64px)] overflow-y-auto bg-[#F8F9FC]">
            <div className="mx-auto max-w-5xl px-4 py-8 md:px-8">
                {/* Header Section */}
                <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h1 className="text-3xl font-extrabold tracking-tight text-gray-900">Notifications</h1>
                        <p className="mt-1.5 text-sm text-gray-500">Manage and view your store alerts and orders</p>
                    </div>

                    <div className="flex flex-wrap gap-3">
                        {unreadCount > 0 && (
                            <Button 
                                variant="outline" 
                                size="sm" 
                                onClick={handleAllRead}
                                className="flex items-center gap-2 border-orange-200 bg-white text-orange-600 hover:bg-orange-50 hover:text-orange-700 transition-colors shadow-sm"
                            >
                                <CheckSquare className="h-4 w-4" />
                                <span>Mark All Read</span>
                            </Button>
                        )}
                        {(unreadCount > 0 || readCount > 0) && (
                            <Button 
                                variant="outline" 
                                size="sm" 
                                onClick={handleDeleteAll}
                                className="flex items-center gap-2 border-red-100 bg-white text-red-600 hover:bg-red-50 hover:text-red-700 transition-colors shadow-sm"
                            >
                                <Trash2 className="h-4 w-4" />
                                <span>Clear All</span>
                            </Button>
                        )}
                    </div>
                </div>

                {/* Navigation Tabs */}
                <div className="mb-6 flex border-b border-gray-200 bg-white p-1 rounded-xl shadow-sm max-w-sm">
                    <button
                        onClick={() => handleTabChange('unread')}
                        className={`flex-1 flex items-center justify-center gap-2 rounded-lg py-2.5 text-sm font-semibold transition-all ${
                            activeTab === 'unread'
                                ? 'bg-[var(--primary-brand)] text-white shadow-sm'
                                : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                        }`}
                    >
                        <span>Unread</span>
                        <Badge 
                            variant="secondary" 
                            className={`rounded-full px-2 py-0.5 text-xs font-bold ${
                                activeTab === 'unread'
                                    ? 'bg-white/20 text-white'
                                    : 'bg-orange-50 text-orange-600'
                            }`}
                        >
                            {unreadCount}
                        </Badge>
                    </button>
                    <button
                        onClick={() => handleTabChange('read')}
                        className={`flex-1 flex items-center justify-center gap-2 rounded-lg py-2.5 text-sm font-semibold transition-all ${
                            activeTab === 'read'
                                ? 'bg-[var(--primary-brand)] text-white shadow-sm'
                                : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                        }`}
                    >
                        <span>Read</span>
                        <Badge 
                            variant="secondary" 
                            className={`rounded-full px-2 py-0.5 text-xs font-bold ${
                                activeTab === 'read'
                                    ? 'bg-white/20 text-white'
                                    : 'bg-gray-100 text-gray-600'
                            }`}
                        >
                            {readCount}
                        </Badge>
                    </button>
                </div>

                {/* Notifications List */}
                <Card className="border-none bg-white shadow-[0px_4px_25px_0px_rgba(0,0,0,0.03)] rounded-2xl overflow-hidden">
                    <CardContent className="p-0">
                        {loading ? (
                            <div className="divide-y divide-gray-100">
                                {[...Array(5)].map((_, i) => (
                                    <div key={i} className="flex items-start gap-4 p-5">
                                        <Skeleton className="h-10 w-10 rounded-full shrink-0" />
                                        <div className="flex-1 space-y-2">
                                            <Skeleton className="h-5 w-1/3" />
                                            <Skeleton className="h-4 w-3/4" />
                                            <Skeleton className="h-3.5 w-20" />
                                        </div>
                                        <Skeleton className="h-8 w-16 rounded" />
                                    </div>
                                ))}
                            </div>
                        ) : activeList.length > 0 ? (
                            <div className="divide-y divide-gray-100">
                                {activeList.map((item: any) => {
                                    const notifType = item?.data?.type;
                                    const redirectPath =
                                        item?.data?.redirectPath ||
                                        item?.redirectPath ||
                                        item?.data?.redirect_path;
                                    const hasRedirect = Boolean(redirectPath && typeof redirectPath === 'string' && redirectPath.trim());

                                    return (
                                        <div
                                            key={item._id}
                                            onClick={() => {
                                                if (hasRedirect) {
                                                    handleNotificationClick(item);
                                                }
                                            }}
                                            className={`group relative flex flex-col md:flex-row md:items-center justify-between gap-4 p-5 transition-all duration-300 hover:bg-slate-50/50 ${
                                                !item.isRead ? 'border-l-4 border-[var(--primary-brand)]' : ''
                                            } ${hasRedirect ? 'cursor-pointer' : ''}`}
                                        >
                                            <div className="flex items-start gap-4 flex-1">
                                                <Avatar className="h-10 w-10 shrink-0 border border-gray-100 bg-slate-50 flex items-center justify-center">
                                                    <AvatarFallback className="bg-transparent">
                                                        {getNotificationIcon(notifType)}
                                                    </AvatarFallback>
                                                </Avatar>
                                                <div className="flex-1 min-w-0">
                                                    <div className="flex items-center gap-2 flex-wrap">
                                                        <h4 className="text-base font-bold text-gray-900">
                                                            {item?.notification?.title || "System Notification"}
                                                        </h4>
                                                        {!item.isRead && (
                                                            <span className="inline-flex h-2 w-2 rounded-full bg-[var(--primary-brand)]" />
                                                        )}
                                                    </div>
                                                    <p className="mt-1 text-sm text-gray-600 leading-relaxed font-medium">
                                                        {item?.notification?.body || ""}
                                                    </p>
                                                    <div className="mt-2.5 flex items-center gap-1.5 text-xs text-gray-400 font-semibold">
                                                        <Clock className="h-3.5 w-3.5" />
                                                        <span>{dayjs(item.createdAt).fromNow()}</span>
                                                    </div>
                                                </div>
                                            </div>

                                            {/* Action Buttons for Card */}
                                            <div className="flex items-center gap-2 self-end md:self-center shrink-0">
                                                {!item.isRead && (
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            handleSingleRead(item._id);
                                                        }}
                                                        className="h-9 w-9 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                                                        title="Mark as read"
                                                    >
                                                        <Check className="h-4 w-4 stroke-[3px]" />
                                                    </Button>
                                                )}
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleSingleDelete(item._id);
                                                    }}
                                                    className="h-9 w-9 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                                    title="Delete notification"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        ) : (
                            <div className="flex flex-col items-center justify-center py-20 px-4 text-center">
                                <div className="flex items-center justify-center w-16 h-16 bg-slate-50 rounded-2xl mb-4 border border-gray-100">
                                    <Inbox className="h-8 w-8 text-gray-400" />
                                </div>
                                <h3 className="text-lg font-bold text-gray-900">All caught up!</h3>
                                <p className="mt-1 text-sm text-gray-500 max-w-sm font-medium">
                                    {activeTab === 'unread' 
                                        ? "You don't have any unread notifications right now."
                                        : "You don't have any read notifications in your history."}
                                </p>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* Pagination Controls */}
                {!loading && activeTotal > 0 && (
                    <div className="mt-6 flex justify-center">
                        <PaginationCompo 
                            totalDataCount={activeTotal} 
                            currentPage={pageNum} 
                            itemsPerPage={10} 
                            onPageChange={handlePageChange} 
                        />
                    </div>
                )}

                <DeleteDialog
                    isOpen={showDeleteModal}
                    onClose={() => setShowDeleteModal(false)}
                    handleDelete={confirmDelete}
                    loading={isDeleting}
                    title={deleteType === 'all' ? 'Delete All Notifications' : 'Delete Notification'}
                    description={
                        deleteType === 'all'
                            ? 'Are you sure you want to delete all notifications? This action cannot be undone.'
                            : 'Are you sure you want to delete this notification? This action cannot be undone.'
                    }
                    actionButtonText={deleteType === 'all' ? 'Yes, Clear All' : 'Yes, Delete'}
                />
            </div>
        </div>
    );
};

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