'use client';

import { useState } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { 
    MessageSquare, 
    Plus, 
    Send, 
    Link as LinkIcon, 
    User, 
    Calendar,
    ChevronRight,
    ChevronLeft,
    Loader2
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { toast } from '@/hooks/use-toast';
import { addForumPost, getForums, addForumResponse } from '../../_actions/forums';
import { cn } from '@/lib/cn';
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';

interface ForumPost {
    id: number;
    title: string;
    description: string;
    link?: string;
    created_at: string;
    user_details?: {
        first_name: string;
        second_name: string;
        avatar?: string;
    };
    responses?: any[];
}

function ForumPostCard({ 
    post, 
    groupId, 
    isArabic, 
    locale 
}: { 
    post: ForumPost; 
    groupId: string; 
    isArabic: boolean; 
    locale: string; 
}) {
    const queryClient = useQueryClient();
    const [isReplying, setIsReplying] = useState(false);
    const [replyContent, setReplyContent] = useState('');

    const replyMutation = useMutation({
        mutationFn: (data: { content: string }) => addForumResponse(post.id.toString(), data),
        onSuccess: () => {
            toast({
                title: isArabic ? "تم إضافة الرد بنجاح" : "Reply added successfully",
                description: isArabic ? "سيظهر ردك في المنتدى الآن" : "Your reply will appear in the forum now",
            });
            setIsReplying(false);
            setReplyContent('');
            queryClient.invalidateQueries({ queryKey: ['forums', groupId] });
        },
        onError: (error) => {
            toast({
                title: isArabic ? "خطأ في إضافة الرد" : "Error adding reply",
                description: error instanceof Error ? error.message : String(error),
                variant: "destructive"
            });
        }
    });

    const handleSubmitReply = (e: React.FormEvent) => {
        e.preventDefault();
        if (!replyContent.trim()) return;
        replyMutation.mutate({ content: replyContent });
    };

    const [showAllResponses, setShowAllResponses] = useState(false);
    const responsesToShow = showAllResponses ? (post.responses || []) : (post.responses || []).slice(0, 2);
    const hasMoreResponses = (post.responses?.length || 0) > 2;

    return (
        <Card className="border-none shadow-[0_4px_20px_-4px_rgba(0,0,0,0.05)] hover:shadow-[0_8px_30px_-4px_rgba(124,58,237,0.1)] transition-all duration-300 overflow-hidden rounded-[2rem] bg-white group">
            <CardHeader className="pb-4 text-start">
                <div className="flex items-start justify-between">
                    <div className="flex items-center gap-4">
                        <div className="size-12 rounded-2xl bg-gradient-to-br from-purple-50 to-purple-100 flex items-center justify-center overflow-hidden shrink-0 border border-purple-200/50 shadow-inner">
                            {post.user_details?.avatar ? (
                                <img src={post.user_details.avatar} alt="" className="size-full object-cover" />
                            ) : (
                                <div className="text-purple-600 font-bold text-lg uppercase">
                                    {post.user_details?.first_name?.[0]}{post.user_details?.second_name?.[0]}
                                </div>
                            )}
                        </div>
                        <div className='text-start'>
                            <h4 className="font-bold text-gray-900 text-lg leading-tight group-hover:text-purple-600 transition-colors">
                                {post.user_details?.first_name} {post.user_details?.second_name}
                            </h4>
                            <div className="flex items-center gap-3 text-xs text-gray-400 mt-1">
                                <span className="flex items-center gap-1">
                                    <Calendar className="size-3" />
                                    {new Date(post.created_at).toLocaleDateString(locale, { dateStyle: 'medium' })}
                                </span>
                                <span className="size-1 rounded-full bg-gray-200" />
                                <span className="font-medium text-purple-600/70">
                                    {isArabic ? "منشور" : "Posted"}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <CardTitle className="text-xl md:text-2xl font-black text-gray-900 mt-6 tracking-tight leading-snug">
                    {post.title}
                </CardTitle>
            </CardHeader>
            <CardContent className='text-start pb-6'>
                <p className="text-gray-600 text-lg leading-relaxed whitespace-pre-wrap font-medium opacity-90">{post.description}</p>
                {post.link && (
                    <a 
                        href={post.link} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-2 px-4 py-2 bg-purple-50 text-purple-700 rounded-xl text-sm font-bold mt-6 hover:bg-purple-100 transition-colors border border-purple-100"
                    >
                        <LinkIcon className="size-4" />
                        {post.link}
                    </a>
                )}
            </CardContent>

            {responsesToShow.length > 0 && (
                <div className="px-6 py-6 bg-gray-50/50 border-t border-gray-100/50 flex flex-col gap-4">
                    {responsesToShow.map((reply: any) => (
                        <div key={reply.id} className="flex gap-4 items-start md:pl-10 md:rtl:pr-10 border-s-2 border-purple-200 py-3 ps-4 relative">
                            {/* Decorative dot */}
                            <div className="absolute top-1/2 -ms-[1.15rem] size-2 rounded-full bg-purple-400 border-2 border-white shadow-sm" />
                            
                            <div className="size-10 rounded-xl bg-white flex items-center justify-center overflow-hidden shrink-0 border border-gray-100 shadow-sm">
                                {reply.user_details?.avatar ? (
                                    <img src={reply.user_details.avatar} alt="" className="size-full object-cover" />
                                ) : (
                                    <div className="text-purple-500 font-bold text-sm uppercase">
                                        {reply.user_details?.first_name?.[0]}{reply.user_details?.second_name?.[0]}
                                    </div>
                                )}
                            </div>
                            <div className="text-start flex-1 max-w-full">
                                <div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-[0_2px_10px_-4px_rgba(0,0,0,0.02)]">
                                    <div className="flex items-center justify-between mb-2">
                                        <h5 className="text-base font-bold text-gray-900">
                                            {reply.user_details?.first_name} {reply.user_details?.second_name}
                                        </h5>
                                        <span className="text-[11px] font-bold text-gray-400 bg-gray-50 px-2 py-0.5 rounded-full">
                                            {reply.created_at ? new Date(reply.created_at).toLocaleDateString(locale, { dateStyle: 'medium' }) : ''}
                                        </span>
                                    </div>
                                    <p className="text-gray-600 text-sm md:text-base leading-relaxed whitespace-pre-wrap break-words font-medium">{reply.content}</p>
                                </div>
                            </div>
                        </div>
                    ))}

                    {hasMoreResponses && (
                        <Button 
                            variant="ghost" 
                            size="sm" 
                            className="text-purple-600 font-bold hover:bg-purple-100 self-start mt-2 rounded-xl"
                            onClick={() => setShowAllResponses(!showAllResponses)}
                        >
                            {showAllResponses 
                                ? (isArabic ? "عرض أقل" : "Show Less") 
                                : (isArabic ? `عرض المزيد (${(post.responses?.length || 0) - 2})` : `Show More (${(post.responses?.length || 0) - 2})`)
                            }
                        </Button>
                    )}
                </div>
            )}

            <div className="bg-gray-50/80 backdrop-blur-sm p-4 md:p-6 border-t border-gray-100 flex flex-col items-stretch gap-3">
                {!isReplying ? (
                    <Button 
                        variant="ghost" 
                        className="w-full justify-start py-6 text-gray-500 hover:text-purple-700 hover:bg-white rounded-2xl border-2 border-dashed border-transparent border-purple-100 transition-all font-bold" 
                        onClick={() => setIsReplying(true)}
                    >
                        <div className="size-8 rounded-lg bg-white shadow-sm flex items-center justify-center me-3 group-hover:scale-110 transition-transform">
                            <MessageSquare className="size-4 text-purple-600" />
                        </div>
                        {isArabic ? "أضف رداً على هذا المنشور..." : "Add a reply to this post..."}
                    </Button>
                ) : (
                    <form onSubmit={handleSubmitReply} className="flex flex-col gap-4 w-full animate-in fade-in slide-in-from-top-2 duration-300">
                        <Textarea 
                            placeholder={isArabic ? "اكتب ردك هنا بوضوح..." : "Write your reply clearly here..."}
                            value={replyContent}
                            onChange={(e) => setReplyContent(e.target.value)}
                            rows={3}
                            required
                            className="bg-white rounded-2xl border-gray-200 focus:border-purple-300 focus:ring-purple-100 min-h-[120px] p-4 text-base font-medium"
                        />
                        <div className="flex justify-end gap-3">
                            <Button 
                                type="button" 
                                variant="ghost" 
                                className="rounded-xl font-bold text-gray-400 hover:text-gray-600" 
                                onClick={() => setIsReplying(false)}
                            >
                                {isArabic ? "إلغاء الأمر" : "Cancel"}
                            </Button>
                            <Button 
                                type="submit" 
                                className="bg-purple-600 hover:bg-purple-700 text-white rounded-xl px-8 font-bold shadow-lg shadow-purple-200 transition-all active:scale-95 px-6" 
                                disabled={replyMutation.isPending}
                            >
                                {replyMutation.isPending ? <Loader2 className="size-4 me-2 animate-spin" /> : <Send className="size-4 me-2" />}
                                {isArabic ? "إرسال الرد" : "Submit Reply"}
                            </Button>
                        </div>
                    </form>
                )}
            </div>
        </Card>
    );
}

export function ForumsInterface({ 
    groupId, 
    courseName 
}: { 
    groupId: string; 
    courseName?: string;
}) {
    const t = useTranslations('programs');
    const locale = useLocale();
    const isArabic = locale === 'ar';
    const queryClient = useQueryClient();
    const [isAddingPost, setIsAddingPost] = useState(false);
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [link, setLink] = useState('');

    const { data: forumsData, isLoading } = useQuery({
        queryKey: ['forums', groupId],
        queryFn: () => getForums(groupId)
    });

    const mutation = useMutation({
        mutationFn: (data: { title: string, description: string, link?: string }) => addForumPost(groupId, data),
        onSuccess: () => {
            toast({
                title: isArabic ? "تم إضافة المشاركة بنجاح" : "Post added successfully",
                description: isArabic ? "ستظهر مشاركتك في المنتدى الآن" : "Your post will appear in the forum now",
            });
            setIsAddingPost(false);
            setTitle('');
            setDescription('');
            setLink('');
            queryClient.invalidateQueries({ queryKey: ['forums', groupId] });
        },
        onError: (error) => {
            toast({
                title: isArabic ? "خطأ في إضافة المشاركة" : "Error adding post",
                description: error instanceof Error ? error.message : String(error),
                variant: "destructive"
            });
        }
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (!title || !description) {
            toast({
                title: isArabic ? "حقول مطلوبة" : "Required fields",
                description: isArabic ? "الرجاء كتمال العنوان والوصف" : "Please complete title and description",
                variant: "destructive"
            });
            return;
        }
        mutation.mutate({ title, description, link });
    };

    const forums = forumsData?.data || [];
    const isSubmitting = mutation.isPending;

    return (
        <div className="flex flex-col gap-8 max-w-5xl mx-auto p-4 md:p-8 w-full">
            {/* Header Section */}
            <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 border-b border-gray-100 pb-8">
                <div className='text-start space-y-2'>
                    <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-purple-50 text-purple-600 text-xs font-bold uppercase tracking-wider">
                        <MessageSquare className="size-3" />
                        <span>{isArabic ? "منتدى المناقشة" : "Discussion Forum"}</span>
                    </div>
                    <h2 className="text-3xl md:text-4xl font-black text-gray-900 tracking-tight">
                        {isArabic ? "تبادل الخبرات" : "Knowledge Exchange"}
                    </h2>
                    <p className="text-gray-500 text-lg font-medium max-w-xl">
                        {isArabic ? "شارك أسئلتك، أفكارك، وتفاعل مع زملائك في هذه الدورة التدريبية." : "Share your questions, ideas, and interact with your peers in this training course."}
                    </p>
                </div>
                {!isAddingPost && (
                    <Button 
                        onClick={() => setIsAddingPost(true)}
                        className="bg-purple-600 hover:bg-purple-700 text-white gap-2 h-12 px-6 rounded-2xl font-bold shadow-lg shadow-purple-200 transition-all hover:scale-105 active:scale-95"
                    >
                        <Plus className="size-5" />
                        {isArabic ? "إضافة مشاركة جديدة" : "New Discussion"}
                    </Button>
                )}
            </div>

            {isAddingPost && (
                <Card className="border-none shadow-[0_20px_50px_rgba(124,58,237,0.1)] rounded-[2.5rem] overflow-hidden bg-white animate-in zoom-in-95 duration-300">
                    <CardHeader className='text-start bg-gradient-to-br from-purple-50/50 to-white pb-6 pt-8 px-8'>
                        <CardTitle className="text-2xl font-black text-gray-900">{isArabic ? "ماذا يدور في ذهنك؟" : "What's on your mind?"}</CardTitle>
                        <CardDescription className="text-base font-medium text-gray-500">
                            {isArabic ? "املأ البيانات أدناه لنشر موضوع جديد للنقاش مع الزملاء." : "Fill out the details below to post a new discussion topic with peers."}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="p-8">
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="space-y-2 text-start">
                                <label className="text-sm font-bold text-gray-700 px-1">{isArabic ? "عنوان المشاركة" : "Post Title"}</label>
                                <Input 
                                    placeholder={isArabic ? "مثال: سؤال حول الوحدة الثانية..." : "e.g., Question about Module 2..."}
                                    value={title}
                                    onChange={(e) => setTitle(e.target.value)}
                                    required
                                    className="h-14 rounded-2xl border-gray-100 bg-gray-50/50 focus:bg-white focus:ring-purple-100 text-lg font-medium transition-all"
                                />
                            </div>
                            <div className="space-y-2 text-start">
                                <label className="text-sm font-bold text-gray-700 px-1">{isArabic ? "تفاصيل الموضوع" : "Discussion Details"}</label>
                                <Textarea 
                                    placeholder={isArabic ? "اشرح وجهة نظرك أو سؤالك بالتفصيل هنا..." : "Explain your point of view or question in detail here..."}
                                    value={description}
                                    onChange={(e) => setDescription(e.target.value)}
                                    rows={5}
                                    required
                                    className="rounded-2xl border-gray-100 bg-gray-50/50 focus:bg-white focus:ring-purple-100 text-lg font-medium transition-all p-4"
                                />
                            </div>
                            <div className="space-y-2 text-start">
                                <label className="text-sm font-bold text-gray-700 px-1 flex items-center gap-2">
                                    <LinkIcon className="size-4" />
                                    {isArabic ? "أضف رابطاً مفيداً (اختياري)" : "Add a useful link (Optional)"}
                                </label>
                                <Input 
                                    placeholder="https://example.com"
                                    type="url"
                                    value={link}
                                    onChange={(e) => setLink(e.target.value)}
                                    className="h-12 rounded-xl border-gray-100 bg-gray-50/50 focus:bg-white focus:ring-purple-100 font-medium transition-all"
                                />
                            </div>
                            <div className="flex items-center justify-end gap-4 pt-4">
                                <Button 
                                    type="button" 
                                    variant="ghost" 
                                    onClick={() => setIsAddingPost(false)}
                                    disabled={isSubmitting}
                                    className="h-12 px-6 rounded-xl font-bold text-gray-400 hover:text-gray-600"
                                >
                                    {isArabic ? "إلغاء الأمر" : "Cancel"}
                                </Button>
                                <Button 
                                    type="submit" 
                                    className="bg-purple-600 hover:bg-purple-700 text-white h-12 px-10 rounded-xl font-bold gap-2 shadow-xl shadow-purple-200 transition-all active:scale-95"
                                    disabled={isSubmitting}
                                >
                                    {isSubmitting ? <Loader2 className="size-5 animate-spin" /> : <Send className="size-5" />}
                                    {isArabic ? "نشر الآن" : "Post Now"}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            )}

            <div className="space-y-6">
                {isLoading ? (
                    <div className="flex flex-col items-center justify-center py-32 gap-6 bg-white rounded-[3rem] border border-gray-50 shadow-sm transition-all animate-pulse">
                        <div className="relative">
                            <div className="size-16 rounded-full border-4 border-purple-100 border-t-purple-600 animate-spin" />
                            <MessageSquare className="size-6 text-purple-600 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2" />
                        </div>
                        <p className="text-gray-400 font-bold text-lg">{isArabic ? "جاري تحضير المناقشات..." : "Preparing discussions..."}</p>
                    </div>
                ) : forums.length === 0 ? (
                    <div className="bg-white rounded-[3rem] border-2 border-dashed border-gray-100 py-32 text-center relative overflow-hidden group">
                        <div className="absolute inset-0 bg-gradient-to-b from-purple-50/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-700" />
                        <div className="relative z-10 flex flex-col items-center gap-6">
                            <div className="bg-purple-50 p-8 rounded-[2rem] text-purple-200 group-hover:bg-purple-100 group-hover:text-purple-400 transition-all duration-500 group-hover:scale-110">
                                <MessageSquare className="size-16" />
                            </div>
                            <div className="space-y-2">
                                <h3 className="text-2xl md:text-3xl font-black text-gray-900 tracking-tight">{isArabic ? "المنتدى هادئ جداً" : "The forum is very quiet"}</h3>
                                <p className="text-gray-400 text-lg font-medium max-w-sm mx-auto px-4">
                                    {isArabic ? "كن أول من يفتح باب النقاش ويشارك المعرفة مع زملائه في هذه الدورة." : "Be the first to open the discussion and share knowledge with peers in this course."}
                                </p>
                            </div>
                            {!isAddingPost && (
                                <Button 
                                    onClick={() => setIsAddingPost(true)}
                                    className="bg-purple-600 hover:bg-purple-700 text-white h-14 px-10 rounded-2xl font-black gap-2 mt-4 shadow-2xl shadow-purple-200 transition-all hover:scale-105 active:scale-95"
                                >
                                    <Plus className="size-6" />
                                    {isArabic ? "ابدأ أول مناقشة" : "Start First Discussion"}
                                </Button>
                            )}
                        </div>
                    </div>
                ) : (
                    forums.map((post: ForumPost) => (
                        <ForumPostCard 
                            key={post.id} 
                            post={post} 
                            groupId={groupId} 
                            isArabic={isArabic} 
                            locale={locale} 
                        />
                    ))
                )}
            </div>
        </div>
    );
}
