import { Head, Link } from '@inertiajs/react';
import SensorHistoryController from '@/actions/App/Http/Controllers/SensorHistoryController';
import Heading from '@/components/heading';
import SensorMap from '@/components/sensor-map';
import WindDirectionIndicator from '@/components/wind-direction-indicator';
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 { dashboard } from '@/routes';

type DashboardSensor = {
    id: number;
    name: string;
    friendly_name: string | null;
    display_name: string;
    device_id: string;
    description: string | null;
    image_url: string | null;
    latitude: number | null;
    longitude: number | null;
    sensor_type_name: string | null;
    latest_data: Record<string, unknown>;
    latest_received_at: string | null;
};

function isWindDirectionMetric(key: string, value: unknown): value is number {
    return key === 'wind_direction' && typeof value === 'number';
}

export default function Dashboard({
    sensors,
    stats,
}: {
    sensors: DashboardSensor[];
    stats: {
        sensor_count: number;
        active_sensor_types: number;
        recent_updates: number;
    };
}) {
    const sensorsWithLocations = sensors.filter(
        (sensor): sensor is DashboardSensor & { latitude: number; longitude: number } =>
            sensor.latitude !== null && sensor.longitude !== null,
    );

    return (
        <>
            <Head title="Dashboard" />
            <div className="space-y-6 p-4">
                <Heading
                    title="Sensor dashboard"
                    description="Review the latest decoded readings for every registered sensor."
                />

                <div className="grid gap-4 md:grid-cols-3">
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Registered sensors</CardDescription>
                            <CardTitle className="text-3xl">{stats.sensor_count}</CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Sensor types in use</CardDescription>
                            <CardTitle className="text-3xl">{stats.active_sensor_types}</CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Sensors with readings</CardDescription>
                            <CardTitle className="text-3xl">{stats.recent_updates}</CardTitle>
                        </CardHeader>
                    </Card>
                </div>

                <Card>
                    <CardHeader className="gap-1">
                        <CardTitle>Sensor map</CardTitle>
                        <CardDescription>
                            A live view of every sensor with stored coordinates.
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <SensorMap sensors={sensorsWithLocations} />
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Latest sensor data</CardTitle>
                        <CardDescription>
                            The most recent decoded payload stored for each sensor.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {sensors.length === 0 ? (
                            <div className="rounded-lg border border-dashed p-6 text-sm text-muted-foreground">
                                No sensors have been created yet.
                            </div>
                        ) : (
                            <div className="grid gap-4 xl:grid-cols-2">
                                {sensors.map((sensor) => (
                                    <article
                                        key={sensor.id}
                                        className="rounded-[1.25rem] border border-border/70 bg-card p-4"
                                    >
                                        <div className="flex gap-4">
                                            <div className="flex size-20 shrink-0 items-center justify-center overflow-hidden rounded-2xl border bg-muted">
                                                {sensor.image_url ? (
                                                    <img
                                                        src={sensor.image_url}
                                                        alt={sensor.display_name}
                                                        className="h-full w-full object-cover"
                                                    />
                                                ) : (
                                                    <span className="px-3 text-center text-xs text-muted-foreground">
                                                        No image
                                                    </span>
                                                )}
                                            </div>

                                            <div className="min-w-0 flex-1 space-y-2">
                                                <div className="flex flex-wrap items-start justify-between gap-2">
                                                    <div className="min-w-0">
                                                        <h2 className="truncate font-medium">
                                                            {sensor.display_name}
                                                        </h2>
                                                        {sensor.friendly_name ? (
                                                            <p className="text-xs text-muted-foreground">
                                                                Internal name: {sensor.name}
                                                            </p>
                                                        ) : null}
                                                    </div>

                                                    {sensor.sensor_type_name ? (
                                                        <Badge variant="secondary">
                                                            {sensor.sensor_type_name}
                                                        </Badge>
                                                    ) : null}
                                                </div>

                                                <div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-2">
                                                    <p>Device ID: {sensor.device_id}</p>
                                                    <p>
                                                        Last update:{' '}
                                                        {sensor.latest_received_at ?? 'No readings yet'}
                                                    </p>
                                                    <p>
                                                        Coordinates:{' '}
                                                        {sensor.latitude !== null &&
                                                        sensor.longitude !== null
                                                            ? `${sensor.latitude.toFixed(4)}, ${sensor.longitude.toFixed(4)}`
                                                            : 'Not set'}
                                                    </p>
                                                </div>

                                                <p className="line-clamp-2 text-sm text-muted-foreground">
                                                    {sensor.description ??
                                                        'No description provided.'}
                                                </p>
                                            </div>
                                        </div>

                                        <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                                            {Object.keys(sensor.latest_data).length === 0 ? (
                                                <div className="rounded-xl border border-dashed p-4 text-sm text-muted-foreground sm:col-span-2 xl:col-span-3">
                                                    No decoded values are stored for this sensor yet.
                                                </div>
                                            ) : (
                                                Object.entries(sensor.latest_data)
                                                    .slice(0, 6)
                                                    .map(([key, value]) => (
                                                        <div
                                                            key={key}
                                                            className="rounded-xl bg-muted/70 p-3"
                                                        >
                                                            <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
                                                                {key.replaceAll('_', ' ')}
                                                            </div>
                                                            <div className="mt-1 text-base font-semibold">
                                                                {isWindDirectionMetric(key, value) ? (
                                                                    <WindDirectionIndicator
                                                                        degrees={value}
                                                                        size="sm"
                                                                    />
                                                                ) : typeof value === 'object' ? (
                                                                    JSON.stringify(value)
                                                                ) : (
                                                                    formatSensorMetricValue(
                                                                        key,
                                                                        value,
                                                                    )
                                                                )}
                                                            </div>
                                                        </div>
                                                    ))
                                            )}
                                        </div>

                                        <div className="mt-4">
                                            <Button variant="outline" size="sm" asChild>
                                                <Link href={SensorHistoryController(sensor.id)}>
                                                    View history
                                                </Link>
                                            </Button>
                                        </div>
                                    </article>
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

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