import { Head, Link, router, usePage } from '@inertiajs/react';
import { Pencil, Plus, Trash2 } from 'lucide-react';
import {
    PaginationControls,
    type PaginatedData,
    SortableHeader,
    type TableFilters,
} from '@/components/data-table-controls';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import type { Auth } from '@/types';

type Author = {
    id: number;
    name: string;
};

type PostItem = {
    id: number;
    title: string;
    slug: string;
    status: 'draft' | 'published';
    published_at: string | null;
    created_at: string;
    author: Author | null;
    categories: {
        id: number;
        name: string;
    }[];
    tags: {
        id: number;
        name: string;
    }[];
};

type PageProps = {
    auth: Auth;
    posts: PaginatedData<PostItem>;
    filters: TableFilters;
};

export default function PostsIndex({ posts, filters }: PageProps) {
    const { auth } = usePage<PageProps>().props;
    const can = (permission: string) => auth.permissions.includes(permission);

    const destroy = (post: PostItem) => {
        if (!window.confirm(`Delete ${post.title}?`)) {
            return;
        }

        router.delete(`/posts/${post.id}`, { preserveScroll: true });
    };

    return (
        <>
            <Head title="Posts" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <Heading
                        title="Posts"
                        description="Manage blog and news posts."
                    />

                    {can('posts.create') && (
                        <Button asChild>
                            <Link href="/posts/create">
                                <Plus />
                                New post
                            </Link>
                        </Button>
                    )}
                </div>

                <div className="overflow-hidden rounded-lg border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-left">
                            <tr>
                                <SortableHeader
                                    basePath="/posts"
                                    column="title"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Post
                                </SortableHeader>
                                <th className="px-4 py-3 font-medium">
                                    Author
                                </th>
                                <th className="px-4 py-3 font-medium">
                                    Categories
                                </th>
                                <th className="px-4 py-3 font-medium">Tags</th>
                                <SortableHeader
                                    basePath="/posts"
                                    column="status"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Status
                                </SortableHeader>
                                <SortableHeader
                                    basePath="/posts"
                                    column="published_at"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Published
                                </SortableHeader>
                                <th className="w-28 px-4 py-3 text-right font-medium">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {posts.data.map((post) => (
                                <tr key={post.id}>
                                    <td className="px-4 py-3">
                                        <div className="font-medium">
                                            {post.title}
                                        </div>
                                        <div className="text-xs text-muted-foreground">
                                            {post.slug}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {post.author?.name ?? 'No author'}
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex flex-wrap gap-1.5">
                                            {post.categories.length ? (
                                                post.categories.map(
                                                    (category) => (
                                                        <Badge
                                                            key={category.id}
                                                            variant="secondary"
                                                        >
                                                            {category.name}
                                                        </Badge>
                                                    ),
                                                )
                                            ) : (
                                                <span className="text-muted-foreground">
                                                    No categories
                                                </span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex flex-wrap gap-1.5">
                                            {post.tags.length ? (
                                                post.tags.map((tag) => (
                                                    <Badge
                                                        key={tag.id}
                                                        variant="outline"
                                                    >
                                                        {tag.name}
                                                    </Badge>
                                                ))
                                            ) : (
                                                <span className="text-muted-foreground">
                                                    No tags
                                                </span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3">
                                        <Badge
                                            variant={
                                                post.status === 'published'
                                                    ? 'secondary'
                                                    : 'outline'
                                            }
                                        >
                                            {post.status}
                                        </Badge>
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {post.published_at
                                            ? new Date(
                                                  post.published_at,
                                              ).toLocaleDateString()
                                            : 'Not scheduled'}
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex justify-end gap-2">
                                            {can('posts.update') && (
                                                <Button
                                                    variant="outline"
                                                    size="icon"
                                                    asChild
                                                >
                                                    <Link
                                                        href={`/posts/${post.id}/edit`}
                                                    >
                                                        <Pencil />
                                                        <span className="sr-only">
                                                            Edit
                                                        </span>
                                                    </Link>
                                                </Button>
                                            )}
                                            {can('posts.delete') && (
                                                <Button
                                                    variant="destructive"
                                                    size="icon"
                                                    onClick={() =>
                                                        destroy(post)
                                                    }
                                                >
                                                    <Trash2 />
                                                    <span className="sr-only">
                                                        Delete
                                                    </span>
                                                </Button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    <PaginationControls
                        basePath="/posts"
                        filters={filters}
                        meta={posts}
                    />
                </div>
            </div>
        </>
    );
}

PostsIndex.layout = {
    breadcrumbs: [
        {
            title: 'Posts',
            href: '/posts',
        },
    ],
};
