"use client"
import React, { useEffect, useState } from 'react';
import { Card, CardContent } from "@/components/ui/card";
import { Avatar, AvatarImage } from "@/components/ui/avatar";
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import DashboardLayout from '@/app/dashboard/layout';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Skeleton } from '@/components/ui/skeleton';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import PaginationCompo from '@/components/common/pagination';



const NotificationListing = () => {



    const { Toast } = useGlobalContext()
    const params = useParams();
    const router = useRouter()
    const searchParams = useSearchParams();
    const queryParams = Object.fromEntries(searchParams.entries());
    const [loading, setLoading] = useState(false)
    const [state, setState] = useState<any>({
        readCount: 0,
        readData: [],
        unreadCount: 0,
        unreadData: []
    })



    const getNotificationListing = async (isLoading?: boolean) => {
        try {
            if (!isLoading) {
                setLoading(true)
            }
            const urlSearchParam = new URLSearchParams();
            if (params.pagination) {
                urlSearchParam.set('pagination', `${Number(params.pagination) - 1}`);
            }
            if (queryParams.limit) {
                urlSearchParam.set('limit', queryParams.limit as string);
            }
            const apiRes = await apis.Notification.listing(urlSearchParam?.toString())
            setState(apiRes)
        } catch (error) {
            Toast.error(error)
        } finally {
            setLoading(false)
        }
    }

    // useEffect(() => {
    //     getNotificationListing()
    // }, [])


    // single read notification...........
    const handleSingleRead = async (id: string, isUnread: boolean) => {
        if (!isUnread) return
        try {
            const apiRes = await apis.Notification.singleRead(id)
            getNotificationListing(true)
        } catch (error) {
            Toast.error(error)

        }
    }


    // all read notification...........
    const handleAllRead = async () => {
        try {
            const apiRes = await apis.Notification.allRead()
        } catch (error) {
            Toast.error(error)
        }
    }

    const handlePageChange = (page: number) => {
        const query = new URLSearchParams(searchParams?.toString());
        query.set("limit", "10");
        router.replace(
            `/notifications/page/${page}?${query.toString()}`,
            { scroll: false }
        );
    };

    const NotificationItem = ({ notification, isUnread }: any) => (
        <div className={`flex items-center gap-3 p-3 my-2 rounded-lg  ${isUnread ? 'bg-primary cursor-pointer' : 'bg-slate-50'} transition-colors`} onClick={() => handleSingleRead(notification?._id, isUnread)}>
            {
                notification?.notification_type === "jobRequest" &&
                <Avatar className="h-10 w-10 shrink-0">
                    {/* <AvatarImage src={logo.src} alt={notification.name} className='h-full w-full' /> */}
                </Avatar>
            }
            <div className="flex-1 min-w-0">
                <p className="text-sm font-medium theme-color text-wrap truncate">{notification.message}</p>
                <p className="text-xs text-gray">{notification.date}</p>
            </div>
            {isUnread && (
                <div className="w-2 h-2 rounded-full bg-blue-500 shrink-0" />
            )}
        </div>
    );

    return (
        <ScrollArea className="h-[calc(100dvh-64px)]">
            <div className='p-7 h-full'>
                <div className='mb-4'><p className="text-2xl font-semibold">Notifications</p></div>
                <Card className="w-full  shadow-lg">
                    <CardContent className='p-4'>
                        {
                            loading ?
                                [...Array(8)].map((index) => (
                                    <div key={index} className='my-2'>
                                        <Skeleton className='h-12' />
                                    </div>
                                ))
                                :
                                <>

                                    <div className="space-y-5">
                                        {/* <div className="flex items-center gap-14 justify-between">
                                                <div className='flex items-center gap-2'>
                                                    <h4 className="text-base font-medium theme-color ">Unread notification</h4>
                                                    <div>
                                                        {state?.unreadCount > 0 && (
                                                            <Badge
                                                                variant="outline"
                                                                className="common-bg text-white text-xs h-18 w-18 "
                                                            >
                                                                {state?.unreadCount}
                                                            </Badge>
                                                        )}
                                                    </div>
                                                </div>
                                                <Button
                                                    variant="outline"
                                                    className="text-xm text-gray  p-0 h-auto font-medium border-0 shadow-none"
                                                    onClick={handleAllRead}
                                                >
                                                    Mark all as read
                                                </Button>
                                            </div> */}
                                        <div className="space-y-1">
                                            {Array.isArray(state?.unreadData) && state.unreadData.length > 0 ? (
                                                state.unreadData.map((res: any) => (
                                                    <NotificationItem
                                                        key={res._id}
                                                        notification={res}
                                                        isUnread={true}
                                                    />
                                                ))
                                            ) :
                                                <div className='flex justify-center w-full'>
                                                    <p className='text-gray'>No new notifcations found</p>
                                                </div>}
                                        </div>
                                    </div>


                                    {/* Previous notification....................... */}
                                    {/* <Separator />
                                    {state?.readData?.length > 0 && (
                                        <div className="space-y-1">
                                            <h4 className="text-base font-medium theme-color">Previous notification</h4>
                                            <div className="space-y-1">
                                                {Array.isArray(state?.readData) && state.readData.length > 0 ? (
                                                    state.readData.map((res: any) => (
                                                        <NotificationItem
                                                            key={res._id}
                                                            notification={res}
                                                            isUnread={false}
                                                        />
                                                    ))
                                                ) : null}
                                            </div>
                                        </div>
                                    )} */}
                                </>
                        }

                    </CardContent>
                </Card>
                {
                    state?.unreadData?.length ?
                        <div className="mx-auto mt-5">
                            <PaginationCompo totalDataCount={state.unreadCount} currentPage={Number(params?.pagination)} itemsPerPage={10} onPageChange={handlePageChange} />
                        </div> : null
                }
            </div>
        </ScrollArea>
    );
};



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