import { Head } from '@inertiajs/react';
import WebhookMessageController from '@/actions/App/Http/Controllers/Admin/WebhookMessageController';
import Heading from '@/components/heading';
import { formatSensorMetricValue } from '@/lib/sensor-metrics';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
type WebhookMessage = {
    id: number;
    message_id: string;
    device_id: string | null;
    sensor_type_name: string | null;
    frm_payload: string;
    network_ids: Record<string, unknown>;
    decoded_payload: Record<string, unknown>;
    created_at: string | null;
};

export default function Messages({
    messages,
}: {
    messages: WebhookMessage[];
}) {
    return (
        <>
            <Head title="Incoming messages" />

            <div className="space-y-6 p-4">
                <Heading
                    title="Incoming webhook messages"
                    description="Review the latest The Things Stack uplinks captured by the webhook endpoint."
                />

                <Card>
                    <CardHeader>
                        <CardTitle>Recent messages</CardTitle>
                        <CardDescription>
                            Showing the 50 most recent stored webhook records.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {messages.length === 0 ? (
                            <div className="rounded-lg border border-dashed p-6 text-sm text-muted-foreground">
                                No webhook messages have been received yet.
                            </div>
                        ) : (
                            messages.map((message) => (
                                <article key={message.id} className="rounded-xl border p-4">
                                    <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                                        <div className="space-y-1">
                                            <h2 className="font-medium">{message.message_id}</h2>
                                            <p className="text-sm text-muted-foreground">
                                                Received {message.created_at ?? 'recently'}
                                            </p>
                                            {message.device_id ? (
                                                <p className="text-xs text-muted-foreground">
                                                    Device: {message.device_id}
                                                </p>
                                            ) : null}
                                        </div>

                                        <div className="flex flex-wrap gap-2">
                                            <Badge variant="outline">frm_payload</Badge>
                                            {message.sensor_type_name ? (
                                                <Badge variant="secondary">
                                                    {message.sensor_type_name}
                                                </Badge>
                                            ) : null}
                                        </div>
                                    </div>

                                    <div className="mt-4 grid gap-4 lg:grid-cols-3">
                                        <section className="space-y-2">
                                            <h3 className="text-sm font-medium">Payload</h3>
                                            <pre className="overflow-x-auto rounded-lg bg-muted p-3 text-xs">
                                                {message.frm_payload}
                                            </pre>
                                        </section>

                                        <section className="space-y-2">
                                            <h3 className="text-sm font-medium">Network IDs</h3>
                                            <pre className="overflow-x-auto rounded-lg bg-muted p-3 text-xs">
                                                {JSON.stringify(message.network_ids, null, 2)}
                                            </pre>
                                        </section>

                                        <section className="space-y-2">
                                            <h3 className="text-sm font-medium">Decoded payload</h3>
                                            <Dialog>
                                                <DialogTrigger asChild>
                                                    <Button variant="outline" size="sm">
                                                        View decoded data
                                                    </Button>
                                                </DialogTrigger>
                                                <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-3xl">
                                                    <DialogHeader>
                                                        <DialogTitle>
                                                            Decoded payload
                                                        </DialogTitle>
                                                        <DialogDescription>
                                                            {message.device_id
                                                                ? `Decoded frm_payload for ${message.device_id}.`
                                                                : 'Decoded frm_payload for this incoming message.'}
                                                        </DialogDescription>
                                                    </DialogHeader>

                                                    <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">
                                                        <section className="space-y-2">
                                                            <h3 className="text-sm font-medium">
                                                                Raw payload
                                                            </h3>
                                                            <pre className="overflow-x-auto rounded-lg bg-muted p-3 text-xs">
                                                                {message.frm_payload}
                                                            </pre>
                                                        </section>

                                                        <section className="space-y-2">
                                                            <h3 className="text-sm font-medium">
                                                                Decoded data
                                                            </h3>
                                                            {Object.keys(message.decoded_payload)
                                                                .length === 0 ? (
                                                                <div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
                                                                    No decoded values available.
                                                                </div>
                                                            ) : (
                                                                <div className="grid gap-2 rounded-lg bg-muted p-3 text-xs">
                                                                    {Object.entries(
                                                                        message.decoded_payload,
                                                                    ).map(([key, value]) => (
                                                                        <div
                                                                            key={key}
                                                                            className="flex items-start justify-between gap-3 border-b border-border/60 pb-2 last:border-b-0 last:pb-0"
                                                                        >
                                                                            <span className="uppercase tracking-wide text-muted-foreground">
                                                                                {key.replaceAll(
                                                                                    '_',
                                                                                    ' ',
                                                                                )}
                                                                            </span>
                                                                            <span className="text-right font-medium">
                                                                                {formatSensorMetricValue(
                                                                                    key,
                                                                                    value,
                                                                                )}
                                                                            </span>
                                                                        </div>
                                                                    ))}
                                                                </div>
                                                            )}
                                                        </section>
                                                    </div>
                                                </DialogContent>
                                            </Dialog>
                                        </section>
                                    </div>
                                </article>
                            ))
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

Messages.layout = {
    breadcrumbs: [
        {
            title: 'Incoming messages',
            href: WebhookMessageController.index(),
        },
    ],
};
