import { startTransition, useState } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
import { MessageSquare, Share2, Flag, CornerDownRight, Trash2 } from 'lucide-react';
import { VoteControl } from './vote-control';
import { useForm, usePage, router, Link } from '@inertiajs/react';
import { store as storePost } from '@/actions/App/Http/Controllers/Forum/PostController';
import { deletePost } from '@/actions/App/Http/Controllers/Forum/ForumModerationController';
import { toast } from 'sonner';
import { SharedData } from '@/types';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';

interface User {
    id: number;
    name: string;
    profile_photo_url?: string;
}

interface Vote {
    id: number;
    user_id: number;
    vote_type: 'up' | 'down';
}

interface Post {
    id: number;
    user_id: number;
    content: string;
    votes_count: number;
    created_at: string;
    user: User;
    user_vote?: Vote | null;
    replies?: Post[];
}

interface Props {
    post: Post;
    threadId: number;
    threadSlug: string;
    forumSlug: string;
    isReply?: boolean;
}

export function ForumPostItem({ post, threadSlug, threadId, forumSlug, isReply = false }: Props) {
    const { auth } = usePage<SharedData>().props;
    const [replying, setReplying] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    
    const isAuthenticated = !!auth.user;
    
    // Check permissions (only if authenticated)
    const can = {
        delete: isAuthenticated && (auth.permissions?.includes('forum.delete') || auth.roles?.includes('admin') || auth.roles?.includes('curator')),
        isOwner: isAuthenticated && post.user.id === auth.user?.id,
    };

    const { data, setData, post: submitPost, processing, reset } = useForm({
        content: '',
        parent_id: post.id,
    });

    const handleReply = (e: React.FormEvent) => {
        e.preventDefault();
        submitPost(storePost.url(threadId), {
            preserveScroll: true,
            onSuccess: () => {
                setReplying(false);
                reset();
                toast.success('Respuesta publicada');
            },
        });
    };

    const handleDelete = () => {
        router.delete(deletePost.url(post.id), {
            preserveScroll: true,
            onSuccess: () => {
                setIsDeleteDialogOpen(false);
                toast.success('Comentario eliminado');
            },
            onError: (errors: any) => toast.error(errors.error || 'No se pudo eliminar el comentario'),
        });
    };

    return (
        <div className={`flex gap-4 ${isReply ? 'mt-4 ml-12 border-l-2 pl-4 border-muted' : ''}`}>
            {/* Vote Control (Left Side) */}
            <div className="shrink-0 pt-2">
                <VoteControl 
                    postId={post.id} 
                    votesCount={post.votes_count} 
                    userVote={post.user_vote?.vote_type}
                    size={isReply ? 'sm' : 'default'}
                />
            </div>

            {/* Post Content */}
            <div className="flex-1 min-w-0 space-y-2">
                <Card className="p-4 bg-card/50 hover:bg-card transition-colors">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                            <Avatar className="h-6 w-6">
                                <AvatarImage src={post.user.profile_photo_url} />
                                <AvatarFallback>{post.user.name.charAt(0)}</AvatarFallback>
                            </Avatar>
                            <span className="font-semibold text-sm">{post.user.name}</span>
                            <span className="text-muted-foreground text-xs">• hace {formatDistanceToNow(new Date(post.created_at), { locale: es })}</span>
                        </div>
                    </div>

                    {/* Body */}
                    <div className="prose prose-sm max-w-none text-foreground mb-4 whitespace-pre-wrap">
                        {post.content}
                    </div>

                    {/* Footer Actions */}
                    <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        {isAuthenticated ? (
                            <button 
                                onClick={() => setReplying(!replying)}
                                className="flex items-center gap-1 hover:text-forest transition-colors font-medium"
                            >
                                <MessageSquare className="h-3 w-3" />
                                Responder
                            </button>
                        ) : (
                            <Link 
                                href="/login"
                                className="flex items-center gap-1 hover:text-forest transition-colors font-medium"
                            >
                                <MessageSquare className="h-3 w-3" />
                                Responder
                            </Link>
                        )}
                        <button className="flex items-center gap-1 hover:text-foreground transition-colors">
                            <Share2 className="h-3 w-3" />
                            Compartir
                        </button>
                        
                        {(can.delete || can.isOwner) && (
                            <>
                                <button 
                                    onClick={() => setIsDeleteDialogOpen(true)}
                                    className="flex items-center gap-1 hover:text-red-500 transition-colors ml-auto"
                                >
                                    <Trash2 className="h-3 w-3" />
                                    Eliminar
                                </button>
                                
                                <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                                    <DialogContent>
                                        <DialogHeader>
                                            <DialogTitle>¿Eliminar comentario?</DialogTitle>
                                            <DialogDescription>
                                                Esta acción no se puede deshacer. Se eliminará el comentario y todas sus respuestas si las tiene.
                                            </DialogDescription>
                                        </DialogHeader>
                                        <DialogFooter>
                                            <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
                                                Cancelar
                                            </Button>
                                            <Button variant="destructive" onClick={handleDelete}>
                                                Eliminar
                                            </Button>
                                        </DialogFooter>
                                    </DialogContent>
                                </Dialog>
                            </>
                        )}
                    </div>
                </Card>

                {/* Reply Form */}
                {replying && (
                    <form onSubmit={handleReply} className="mt-2 ml-4 flex gap-3 animate-in fade-in slide-in-from-top-2">
                        <div className="shrink-0 pt-2">
                            <CornerDownRight className="h-5 w-5 text-muted-foreground" />
                        </div>
                        <div className="flex-1 space-y-2">
                            <Textarea
                                value={data.content}
                                onChange={e => setData('content', e.target.value)}
                                placeholder={`Respondiendo a ${post.user.name}...`}
                                className="min-h-[80px]"
                                autoFocus
                            />
                            <div className="flex justify-end gap-2">
                                <Button 
                                    type="button" 
                                    variant="ghost" 
                                    size="sm" 
                                    onClick={() => setReplying(false)}
                                >
                                    Cancelar
                                </Button>
                                <Button 
                                    type="submit" 
                                    size="sm" 
                                    className="bg-forest hover:bg-forest-light"
                                    disabled={processing}
                                >
                                    Responder
                                </Button>
                            </div>
                        </div>
                    </form>
                )}

                {/* Nested Replies */}
                {post.replies && post.replies.length > 0 && (
                    <div className="space-y-4">
                        {post.replies.map(reply => (
                            <ForumPostItem 
                                key={reply.id} 
                                post={reply} 
                                threadId={threadId}
                                threadSlug={threadSlug}
                                forumSlug={forumSlug}
                                isReply={true}
                            />
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
