import { Head, Link, usePage } from '@inertiajs/react';
import type { InertiaLinkProps } from '@inertiajs/react';
import { ArrowRight, CircleCheck, TriangleAlert } from 'lucide-react';
import CategoryController from '@/actions/App/Http/Controllers/Admin/CategoryController';
import LeadController from '@/actions/App/Http/Controllers/Admin/LeadController';
import PostController from '@/actions/App/Http/Controllers/Admin/PostController';
import TreatmentController from '@/actions/App/Http/Controllers/Admin/TreatmentController';
import { LeadStatusBadge } from '@/components/admin/badges';
import { EmptyState } from '@/components/admin/empty-state';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { dashboard } from '@/routes';

type Href = NonNullable<InertiaLinkProps['href']>;

type Props = {
    stats: {
        categories: number;
        treatments: number;
        /** Blog posts that are on the site right now. */
        posts: number;
        unreviewed: number;
        newLeads: number;
    };
    latestLeads: {
        id: number;
        name: string;
        /** Null for requests kept in the CRM. */
        phone: string | null;
        treatment: string | null;
        status: { value: string; label: string };
        createdAt: string | null;
    }[];
    /**
     * Faults in how this copy is installed (wrong site address, debugging
     * left on, SSR process down…). Empty on a developer machine.
     */
    setup: {
        key: string;
        level: 'warning' | 'error';
        label: string;
        detail: string;
    }[];
    /** What is still missing before the content is complete. */
    gaps: {
        type: 'translation' | 'review';
        locale: string | null;
        count: number;
        treatments: { id: number; name: string }[];
    }[];
};

export default function Dashboard({ stats, latestLeads, setup, gaps }: Props) {
    const { locales } = usePage().props;

    const tiles: { label: string; value: number; href: Href }[] = [
        {
            label: 'Yayındaki kategori',
            value: stats.categories,
            href: CategoryController.index(),
        },
        {
            label: 'Yayındaki işlem',
            value: stats.treatments,
            href: TreatmentController.index({ query: { published: '1' } }),
        },
        {
            label: 'Yayındaki yazı',
            value: stats.posts,
            href: PostController.index({ query: { status: 'live' } }),
        },
        {
            label: 'Hekim onayı girilmemiş işlem',
            value: stats.unreviewed,
            href: TreatmentController.index({ query: { reviewed: '0' } }),
        },
        {
            label: 'Yeni talep',
            value: stats.newLeads,
            href: LeadController.index({ query: { status: 'new' } }),
        },
    ];

    const gapLists = gaps.map((gap) => {
        if (gap.type === 'review') {
            return {
                ...gap,
                title: 'Hekim onayı girilmemiş işlemler',
                description:
                    'Onaylayan hekim girilmeden işlem sayfasında “hekim tarafından gözden geçirildi” bilgisi gösterilmez.',
                href: TreatmentController.index({ query: { reviewed: '0' } }),
            };
        }

        const language =
            locales.find((locale) => locale.code === gap.locale)?.name ??
            gap.locale ??
            '';

        return {
            ...gap,
            title: `${language} çevirisi eksik işlemler`,
            description: `Adı ya da adres uzantısı ${language} olarak girilmemiş işlemler ${language} sitede yer almaz.`,
            href: TreatmentController.index({
                query: { missing: gap.locale ?? '' },
            }),
        };
    });

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

            <PageContainer>
                <PageHeader
                    title="Pano"
                    description="Sitenin içerik durumu ve son gelen talepler."
                />

                {setup.length > 0 ? (
                    <section
                        aria-labelledby="setup-heading"
                        className="rounded-xl border border-destructive/40 bg-destructive/5 p-5"
                    >
                        <h2
                            id="setup-heading"
                            className="flex items-center gap-2 leading-none font-semibold"
                        >
                            <TriangleAlert
                                aria-hidden="true"
                                className="size-4 text-destructive"
                            />
                            Kurulum uyarıları
                        </h2>
                        <p className="mt-2 text-sm text-muted-foreground">
                            Bu kopyanın sunucu ayarlarında düzeltilmesi
                            gerekenler var. Ziyaretçi fark etmez, ama arama
                            motorlarını ve sayfa hızını etkiler. Sunucuda{' '}
                            <code className="rounded bg-muted px-1 py-0.5 text-xs">
                                php artisan site:doctor
                            </code>{' '}
                            aynı listeyi verir.
                        </p>
                        <ul className="mt-4 space-y-3 text-sm">
                            {setup.map((item) => (
                                <li key={item.key}>
                                    <span className="font-medium">
                                        {item.label}:
                                    </span>{' '}
                                    <span className="text-muted-foreground">
                                        {item.detail}
                                    </span>
                                </li>
                            ))}
                        </ul>
                    </section>
                ) : null}

                {/* Five tiles: in two columns the last one fills its row. */}
                <div className="grid grid-cols-2 gap-4 xl:grid-cols-5">
                    {tiles.map((tile) => (
                        <Link
                            key={tile.label}
                            href={tile.href}
                            className="group rounded-xl border bg-card p-5 shadow-sm transition-colors outline-none last:col-span-2 hover:border-foreground/30 focus-visible:ring-[3px] focus-visible:ring-ring/50 xl:last:col-span-1"
                        >
                            <p className="text-3xl font-semibold tabular-nums">
                                {tile.value}
                            </p>
                            <p className="mt-1 flex items-center gap-1 text-sm text-muted-foreground">
                                {tile.label}
                                <ArrowRight
                                    aria-hidden="true"
                                    className="size-3.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"
                                />
                            </p>
                        </Link>
                    ))}
                </div>

                <div className="grid grid-cols-1 items-start gap-6 xl:grid-cols-5">
                    <Card className="xl:col-span-3">
                        <CardHeader>
                            <div className="flex items-center justify-between gap-2">
                                <h2 className="leading-none font-semibold">
                                    Son talepler
                                </h2>
                                <Link
                                    href={LeadController.index()}
                                    className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
                                >
                                    Tüm talepler
                                </Link>
                            </div>
                        </CardHeader>
                        <CardContent>
                            {latestLeads.length === 0 ? (
                                <EmptyState
                                    title="Henüz talep yok"
                                    description="Sitedeki iletişim formundan gönderilen talepler burada listelenir."
                                />
                            ) : (
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Ad soyad</TableHead>
                                            <TableHead>
                                                İlgilendiği işlem
                                            </TableHead>
                                            <TableHead>Durum</TableHead>
                                            <TableHead className="text-right">
                                                Tarih
                                            </TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {latestLeads.map((lead) => (
                                            <TableRow key={lead.id}>
                                                <TableCell>
                                                    <Link
                                                        href={LeadController.show(
                                                            lead.id,
                                                        )}
                                                        className="font-medium underline-offset-4 hover:underline"
                                                    >
                                                        {lead.name}
                                                    </Link>
                                                    {lead.phone && (
                                                        <p className="text-xs text-muted-foreground">
                                                            {lead.phone}
                                                        </p>
                                                    )}
                                                </TableCell>
                                                <TableCell className="text-muted-foreground">
                                                    {lead.treatment ?? '—'}
                                                </TableCell>
                                                <TableCell>
                                                    <LeadStatusBadge
                                                        status={
                                                            lead.status.value
                                                        }
                                                        label={
                                                            lead.status.label
                                                        }
                                                    />
                                                </TableCell>
                                                <TableCell className="text-right whitespace-nowrap text-muted-foreground tabular-nums">
                                                    {lead.createdAt}
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            )}
                        </CardContent>
                    </Card>

                    <Card className="xl:col-span-2">
                        <CardHeader>
                            <h2 className="leading-none font-semibold">
                                Eksikler
                            </h2>
                            <p className="text-sm text-muted-foreground">
                                İçeriğin tamamlanması için kalanlar.
                            </p>
                        </CardHeader>
                        <CardContent className="grid grid-cols-1 gap-6">
                            {gapLists.map((gap) => (
                                <section
                                    key={gap.title}
                                    className="grid grid-cols-1 gap-2"
                                >
                                    <div className="flex items-center justify-between gap-2">
                                        <h3 className="text-sm font-medium">
                                            {gap.title}
                                        </h3>
                                        {gap.count === 0 ? (
                                            <CircleCheck
                                                aria-hidden="true"
                                                className="size-4 text-emerald-600"
                                            />
                                        ) : (
                                            <Badge variant="secondary">
                                                {gap.count}
                                            </Badge>
                                        )}
                                    </div>

                                    {gap.count === 0 ? (
                                        <p className="text-sm text-muted-foreground">
                                            Eksik yok.
                                        </p>
                                    ) : (
                                        <>
                                            <p className="text-xs text-muted-foreground">
                                                {gap.description}
                                            </p>
                                            <ul className="grid grid-cols-1 gap-1 text-sm">
                                                {gap.treatments.map(
                                                    (treatment) => (
                                                        <li key={treatment.id}>
                                                            <Link
                                                                href={TreatmentController.edit(
                                                                    treatment.id,
                                                                )}
                                                                className="underline-offset-4 hover:underline"
                                                            >
                                                                {treatment.name}
                                                            </Link>
                                                        </li>
                                                    ),
                                                )}
                                            </ul>
                                            <Link
                                                href={gap.href}
                                                className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
                                            >
                                                Tümünü listele ({gap.count})
                                            </Link>
                                        </>
                                    )}
                                </section>
                            ))}
                        </CardContent>
                    </Card>
                </div>
            </PageContainer>
        </>
    );
}

Dashboard.layout = {
    breadcrumbs: [
        {
            title: 'Pano',
            href: dashboard(),
        },
    ],
};
