import React, { useEffect, useState } from 'react';
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import dayjs from 'dayjs';
import { Separator } from './ui/separator';
import apis from '@/utils/apis';
import { ScrollArea } from './ui/scroll-area';
import { useGlobalContext } from '@/context/Provider';
import { useRouter } from 'next/navigation';
import logo from "@/assets/images/logo2.png"
import { Skeleton } from './ui/skeleton';

const NotificationCard = ({setState,state}:any) => {



  const { Toast } = useGlobalContext()
  const router = useRouter()
  const [loading, setLoading] = useState(false)

  const getNotificationListing = async () => {
    try {
      setLoading(true)
      const urlSearchParam = new URLSearchParams();
      urlSearchParam.set('pagination', `0`);
      urlSearchParam.set('limit', "10");
      const apiRes = await apis.Notification.listing(urlSearchParam?.toString())
      setState(apiRes)
    } catch (error) {
      console.log(error)
    } finally {
      setLoading(false)
    }
  }

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


  // single read notification...........
  const handleSingleRead = async (id: string) => {
    try {
      const apiRes = await apis.Notification.singleRead(id)
      getNotificationListing()
    } catch (error) {
      Toast.error(error)

    }
  }


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


  const NotificationItem = ({ notification, isUnread }: any) => {
    const redirectPath =
      notification?.data?.redirectPath ||
      notification?.redirectPath ||
      notification?.data?.redirect_path;
    const hasRedirect = Boolean(redirectPath && typeof redirectPath === 'string' && redirectPath.trim());

    const handleClick = () => {
      if (isUnread && notification?._id) {
        handleSingleRead(notification._id);
      }
      if (hasRedirect && typeof redirectPath === 'string') {
        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') || notification?.data?.order_id;
          targetPath = orderId ? `/orders/ongoing?id=${orderId}` : `/orders/ongoing`;
        } else if (!targetPath.startsWith('/')) {
          targetPath = `/${targetPath}`;
        }
        router.push(targetPath);
      }
    };

    return (
      <div
        className={`flex items-center gap-3 p-3 my-2 rounded-lg ${
          hasRedirect || isUnread ? 'cursor-pointer hover:bg-slate-100/80' : ''
        } ${isUnread ? 'bg-primary' : 'bg-slate-50'} transition-colors`}
        onClick={handleClick}
      >
        {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 || notification?.notification?.body || notification?.notification?.title}
          </p>
          <p className="text-xs text-gray">
            {notification.created_at || notification.createdAt
              ? dayjs(notification.created_at || notification.createdAt).format('DD/MM/YYYY')
              : ''}
          </p>
        </div>
        {isUnread && <div className="w-2 h-2 rounded-full bg-blue-500 shrink-0" />}
      </div>
    );
  };





  return (
    <Card className="w-full max-w-md shadow-lg max-h-[550px]">
      <CardHeader className="pb-5 text-center">
        <h3 className="font-semibold theme-color  text-lg">Notifications</h3>
      </CardHeader>
      <CardContent className="space-y-4">

        {
          loading ?
            <Card className="w-96 border-0 shadow-none">
              <CardContent className="p-0 border-0">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <Skeleton className="h-4 w-32" />
                    <Skeleton className="h-5 w-8 rounded-full" />
                  </div>
                  <Skeleton className="h-4 w-24" />
                </div>

                <ScrollArea className="h-[300px]">
                  <div className="space-y-2">
                    {[1, 2].map((_, i) => (
                      <div key={`new-${i}`} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg border">
                        <Skeleton className="w-8 h-8 rounded-full" />
                        <div className="flex-1 space-y-2">
                          <Skeleton className="h-4 w-full" />
                          <Skeleton className="h-3 w-20" />
                        </div>
                        <Skeleton className="w-2 h-2 rounded-full" />
                      </div>
                    ))}
                    <Skeleton className="h-4 w-36 mt-4 mb-2" />
                    {[1, 2].map((_, i) => (
                      <div key={`prev-${i}`} className="flex items-start gap-3 p-3 bg-white rounded-lg border">
                        <Skeleton className="w-8 h-8 rounded-full" />
                        <div className="flex-1 space-y-2">
                          <Skeleton className="h-4 w-full" />
                          <Skeleton className="h-3 w-20" />
                        </div>
                      </div>
                    ))}
                  </div>
                </ScrollArea>
                <Skeleton className="h-10 w-full mt-4 rounded-md" />
              </CardContent>
            </Card> :
            <>
              {/* ..................Unread notification................. */}
              {state?.unreadCount > 0 && (
                <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">
                    <ScrollArea className='h-[150px] p-2 '>
                      {Array.isArray(state?.unreadData) && state.unreadData.length > 0 ? (
                        state.unreadData.map((res: any) => (
                          <NotificationItem
                            key={res._id}
                            notification={res}
                            isUnread={true}
                          />
                        ))
                      ) : null}
                    </ScrollArea>
                    {
                      state.unreadData.length > 0 ?
                        <div className='flex justify-end'>
                          <Button type='button' onClick={() => router.push("/notifications/page/1?limit=10")}>View All</Button>
                        </div> : null
                    }
                  </div>
                </div>
              )}
              <Separator />
              {/* ............Previous notification.................. */}
              {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">
                    <ScrollArea className='h-[150px] p-2 '>
                      {Array.isArray(state?.readData) && state.readData.length > 0 ? (
                        state.readData.map((res: any) => (
                          <NotificationItem
                            key={res._id}
                            notification={res}
                            isUnread={false}
                          />
                        ))
                      ) : null}
                    </ScrollArea>
                  </div>
                </div>
              )}
            </>
        }

      </CardContent>
    </Card>
  );
};

export default NotificationCard;