import { Head, Link, useForm, usePage, router } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { index, show as showForum } from '@/actions/App/Http/Controllers/Forum/ForumController';
import { store as storePost } from '@/actions/App/Http/Controllers/Forum/PostController';
import { deleteThread, toggleSticky, toggleLock } from '@/actions/App/Http/Controllers/Forum/ForumModerationController';
import { MessageSquare, Calendar, ChevronLeft, Lock, Trash2, Pin, PinOff, Unlock } from 'lucide-react';
import PublicLayout from '@/layouts/public-layout';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { formatDistanceToNow, format } from 'date-fns';
import { es } from 'date-fns/locale';
import { ForumPostItem } from '@/components/forum/forum-post-item';
import { toast } from 'sonner';
import { SharedData } from '@/types';
import { useState } from 'react';

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 Thread {
    id: number;
    title: string;
    slug: string;
    content: string;
    is_sticky: boolean;
    is_locked: boolean;
    views_count: number;
    posts_count: number;
    created_at: string;
    user: User;
}

interface Forum {
    id: number;
    name: string;
    slug: string;
}

interface Props {
    forum: Forum;
    thread: Thread;
    posts: {
        data: Post[];
        links: any[]; // Pagination needed?
    };
}

export default function ThreadShow({ forum, thread, posts }: Props) {
    const { auth } = usePage<SharedData>().props;
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const { data, setData, post, processing, reset } = useForm({
        content: '',
        parent_id: null,
    });
    
    const isAuthenticated = !!auth.user;
    
    // Check moderation permissions (only if authenticated)
    const can = {
        moderate: isAuthenticated && (auth.permissions?.includes('forum.moderate') || auth.roles?.includes('admin') || auth.roles?.includes('curator')),
        delete: isAuthenticated && (auth.permissions?.includes('forum.delete') || auth.roles?.includes('admin') || auth.roles?.includes('curator') || thread.user.id === auth.user?.id),
    };

    const handleToggleSticky = () => {
        router.post(toggleSticky.url(thread.id), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(thread.is_sticky ? 'Hilo desfijado' : 'Hilo fijado'),
            onError: (errors: any) => toast.error(errors.error || 'Error al cambiar estado fijado'),
        });
    };

    const handleToggleLock = () => {
        router.post(toggleLock.url(thread.id), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(thread.is_locked ? 'Hilo desbloqueado' : 'Hilo bloqueado'),
            onError: (errors: any) => toast.error(errors.error || 'Error al cambiar estado bloqueo'),
        });
    };

    const handleDelete = () => {
        router.delete(deleteThread.url(thread.id), {
            onSuccess: () => {
                setIsDeleteDialogOpen(false);
                toast.success('Hilo eliminado exitosamente');
            },
            onError: (errors: any) => toast.error(errors.error || 'No se pudo eliminar el hilo'),
        });
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(storePost.url(thread.id), {
            preserveScroll: true,
            onSuccess: () => {
                reset();
                toast.success('Comentario publicado exitosamente');
            },
        });
    };

    return (
        <PublicLayout>
            <Head title={thread.title} />

            <div className="max-w-4xl mx-auto p-6 space-y-8">
                {/* Breadcrumbs */}
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Link href={index.url()} className="hover:text-forest transition-colors">Foros</Link>
                    <span>/</span>
                    <Link href={showForum.url(forum.slug)} className="hover:text-forest transition-colors">{forum.name}</Link>
                    <span>/</span>
                    <span className="text-foreground font-medium truncate max-w-[200px]">{thread.title}</span>
                </div>

                {/* Main Thread Content */}
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                >
                    <Card className="border-l-4 border-l-forest overflow-hidden">
                        <CardHeader className="bg-muted/30 pb-4">
                            <div className="flex items-start justify-between gap-4">
                                <div className="space-y-3 flex-1">
                                    <div className="flex items-center gap-2 flex-wrap">
                                        {thread.is_locked && <Badge variant="destructive" className="gap-1"><Lock className="w-3 h-3" /> Cerrado</Badge>}
                                        {thread.is_sticky && <Badge variant="secondary" className="bg-forest/10 text-forest hover:bg-forest/20">Fijado</Badge>}
                                        <h1 className="text-2xl font-bold font-heading text-forest-dark leading-tight">
                                            {thread.title}
                                        </h1>
                                    </div>
                                    <div className="flex items-center gap-3 text-sm text-muted-foreground">
                                        <div className="flex items-center gap-2 text-foreground font-medium">
                                            <Avatar className="h-6 w-6">
                                                <AvatarImage src={thread.user.profile_photo_url} />
                                                <AvatarFallback>{thread.user.name.charAt(0)}</AvatarFallback>
                                            </Avatar>
                                            {thread.user.name}
                                        </div>
                                        <span>•</span>
                                        <div className="flex items-center gap-1" title={format(new Date(thread.created_at), "PPP p", { locale: es })}>
                                            <Calendar className="h-3 w-3" />
                                            {formatDistanceToNow(new Date(thread.created_at), { addSuffix: true, locale: es })}
                                        </div>
                                    </div>
                                </div>

                                {/* Moderation Actions */}
                                {(can.moderate || can.delete) && (
                                    <div className="flex gap-2 shrink-0">
                                        {can.moderate && (
                                            <>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={handleToggleSticky}
                                                    title={thread.is_sticky ? "Desfijar" : "Fijar"}
                                                >
                                                    {thread.is_sticky ? <PinOff className="h-4 w-4" /> : <Pin className="h-4 w-4" />}
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={handleToggleLock}
                                                    title={thread.is_locked ? "Desbloquear" : "Bloquear"}
                                                >
                                                    {thread.is_locked ? <Unlock className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
                                                </Button>
                                            </>
                                        )}
                                        {can.delete && (
                                            <>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={() => setIsDeleteDialogOpen(true)}
                                                    className="text-red-500 hover:text-red-700 hover:bg-red-50"
                                                    title="Eliminar Hilo"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>

                                                <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                                                    <DialogContent>
                                                        <DialogHeader>
                                                            <DialogTitle>¿Estás completamente seguro?</DialogTitle>
                                                            <DialogDescription>
                                                                Esta acción no se puede deshacer. Esto eliminará permanentemente el hilo y todos sus comentarios.
                                                            </DialogDescription>
                                                        </DialogHeader>
                                                        <DialogFooter>
                                                            <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
                                                                Cancelar
                                                            </Button>
                                                            <Button variant="destructive" onClick={handleDelete}>
                                                                Eliminar Hilo
                                                            </Button>
                                                        </DialogFooter>
                                                    </DialogContent>
                                                </Dialog>
                                            </>
                                        )}
                                    </div>
                                )}
                            </div>
                        </CardHeader>
                        
                        <Separator />
                        
                        <CardContent className="p-6 md:p-8 min-h-[150px] text-lg leading-relaxed whitespace-pre-wrap">
                            {thread.content}
                        </CardContent>
                    </Card>
                </motion.div>

                {/* Posts Section */}
                <div className="space-y-8">
                    <div className="flex items-center gap-2 text-lg font-semibold text-muted-foreground">
                        <MessageSquare className="h-5 w-5" />
                        {posts.data.length} Respuestas
                    </div>

                    <div className="space-y-6">
                        {posts.data.map((post) => (
                            <ForumPostItem 
                                key={post.id} 
                                post={post} 
                                threadId={thread.id} 
                                threadSlug={thread.slug}
                                forumSlug={forum.slug}
                            />
                        ))}
                        
                        {posts.data.length === 0 && (
                            <div className="text-center py-12 text-muted-foreground bg-muted/20 rounded-lg border border-dashed">
                                No hay respuestas aún. {isAuthenticated ? '¡Sé el primero en participar!' : 'Inicia sesión para participar.'}
                            </div>
                        )}
                    </div>

                    {/* Main Reply Form */}
                    {thread.is_locked ? (
                        <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-200 p-4 rounded-lg flex items-center justify-center gap-2">
                            <Lock className="h-4 w-4" />
                            Este hilo está cerrado y no admite nuevas respuestas.
                        </div>
                    ) : isAuthenticated ? (
                        <div className="bg-card border rounded-lg p-6 shadow-sm">
                            <h3 className="text-lg font-semibold mb-4">Publicar una respuesta</h3>
                            <form onSubmit={handleSubmit} className="space-y-4">
                                <Textarea
                                    value={data.content}
                                    onChange={e => setData('content', e.target.value)}
                                    placeholder="Escribe tu respuesta aquí. Sé amable y constructivo."
                                    className="min-h-[120px]"
                                />
                                <div className="flex justify-end">
                                    <Button 
                                        type="submit" 
                                        className="bg-forest hover:bg-forest-light"
                                        disabled={processing || !data.content.trim()}
                                    >
                                        {processing ? 'Publicando...' : 'Publicar Respuesta'}
                                    </Button>
                                </div>
                            </form>
                        </div>
                    ) : (
                        <div className="bg-card border rounded-lg p-6 shadow-sm text-center">
                            <p className="text-muted-foreground mb-4">¿Quieres participar en la conversación?</p>
                            <Link href="/login">
                                <Button className="bg-forest hover:bg-forest-light">
                                    Inicia sesión para responder
                                </Button>
                            </Link>
                        </div>
                    )}
                </div>
            </div>
        </PublicLayout>
    );
}
