// components/layout/PendingChallengesBadge.tsx
"use client";

import React, { useState, useEffect } from "react";
import { Award } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
   Popover,
   PopoverContent,
   PopoverTrigger,
} from "@/components/ui/popover";
import { useRouter } from "next/navigation";
import { format } from "date-fns";

interface PendingChallenge {
   id: string;
   productId: number;
   product: {
       plan: string;
       description: string;
   };
   createdAt: string;
}

interface PendingChallengesBadgeProps {
   onRefetch?: () => void;
}

export function PendingChallengesBadge({ onRefetch }: PendingChallengesBadgeProps) {
   const [pendingChallenges, setPendingChallenges] = useState<PendingChallenge[]>([]);
   const [isLoading, setIsLoading] = useState(false);
   const router = useRouter();

   const fetchPendingChallenges = async () => {
       setIsLoading(true);
       try {
           const res = await fetch("/api/products/pending");
           if (res.ok) {
               const data = await res.json();
               setPendingChallenges(data);
               if (onRefetch) {
                   onRefetch();
               }
           }
       } catch (error) {
           console.error("Error fetching pending challenges:", error);
       } finally {
           setIsLoading(false);
       }
   };

   useEffect(() => {
       (window as any).refreshPendingChallenges = fetchPendingChallenges;
       
       fetchPendingChallenges();

       const intervalId = setInterval(() => {
           fetchPendingChallenges();
       }, 30000);

       return () => {
           clearInterval(intervalId);
           delete (window as any).refreshPendingChallenges;
       };
   }, []);

   const handleChallengeClick = (id: string) => {
       router.push(`/dashboard/shop/user-products`);
   };

   return (
       <Popover>
           <PopoverTrigger asChild>
               <div className="relative cursor-pointer">
                   <Award className="h-5 w-5" />
                   {pendingChallenges.length > 0 && (
                       <Badge className="absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 rounded-full">
                           {pendingChallenges.length}
                       </Badge>
                   )}
               </div>
           </PopoverTrigger>
           <PopoverContent className="w-80" align="end" dir="rtl">
               <div className="space-y-4">
                   <h4 className="font-medium text-sm">چالش‌های در انتظار</h4>

                   {isLoading ? (
                       <div className="text-center py-4">
                           <span className="text-muted-foreground">در حال بارگذاری...</span>
                       </div>
                   ) : pendingChallenges.length === 0 ? (
                       <div className="text-center py-4">
                           <span className="text-muted-foreground">چالش در انتظاری وجود ندارد</span>
                       </div>
                   ) : (
                       <div className="space-y-3 max-h-[300px] overflow-y-auto">
                           {pendingChallenges.map((challenge) => (
                               <div
                                   key={challenge.id}
                                   className="bg-muted/50 rounded-lg p-3 cursor-pointer hover:bg-muted"
                                   onClick={() => handleChallengeClick(challenge.id)}
                               >
                                   <div className="flex justify-between items-start">
                                       <p className="font-medium">{challenge.product.plan}</p>
                                       <Badge>در انتظار</Badge>
                                   </div>
                                   <p className="text-sm mt-2 line-clamp-2">
                                       {challenge.product.description}
                                   </p>
                                   <p className="text-xs text-muted-foreground mt-1 text-left">
                                       {format(new Date(challenge.createdAt), "HH:mm - yyyy/MM/dd")}
                                   </p>
                               </div>
                           ))}
                       </div>
                   )}
               </div>
           </PopoverContent>
       </Popover>
   );
}