import { Head, Link, router, usePage } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { show } from '@/actions/App/Http/Controllers/Forum/ThreadController';
import { index } from '@/actions/App/Http/Controllers/Forum/ForumController';
import { MessageSquare, Users, Clock, Plus, Pin, Lock, Eye, MessageCircle, ChevronLeft } from 'lucide-react';
import { useState } from 'react';
import PublicLayout from '@/layouts/public-layout';
import { Card, CardContent } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { CreateThreadModal } from '@/components/forum/create-thread-modal';
import { formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
import { SharedData } from '@/types';

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

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;
    latest_post?: {
        created_at: string;
        user: User;
    };
}

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

interface PaginationLinks {
    url?: string;
    label: string;
    active: boolean;
}

interface Pagination {
    data: Thread[];
    current_page: number;
    last_page: number;
    prev_page_url?: string;
    next_page_url?: string;
    links: PaginationLinks[];
}

interface Props {
    forum: Forum;
    threads: Pagination;
}

export default function ForumShow({ forum, threads }: Props) {
    const { auth } = usePage<SharedData>().props;
    const isAuthenticated = !!auth.user;
    const [createModalOpen, setCreateModalOpen] = useState(false);

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

            <div className="max-w-5xl mx-auto p-6 space-y-8">
                {/* Header & Breadcrumbs */}
                <div className="space-y-4">
                    <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <Link href={index.url()} className="hover:text-forest transition-colors flex items-center gap-1">
                            <ChevronLeft className="h-4 w-4" />
                            Foros
                        </Link>
                        <span>/</span>
                        <span className="text-foreground font-medium">{forum.name}</span>
                    </div>

                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div className="space-y-2">
                            <h1 className="text-3xl font-bold font-heading text-forest-dark">{forum.name}</h1>
                            <p className="text-muted-foreground max-w-2xl">
                                {forum.description}
                            </p>
                        </div>
                        {isAuthenticated ? (
                            <Button 
                                onClick={() => setCreateModalOpen(true)}
                                className="bg-forest hover:bg-forest-light shrink-0"
                            >
                                <Plus className="mr-2 h-4 w-4" />
                                Nuevo Hilo
                            </Button>
                        ) : (
                            <Link href="/login">
                                <Button className="bg-forest hover:bg-forest-light shrink-0">
                                    <Plus className="mr-2 h-4 w-4" />
                                    Inicia sesión para publicar
                                </Button>
                            </Link>
                        )}
                    </div>
                </div>

                <CreateThreadModal 
                    open={createModalOpen} 
                    onOpenChange={setCreateModalOpen}
                    forumSlug={forum.slug}
                />

                {/* Threads List */}
                <div className="space-y-4">
                    {threads.data.length === 0 ? (
                        <Card className="bg-muted/30 border-dashed">
                            <CardContent className="flex flex-col items-center justify-center p-12 text-center space-y-4">
                                <div className="p-4 rounded-full bg-background border">
                                    <MessageSquare className="h-8 w-8 text-muted-foreground" />
                                </div>
                                <div>
                                    <h3 className="font-semibold text-lg">No hay hilos aún</h3>
                                    <p className="text-muted-foreground">Sé el primero en iniciar una conversación en este foro.</p>
                                </div>
                                <Button onClick={() => setCreateModalOpen(true)} variant="outline">
                                    Crear primer hilo
                                </Button>
                            </CardContent>
                        </Card>
                    ) : (
                        threads.data.map((thread) => (
                            <motion.div
                                key={thread.id}
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                            >
                                <Link href={show.url({ forum: forum.slug, thread: thread.slug })}>
                                    <Card className={`hover:shadow-md transition-all duration-200 group ${thread.is_sticky ? 'bg-forest/5 border-forest/20' : ''}`}>
                                        <div className="p-4 flex gap-4">
                                            {/* Avatar */}
                                            <div className="hidden sm:block shrink-0">
                                                <Avatar>
                                                    <AvatarImage src={thread.user.profile_photo_url} />
                                                    <AvatarFallback>{thread.user.name.charAt(0)}</AvatarFallback>
                                                </Avatar>
                                            </div>

                                            {/* Content */}
                                            <div className="flex-1 min-w-0">
                                                <div className="flex items-start justify-between gap-2 mb-1">
                                                    <div className="space-y-1">
                                                        <div className="flex items-center gap-2">
                                                            {thread.is_sticky && <Pin className="h-4 w-4 text-forest rotate-45" />}
                                                            {thread.is_locked && <Lock className="h-4 w-4 text-amber-500" />}
                                                            <h3 className="font-semibold text-lg group-hover:text-forest transition-colors truncate">
                                                                {thread.title}
                                                            </h3>
                                                        </div>
                                                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                                            <span className="font-medium text-foreground">{thread.user.name}</span>
                                                            <span>•</span>
                                                            <span>{formatDistanceToNow(new Date(thread.created_at), { addSuffix: true, locale: es })}</span>
                                                        </div>
                                                    </div>

                                                    {/* Mobile Stats */}
                                                    <div className="sm:hidden flex flex-col items-end text-xs text-muted-foreground gap-1">
                                                        <div className="flex items-center gap-1">
                                                            <MessageCircle className="h-3 w-3" /> {thread.posts_count}
                                                        </div>
                                                        <div className="flex items-center gap-1">
                                                            <Eye className="h-3 w-3" /> {thread.views_count}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            {/* Desktop Stats */}
                                            <div className="hidden sm:flex items-center gap-6 px-4 border-l border-r mx-2 shrink-0">
                                                <div className="text-center min-w-[60px]">
                                                    <div className="font-bold text-lg">{thread.posts_count}</div>
                                                    <div className="text-xs text-muted-foreground">Respuestas</div>
                                                </div>
                                                <div className="text-center min-w-[60px]">
                                                    <div className="font-bold text-lg text-muted-foreground">{thread.views_count}</div>
                                                    <div className="text-xs text-muted-foreground">Vistas</div>
                                                </div>
                                            </div>

                                            {/* Last Post Info */}
                                            <div className="hidden md:flex flex-col justify-center items-end text-sm text-right shrink-0 min-w-[140px]">
                                                {thread.latest_post ? (
                                                    <>
                                                        <div className="flex items-center gap-2 mb-1">
                                                            <Avatar className="h-6 w-6">
                                                                <AvatarImage src={thread.latest_post.user.profile_photo_url} />
                                                                <AvatarFallback>{thread.latest_post.user.name.charAt(0)}</AvatarFallback>
                                                            </Avatar>
                                                            <span className="truncate max-w-[100px]">{thread.latest_post.user.name}</span>
                                                        </div>
                                                        <div className="text-muted-foreground text-xs">
                                                            {formatDistanceToNow(new Date(thread.latest_post.created_at), { addSuffix: true, locale: es })}
                                                        </div>
                                                    </>
                                                ) : (
                                                    <span className="text-muted-foreground italic text-xs">Sin respuestas</span>
                                                )}
                                            </div>
                                        </div>
                                    </Card>
                                </Link>
                            </motion.div>
                        ))
                    )}
                </div>

                {/* Pagination */}
                {threads.data.length > 0 && threads.last_page > 1 && (
                    <div className="flex justify-center pt-8">
                        <div className="flex items-center gap-2">
                            {threads.links.map((link, i) => (
                                <Link
                                    key={i}
                                    href={link.url || '#'}
                                    preserveState
                                    className={`
                                        px-4 py-2 rounded-md text-sm font-medium transition-colors
                                        ${link.active 
                                            ? 'bg-forest text-white' 
                                            : !link.url 
                                                ? 'text-muted-foreground cursor-not-allowed' 
                                                : 'bg-background border hover:bg-muted'
                                        }
                                    `}
                                    onClick={(e) => !link.url && e.preventDefault()}
                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                />
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </PublicLayout>
    );
}
