import { Link } from "@/i18n/navigation";
import { Program } from "@/types/models";
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { Star, Send, Loader2, CheckCircle2 } from "lucide-react";
import { useTranslations, useLocale } from "next-intl";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

import { useState, useEffect } from "react";
import { checkEnrollment, getFeedbacks, submitFeedback } from "../../_actions/feedback";
import { toast } from "@/hooks/use-toast";

export function Reviews({ program }: { program: Program }) {
    const t = useTranslations();
    const locale = useLocale();
    const isArabic = locale === 'ar';
    const [hasToken, setHasToken] = useState<string | undefined>(undefined);
    const [isEnrolled, setIsEnrolled] = useState<boolean>(false);
    const [dynamicReviews, setDynamicReviews] = useState<any[]>([]);
    const [isLoadingReviews, setIsLoadingReviews] = useState(true);
    
    // Form state
    const [rating, setRating] = useState(5);
    const [feedback, setFeedback] = useState("");
    const [clientName, setClientName] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showForm, setShowForm] = useState(false);
    const [submissionSuccess, setSubmissionSuccess] = useState(false);

    useEffect(() => {
        const token = USER_TOKEN_CL();
        setHasToken(token);

        if (token && program?.id) {
            checkEnrollment(program.id.toString()).then(res => {
                if (res?.status === true) {
                    setIsEnrolled(true);
                }
            });
        }

        fetchDynamicReviews();
    }, [program?.id]);

    const fetchDynamicReviews = async () => {
        setIsLoadingReviews(true);
        try {
            const res = await getFeedbacks();
            if (res?.status && res?.data) {
                // Filter feedbacks for this specific group
                const filtered = res.data.filter((f: any) => f.group_id === program?.id);
                setDynamicReviews(filtered);
            }
        } catch (error) {
            console.error("Error fetching dynamic reviews:", error);
        } finally {
            setIsLoadingReviews(false);
        }
    };

    const handleRatingClick = (val: number) => {
        setRating(val);
    };

    const handleFeedbackSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!feedback.trim()) return;

        setIsSubmitting(true);
        try {
            const res = await submitFeedback({
                group_id: program.id,
                client_name: clientName,
                rating: rating,
                message: feedback
            });

            if (res?.status || res?.success) {
                setSubmissionSuccess(true);
                setFeedback("");
                setClientName("");
                fetchDynamicReviews();
                toast({
                    title: isArabic ? "تم إرسال التقييم بنجاح" : "Review submitted successfully",
                    variant: "default",
                });
            } else {
                toast({
                    title: isArabic ? "فشل إرسال التقييم" : "Failed to submit review",
                    description: res?.message || "",
                    variant: "destructive",
                });
            }
        } catch (error) {
            console.error("Error submitting feedback:", error);
            toast({
                title: isArabic ? "حدث خطأ غير متوقع" : "An unexpected error occurred",
                variant: "destructive",
            });
        } finally {
            setIsSubmitting(false);
        }
    };
    
    // Combine static reviews from program with dynamic reviews from API
    // Mapping dynamic reviews to match static review interface
    const mappedDynamic = dynamicReviews.map(dr => ({
        name: dr.client_name || t("anonymous"),
        message: dr.message || dr.feedback, // handle both keys if API varies
        rating: dr.rating,
        date: dr.created_at ? new Date(dr.created_at).toLocaleDateString(locale) : ""
    }));

    const staticReviews = program?.reviews || [];
    
    // ── Debug Logs ──────────────────────────────────────────────────
    console.group('%c[REVIEWS DEBUG]', 'color:#7c3aed;font-weight:bold');
    console.log('Static Reviews  (from Program):', staticReviews);
    console.log('Dynamic Reviews (from Feedback API):', mappedDynamic);
    console.groupEnd();
    // ───────────────────────────────────────────────────────────────

    // Combine and deduplicate reviews
    const allCombined = [...mappedDynamic, ...staticReviews];
    const allReviews = allCombined.reduce((acc, current) => {
        const isDuplicate = acc.find(item => {
            // Normalize names: treat the "anonymous" label as empty for comparison
            const anonLabel = t("anonymous");
            const name1 = (item.name === anonLabel || !item.name) ? '' : item.name.trim();
            const name2 = (current.name === anonLabel || !current.name) ? '' : current.name.trim();
            
            // Normalize messages
            const msg1 = (item.message || '').trim();
            const msg2 = (current.message || '').trim();

            return (name1 === name2) && 
                   (msg1 === msg2) && 
                   (Number(item.rating) === Number(current.rating));
        });

        if (!isDuplicate) {
            acc.push(current);
        }
        return acc;
    }, [] as any[]);
    
    // Calculate stats based on combined reviews
    const reviewsCount = allReviews.length || program?.reviews_count || 0;
    const totalRating = allReviews.reduce((acc, curr) => acc + (curr.rating || 0), 0);
    const averageRating = reviewsCount > 0 ? totalRating / reviewsCount : program?.rating || 0;

    const ratingBreakdown = [5, 4, 3, 2, 1].map(stars => {
        const count = allReviews.filter(r => r.rating === stars).length;
        const percentage = reviewsCount > 0 ? (count / reviewsCount) * 100 : 0;
        return { stars, count, percentage };
    });

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between gap-4 flex-wrap">
                <h2 className="text-3xl font-bold">{t("programs.reviews")}</h2>
                {isEnrolled && !submissionSuccess && (
                    <Button 
                        onClick={() => setShowForm(!showForm)}
                        variant={showForm ? "outline" : "default"}
                        className={showForm ? "" : "bg-purple-600 hover:bg-purple-700 text-white"}
                    >
                        {showForm 
                            ? (isArabic ? "إلغاء التقييم" : "Cancel Review") 
                            : (isArabic ? "أضف تقييمك" : "Add Your Review")
                        }
                    </Button>
                )}
            </div>

            {/* Submission Form */}
            {isEnrolled && showForm && !submissionSuccess && (
                <div className="border border-purple-200 rounded-lg p-6 bg-purple-50/30 animate-in fade-in slide-in-from-top-4 duration-300">
                    <h3 className="text-xl font-bold mb-4 text-purple-900 border-b pb-2">
                        {isArabic ? "ما هو رأيك في هذه الدورة؟" : "What is your feedback on this course?"}
                    </h3>
                    <form onSubmit={handleFeedbackSubmit} className="space-y-4">
                        <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">
                                {isArabic ? "الاسم (اختياري)" : "Name (Optional)"}
                            </label>
                            <input 
                                type="text"
                                value={clientName}
                                onChange={(e) => setClientName(e.target.value)}
                                placeholder={isArabic ? "أدخل اسمك..." : "Enter your name..."}
                                className="w-full p-2 border rounded-md focus:ring-2 focus:ring-purple-500 focus:outline-none bg-white"
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">
                                {isArabic ? "التقييم" : "Rating"}
                            </label>
                            <div className="flex gap-2">
                                {[1, 2, 3, 4, 5].map((star) => (
                                    <button
                                        key={star}
                                        type="button"
                                        onClick={() => handleRatingClick(star)}
                                        className="transition-transform hover:scale-110"
                                    >
                                        <Star
                                            className={`size-8 ${star <= rating
                                                ? "text-yellow-400 fill-yellow-400"
                                                : "text-gray-300 fill-gray-300"
                                            }`}
                                        />
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">
                                {isArabic ? "تعليقك" : "Your Comment"}
                            </label>
                            <Textarea 
                                value={feedback}
                                onChange={(e) => setFeedback(e.target.value)}
                                placeholder={isArabic ? "اكتب تعليقك هنا..." : "Write your comment here..."}
                                className="min-h-[120px] bg-white"
                                required
                            />
                        </div>

                        <Button 
                            type="submit" 
                            disabled={isSubmitting}
                            className="bg-purple-600 hover:bg-purple-700 text-white w-full md:w-auto px-10"
                        >
                            {isSubmitting ? (
                                <>
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    {isArabic ? "جاري الإرسال..." : "Sending..."}
                                </>
                            ) : (
                                <>
                                    <Send className="mr-2 h-4 w-4" />
                                    {isArabic ? "إرسال التقييم" : "Send Review"}
                                </>
                            )}
                        </Button>
                    </form>
                </div>
            )}

            {/* Success Message */}
            {submissionSuccess && (
                <div className="border border-green-200 rounded-lg p-6 bg-green-50 flex items-center gap-4 animate-in zoom-in duration-300">
                    <div className="p-3 bg-green-100 rounded-full">
                        <CheckCircle2 className="size-8 text-green-600" />
                    </div>
                    <div>
                        <h3 className="text-lg font-bold text-green-900">
                            {isArabic ? "شكراً لك على تقييمك!" : "Thank you for your review!"}
                        </h3>
                        <p className="text-green-700">
                            {isArabic ? "تم استلام ملاحظاتك بنجاح." : "Your feedback has been successfully received."}
                        </p>
                    </div>
                </div>
            )}

            <div className="border rounded-lg p-8 bg-white shadow-sm">
                <div className="flex flex-col md:flex-row gap-8 items-start">
                    {/* Left Side - Overall Rating */}
                    <div className="flex flex-col items-center justify-center min-w-[200px]">
                        <div className="text-7xl font-bold text-purple-600">
                            {averageRating.toFixed(1)}
                        </div>
                        <div className="flex gap-1 my-3">
                            {Array.from({ length: 5 }).map((_, i) => (
                                <Star
                                    key={i}
                                    className={`size-5 ${i < Math.floor(averageRating)
                                        ? "text-yellow-400 fill-yellow-400"
                                        : "text-gray-300 fill-gray-300"
                                        }`}
                                />
                            ))}
                        </div>
                        <p className="text-lg text-gray-600 font-medium text-center">
                            {reviewsCount} {t("programs.reviews")}
                        </p>
                    </div>

                    {/* Right Side - Rating Breakdown */}
                    <div className="flex-1 w-full space-y-3">
                        {ratingBreakdown.map((rating) => (
                            <div key={rating.stars} className="flex items-center gap-4">
                                {/* Stars */}
                                <div className="flex gap-1 min-w-[120px]">
                                    {Array.from({ length: 5 }).map((_, i) => (
                                        <Star
                                            key={i}
                                            className={`size-4 ${i < rating.stars
                                                ? "text-yellow-400 fill-yellow-400"
                                                : "text-gray-300 fill-gray-300"
                                                }`}
                                        />
                                    ))}
                                </div>

                                {/* Progress Bar */}
                                <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                                    <div
                                        className="h-full bg-purple-400 transition-all duration-300"
                                        style={{ width: `${rating.percentage}%` }}
                                    />
                                </div>

                                {/* Count */}
                                <span className="text-gray-600 min-w-[40px] text-right">
                                    ({rating.count})
                                </span>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Reviews List */}
                {allReviews.length > 0 ? (
                    <div className="mt-8 pt-6 border-t space-y-6">
                        {allReviews.map((review, index) => (
                            <div key={index} className="flex gap-4 pb-6 border-b last:border-b-0">
                                <Avatar className="size-12 flex-shrink-0">
                                    <AvatarFallback className="bg-purple-100 text-purple-700 font-semibold border-2 border-purple-200">
                                        {review?.name?.[0]?.toUpperCase() || 'U'}
                                    </AvatarFallback>
                                </Avatar>
                                <div className="flex-1">
                                    <div className="flex items-center gap-3 mb-2 flex-wrap">
                                        <h4 className="font-semibold text-gray-900">{review?.name || t("anonymous")}</h4>
                                        <div className="flex gap-0.5">
                                            {Array.from({ length: 5 }).map((_, i) => (
                                                <Star
                                                    key={i}
                                                    className={`size-3.5 ${i < (review?.rating || 0)
                                                        ? "text-yellow-400 fill-yellow-400"
                                                        : "text-gray-300 fill-gray-300"
                                                        }`}
                                                />
                                            ))}
                                        </div>
                                        {review?.date && <span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">{review.date}</span>}
                                    </div>
                                    {review?.message && <p className="text-gray-700 leading-relaxed">{review.message}</p>}
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className="mt-8 pt-6 border-t text-center py-10">
                        <p className="text-gray-500 italic">{t("programs.no reviews")}</p>
                        {!hasToken && (
                            <div className="mt-4 p-4 bg-gray-50 rounded-lg inline-block">
                                <p className="text-gray-600">
                                    <Link href="/login" className="text-purple-600 font-bold hover:underline">
                                        {t("routes.login")}
                                    </Link>
                                    {" "}{isArabic ? "أو" : "or"}{" "}
                                    <Link href="/register" className="text-purple-600 font-bold hover:underline">
                                        {t("routes.register")}
                                    </Link>
                                    {" "}{isArabic ? "لإضافة تقييمك" : "to post a review"}
                                </p>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}
