import { Head, Link, usePage } from '@inertiajs/react';
import { Pencil, Plus } from 'lucide-react';
import PostController from '@/actions/App/Http/Controllers/Admin/PostController';
import {
    MissingTranslations,
    PostStatusBadge,
} from '@/components/admin/badges';
import type { PostStatus } from '@/components/admin/badges';
import { EmptyState } from '@/components/admin/empty-state';
import { ExternalLink } from '@/components/admin/external-link';
import {
    ListFilters,
    SearchFilter,
    SelectFilter,
} from '@/components/admin/list-filters';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { Pagination } from '@/components/admin/pagination';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useListFilters } from '@/hooks/use-list-filters';
import type { Paginated } from '@/types';

type Post = {
    id: number;
    title: string;
    /** Name of the category the post belongs to; null without one. */
    category: string | null;
    status: PostStatus;
    /** Publish date in the site's time zone; null while the post has none. */
    publishedAt: string | null;
    /** Languages the post has no title or slug in. */
    missing: string[];
    /** Address of the live post; null while it is not on the site. */
    url: string | null;
};

type Filters = {
    search: string;
    category: string;
    status: string;
    missing: string;
};

type Props = {
    posts: Paginated<Post>;
    filters: Filters;
    categories: { id: number; name: string }[];
};

export default function PostIndex({ posts, filters, categories }: Props) {
    const { locales } = usePage().props;
    const { apply, reset, active } = useListFilters(
        PostController.index().url,
        filters,
    );

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

            <PageContainer>
                <PageHeader
                    title="Blog"
                    description="Sitedeki blog yazıları; en yeni yazı en üsttedir. Yayın tarihi ileride olan yazı “Zamanlandı” olarak bekler ve tarihi geldiğinde kendiliğinden yayına girer."
                    actions={
                        <Button asChild size="sm">
                            <Link href={PostController.create()}>
                                <Plus />
                                Yeni yazı
                            </Link>
                        </Button>
                    }
                />

                <ListFilters active={active} onReset={reset}>
                    <SearchFilter
                        key={filters.search}
                        value={filters.search}
                        onSearch={(search) => apply({ search })}
                        label="Yazı başlığında ara"
                    />
                    <SelectFilter
                        value={filters.category}
                        onChange={(category) => apply({ category })}
                        label="Kategori"
                        allLabel="Tüm kategoriler"
                        options={categories.map((category) => ({
                            value: String(category.id),
                            label: category.name,
                        }))}
                    />
                    <SelectFilter
                        value={filters.status}
                        onChange={(status) => apply({ status })}
                        label="Yayın durumu"
                        allLabel="Tüm durumlar"
                        options={[
                            { value: 'live', label: 'Yayında' },
                            { value: 'scheduled', label: 'Zamanlandı' },
                            { value: 'draft', label: 'Taslak' },
                        ]}
                    />
                    <SelectFilter
                        value={filters.missing}
                        onChange={(missing) => apply({ missing })}
                        label="Çeviri durumu"
                        allLabel="Çevirisi tam ve eksik"
                        // The default language is always present.
                        options={locales
                            .filter((locale) => !locale.default)
                            .map((locale) => ({
                                value: locale.code,
                                label: `${locale.name} çevirisi eksik`,
                            }))}
                    />
                </ListFilters>

                {posts.data.length === 0 ? (
                    <EmptyState
                        title={
                            active
                                ? 'Bu filtrelere uyan yazı yok'
                                : 'Henüz yazı yok'
                        }
                        description={
                            active
                                ? 'Aramayı ya da filtreleri değiştirmeyi deneyin.'
                                : 'İlk yazıyı ekleyerek başlayın. Sitede “Blog” bağlantısı, ilk yazı yayına girdiğinde görünür.'
                        }
                        action={
                            !active && (
                                <Button asChild size="sm">
                                    <Link href={PostController.create()}>
                                        <Plus />
                                        Yeni yazı
                                    </Link>
                                </Button>
                            )
                        }
                    />
                ) : (
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="pl-4">
                                        Başlık
                                    </TableHead>
                                    <TableHead>Kategori</TableHead>
                                    <TableHead>Durum</TableHead>
                                    <TableHead>Yayın tarihi</TableHead>
                                    <TableHead>Sitede</TableHead>
                                    <TableHead className="pr-4">
                                        <span className="sr-only">
                                            İşlemler
                                        </span>
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {posts.data.map((post) => (
                                    <TableRow key={post.id}>
                                        <TableCell className="pl-4">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <Link
                                                    href={PostController.edit(
                                                        post.id,
                                                    )}
                                                    className="font-medium underline-offset-4 hover:underline"
                                                >
                                                    {post.title}
                                                </Link>
                                                <MissingTranslations
                                                    locales={post.missing}
                                                />
                                            </div>
                                        </TableCell>
                                        <TableCell className="text-muted-foreground">
                                            {post.category ?? '—'}
                                        </TableCell>
                                        <TableCell>
                                            <PostStatusBadge
                                                status={post.status}
                                            />
                                        </TableCell>
                                        <TableCell className="whitespace-nowrap text-muted-foreground tabular-nums">
                                            {post.publishedAt ?? '—'}
                                        </TableCell>
                                        <TableCell>
                                            {post.url ? (
                                                <ExternalLink
                                                    href={post.url}
                                                    className="text-muted-foreground"
                                                >
                                                    Sayfayı aç
                                                </ExternalLink>
                                            ) : (
                                                <span className="text-muted-foreground">
                                                    —
                                                </span>
                                            )}
                                        </TableCell>
                                        <TableCell className="pr-4 text-right">
                                            <Button
                                                asChild
                                                variant="ghost"
                                                size="sm"
                                            >
                                                <Link
                                                    href={PostController.edit(
                                                        post.id,
                                                    )}
                                                >
                                                    <Pencil />
                                                    Düzenle
                                                </Link>
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                )}

                <Pagination paginator={posts} />
            </PageContainer>
        </>
    );
}

PostIndex.layout = {
    breadcrumbs: [
        {
            title: 'Blog',
            href: PostController.index(),
        },
    ],
};
