import { Head } from '@inertiajs/react';
import DiagnosticsController from '@/actions/App/Http/Controllers/Admin/DiagnosticsController';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';

type LogSource = {
    name: string;
    path: string;
    status: string;
    entries: string[];
};

type AuditSummary = {
    users: number;
    active_sessions: number;
    failed_jobs: number;
    webhook_messages: number;
};

type SessionAudit = {
    user_name: string | null;
    user_email: string | null;
    ip_address: string | null;
    user_agent: string | null;
    last_activity: string | null;
};

type UserAudit = {
    id: number;
    name: string;
    email: string;
    role: string;
    created_at: string | null;
    updated_at: string | null;
};

type FailedJobAudit = {
    id: number;
    uuid: string;
    connection: string;
    queue: string;
    failed_at: string | null;
    exception_preview: string;
};

type WebhookMessageAudit = {
    id: number;
    message_id: string;
    device_id: string | null;
    created_at: string | null;
};

type Audit = {
    summary: AuditSummary;
    sessions: SessionAudit[];
    users: UserAudit[];
    failed_jobs: FailedJobAudit[];
    webhook_messages: WebhookMessageAudit[];
};

function EmptyState({ children }: { children: string }) {
    return (
        <div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
            {children}
        </div>
    );
}

function formatLabel(label: string): string {
    return label.replaceAll('_', ' ');
}

export default function Diagnostics({ logs, audit }: { logs: LogSource[]; audit: Audit }) {
    return (
        <>
            <Head title="Logs & audit" />

            <div className="space-y-6 p-4">
                <Heading
                    title="Logs & audit"
                    description="Review application logs, Apache logs, sessions, failed jobs, users, and webhook activity."
                />

                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    {Object.entries(audit.summary).map(([key, value]) => (
                        <Card key={key}>
                            <CardHeader className="pb-2">
                                <CardDescription className="capitalize">
                                    {formatLabel(key)}
                                </CardDescription>
                                <CardTitle className="text-2xl">{value}</CardTitle>
                            </CardHeader>
                        </Card>
                    ))}
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Logs</CardTitle>
                        <CardDescription>
                            Showing configured Laravel and Apache log sources.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="grid gap-4 xl:grid-cols-3">
                        {logs.map((log) => (
                            <section key={log.name} className="space-y-3 rounded-lg border p-4">
                                <div className="space-y-1">
                                    <div className="flex flex-wrap items-center gap-2">
                                        <h2 className="text-sm font-medium">{log.name}</h2>
                                        <Badge
                                            variant={log.entries.length > 0 ? 'secondary' : 'outline'}
                                        >
                                            {log.entries.length} entries
                                        </Badge>
                                    </div>
                                    <p className="break-all text-xs text-muted-foreground">
                                        {log.path}
                                    </p>
                                    <p className="text-xs text-muted-foreground">{log.status}</p>
                                </div>

                                {log.entries.length === 0 ? (
                                    <EmptyState>No readable entries are available.</EmptyState>
                                ) : (
                                    <pre className="max-h-96 overflow-auto rounded-lg bg-muted p-3 text-xs whitespace-pre-wrap">
                                        {log.entries.join('\n')}
                                    </pre>
                                )}
                            </section>
                        ))}
                    </CardContent>
                </Card>

                <div className="grid gap-6 xl:grid-cols-2">
                    <Card>
                        <CardHeader>
                            <CardTitle>Active sessions</CardTitle>
                            <CardDescription>
                                Recent session records from the database session store.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {audit.sessions.length === 0 ? (
                                <EmptyState>No active sessions were found.</EmptyState>
                            ) : (
                                audit.sessions.map((session, index) => (
                                    <article key={`${session.user_email}-${index}`} className="rounded-lg border p-3">
                                        <div className="flex flex-wrap items-start justify-between gap-3">
                                            <div>
                                                <h2 className="text-sm font-medium">
                                                    {session.user_name ?? 'Guest session'}
                                                </h2>
                                                <p className="text-xs text-muted-foreground">
                                                    {session.user_email ?? session.ip_address ?? 'Unknown source'}
                                                </p>
                                            </div>
                                            <Badge variant="outline">
                                                {session.last_activity ?? 'Unknown time'}
                                            </Badge>
                                        </div>
                                        {session.user_agent ? (
                                            <p className="mt-2 line-clamp-2 text-xs text-muted-foreground">
                                                {session.user_agent}
                                            </p>
                                        ) : null}
                                    </article>
                                ))
                            )}
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>User audit</CardTitle>
                            <CardDescription>
                                Recent user records ordered by last update.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {audit.users.map((user) => (
                                <article key={user.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                                    <div>
                                        <h2 className="text-sm font-medium">{user.name}</h2>
                                        <p className="text-xs text-muted-foreground">{user.email}</p>
                                    </div>
                                    <div className="flex flex-col items-start gap-1 sm:items-end">
                                        <Badge variant="secondary">{formatLabel(user.role)}</Badge>
                                        <p className="text-xs text-muted-foreground">
                                            Updated {user.updated_at ?? 'recently'}
                                        </p>
                                    </div>
                                </article>
                            ))}
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Failed jobs</CardTitle>
                            <CardDescription>
                                Queue failures with shortened exception previews.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {audit.failed_jobs.length === 0 ? (
                                <EmptyState>No failed jobs were found.</EmptyState>
                            ) : (
                                audit.failed_jobs.map((job) => (
                                    <article key={job.id} className="space-y-2 rounded-lg border p-3">
                                        <div className="flex flex-wrap items-center justify-between gap-2">
                                            <h2 className="text-sm font-medium">{job.uuid}</h2>
                                            <Badge variant="outline">{job.failed_at ?? 'Unknown time'}</Badge>
                                        </div>
                                        <p className="text-xs text-muted-foreground">
                                            {job.connection} / {job.queue}
                                        </p>
                                        <pre className="overflow-x-auto rounded bg-muted p-2 text-xs">
                                            {job.exception_preview}
                                        </pre>
                                    </article>
                                ))
                            )}
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Webhook audit</CardTitle>
                            <CardDescription>
                                Recent stored The Things Stack webhook messages.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {audit.webhook_messages.length === 0 ? (
                                <EmptyState>No webhook messages were found.</EmptyState>
                            ) : (
                                audit.webhook_messages.map((message) => (
                                    <article key={message.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                                        <div>
                                            <h2 className="text-sm font-medium">
                                                {message.message_id}
                                            </h2>
                                            <p className="text-xs text-muted-foreground">
                                                {message.device_id ?? 'No device id'}
                                            </p>
                                        </div>
                                        <Badge variant="outline">
                                            {message.created_at ?? 'Unknown time'}
                                        </Badge>
                                    </article>
                                ))
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </>
    );
}

Diagnostics.layout = {
    breadcrumbs: [
        {
            title: 'Logs & audit',
            href: DiagnosticsController(),
        },
    ],
};
