import { Head, Link, router } from '@inertiajs/react';
import { Pin, Lock, Unlock, PinOff, Eye, MessageSquare, ChevronLeft } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
import { toast } from 'sonner';
import { index as forumsIndex, toggleSticky, toggleLock } from '@/actions/App/Http/Controllers/Admin/ForumManagementController';
import { show as threadShow } from '@/actions/App/Http/Controllers/Forum/ThreadController';

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

interface Thread {
    id: number;
    title: string;
    slug: 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 PaginationLinks {
    url?: string;
    label: string;
    active: boolean;
}

interface Pagination {
    data: Thread[];
    links: PaginationLinks[];
}

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

export default function AdminForumThreads({ forum, threads }: Props) {
    const handleToggleSticky = (threadId: number, currentState: boolean) => {
        router.post(toggleSticky.url(threadId), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(currentState ? 'Hilo desfijado' : 'Hilo fijado'),
        });
    };

    const handleToggleLock = (threadId: number, currentState: boolean) => {
        router.post(toggleLock.url(threadId), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(currentState ? 'Hilo desbloqueado' : 'Hilo bloqueado'),
        });
    };

    return (
        <AppLayout>
            <Head title={`Moderar: ${forum.name}`} />

            <div className="p-6 space-y-6">
                {/* Header */}
                <div className="space-y-4">
                    <Link 
                        href={forumsIndex.url()} 
                        className="inline-flex items-center text-sm text-muted-foreground hover:text-forest transition-colors"
                    >
                        <ChevronLeft className="h-4 w-4 mr-1" />
                        Volver a Foros
                    </Link>
                    <div>
                        <h1 className="text-3xl font-bold">Moderación: {forum.name}</h1>
                        <p className="text-muted-foreground mt-1">
                            Gestiona hilos: fijar, bloquear o eliminar
                        </p>
                    </div>
                </div>

                {/* Threads List */}
                <div className="space-y-4">
                    {threads.data.length === 0 ? (
                        <Card className="p-12 text-center text-muted-foreground">
                            <MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-50" />
                            <p>No hay hilos en este foro aún.</p>
                        </Card>
                    ) : (
                        threads.data.map((thread) => (
                            <Card key={thread.id} className="p-6 hover:shadow-md transition-shadow">
                                <div className="flex items-start gap-4">
                                    {/* Avatar */}
                                    <Avatar>
                                        <AvatarImage src={thread.user.profile_photo_url} />
                                        <AvatarFallback>{thread.user.name.charAt(0)}</AvatarFallback>
                                    </Avatar>

                                    {/* Content */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-start justify-between gap-4 mb-2">
                                            <div className="space-y-1">
                                                <div className="flex items-center gap-2 flex-wrap">
                                                    {thread.is_sticky && (
                                                        <Badge variant="secondary" className="gap-1 bg-forest/10 text-forest">
                                                            <Pin className="h-3 w-3" /> Fijado
                                                        </Badge>
                                                    )}
                                                    {thread.is_locked && (
                                                        <Badge variant="destructive" className="gap-1">
                                                            <Lock className="h-3 w-3" /> Bloqueado
                                                        </Badge>
                                                    )}
                                                    <Link
                                                        href={threadShow.url({ forum: forum.slug, thread: thread.slug })}
                                                        className="text-lg font-semibold hover:text-forest transition-colors"
                                                    >
                                                        {thread.title}
                                                    </Link>
                                                </div>
                                                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                                    <span className="font-medium">{thread.user.name}</span>
                                                    <span>•</span>
                                                    <span>{formatDistanceToNow(new Date(thread.created_at), { addSuffix: true, locale: es })}</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="flex items-center gap-4 text-sm text-muted-foreground">
                                            <div className="flex items-center gap-1">
                                                <Eye className="h-4 w-4" />
                                                {thread.views_count} vistas
                                            </div>
                                            <div className="flex items-center gap-1">
                                                <MessageSquare className="h-4 w-4" />
                                                {thread.posts_count} respuestas
                                            </div>
                                        </div>
                                    </div>

                                    {/* Actions */}
                                    <div className="flex items-center gap-2 shrink-0">
                                        <Button
                                            variant={thread.is_sticky ? "default" : "outline"}
                                            size="sm"
                                            onClick={() => handleToggleSticky(thread.id, thread.is_sticky)}
                                            className={thread.is_sticky ? "bg-forest hover:bg-forest-light" : ""}
                                        >
                                            {thread.is_sticky ? (
                                                <>
                                                    <PinOff className="h-4 w-4 mr-1" />
                                                    Defijar
                                                </>
                                            ) : (
                                                <>
                                                    <Pin className="h-4 w-4 mr-1" />
                                                    Fijar
                                                </>
                                            )}
                                        </Button>
                                        <Button
                                            variant={thread.is_locked ? "destructive" : "outline"}
                                            size="sm"
                                            onClick={() => handleToggleLock(thread.id, thread.is_locked)}
                                        >
                                            {thread.is_locked ? (
                                                <>
                                                    <Unlock className="h-4 w-4 mr-1" />
                                                    Desbloquear
                                                </>
                                            ) : (
                                                <>
                                                    <Lock className="h-4 w-4 mr-1" />
                                                    Bloquear
                                                </>
                                            )}
                                        </Button>
                                    </div>
                                </div>
                            </Card>
                        ))
                    )}
                </div>

                {/* Pagination */}
                {threads.data.length > 0 && threads.links.length > 3 && (
                    <div className="flex justify-center pt-4">
                        <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>
        </AppLayout>
    );
}
