<script lang="ts">
    import { page } from "$app/state";
    import Icon from "$lib/components/atoms/icon.svelte";
    import MaxWidthWrapper from "$lib/components/molecules/max-width-wrapper.svelte";
    import { Badge } from "$lib/components/ui/badge";
    import { Button, buttonVariants } from "$lib/components/ui/button";
    import * as Card from "$lib/components/ui/card";
    import { Separator } from "$lib/components/ui/separator";
    import { Skeleton } from "$lib/components/ui/skeleton";
    import { mainNavTree, WS_SCRCPY_URL } from "$lib/core/constants";
    import { deviceDetailsVM } from "$lib/domains/device/device-details.vm.svelte";
    import DeviceForm from "$lib/domains/device/device-form.svelte";
    import { deviceVM } from "$lib/domains/device/device.vm.svelte";
    import { breadcrumbs } from "$lib/global.stores";
    import ExternalLink from "@lucide/svelte/icons/external-link";
    import MonitorSmartphone from "@lucide/svelte/icons/monitor-smartphone";
    import RefreshCw from "@lucide/svelte/icons/refresh-cw";
    import Server from "@lucide/svelte/icons/server";
    import Smartphone from "@lucide/svelte/icons/smartphone";
    import { onMount } from "svelte";

    const deviceId = $derived(Number(page.params.id));
    const currentDevice = $derived(deviceDetailsVM.device);
    const streamUrl = $derived(deviceDetailsVM.streamUrl);
    let editTitle = $state("");
    let editVersion = $state("");
    let editHost = $state("");
    let editContainerId = $state("");
    let editWsPort = $state("");
    let editIsActive = $state(false);
    let editInUse = $state(false);
    let editStatus = $state(
        "offline" as "online" | "offline" | "busy" | "error",
    );

    function formatDate(value: Date | string | null | undefined): string {
        if (!value) return "—";
        return new Date(value).toLocaleString();
    }

    function statusVariant(
        status: string,
    ): "default" | "secondary" | "destructive" | "outline" {
        switch (status) {
            case "online":
                return "default";
            case "busy":
                return "outline";
            case "error":
                return "destructive";
            default:
                return "secondary";
        }
    }

    function setPageBreadcrumbs(title?: string) {
        breadcrumbs.set([
            mainNavTree[0],
            {
                title: title || `Device #${page.params.id}`,
                url: page.url.pathname,
            },
        ]);
    }

    async function loadDevice() {
        if (!Number.isFinite(deviceId) || deviceId <= 0) return;
        await deviceDetailsVM.fetchDevice(deviceId);
        setPageBreadcrumbs(deviceDetailsVM.device?.title);
    }

    function syncEditForm() {
        if (!currentDevice) return;
        editTitle = currentDevice.title;
        editVersion = currentDevice.version;
        editHost = currentDevice.host;
        editContainerId = currentDevice.containerId;
        editWsPort = currentDevice.wsPort;
        editIsActive = currentDevice.isActive;
        editInUse = currentDevice.inUse;
        editStatus = currentDevice.status as typeof editStatus;
    }

    async function handleUpdate(e: Event) {
        e.preventDefault();
        if (!currentDevice) return;

        const success = await deviceVM.updateDevice(currentDevice.id, {
            title: editTitle,
            version: editVersion,
            host: editHost,
            containerId: editContainerId,
            wsPort: editWsPort,
            isActive: editIsActive,
            inUse: editInUse,
            status: editStatus,
        });

        if (!success) return;
        await loadDevice();
    }

    onMount(async () => {
        setPageBreadcrumbs();
        await loadDevice();
    });

    $effect(() => {
        setPageBreadcrumbs(currentDevice?.title);
    });

    $effect(() => {
        if (!currentDevice) return;
        syncEditForm();
    });

    $effect(() => {
        if (!Number.isFinite(deviceId) || deviceId <= 0) return;
        if (deviceDetailsVM.currentId === deviceId) return;
        void loadDevice();
    });
</script>

<MaxWidthWrapper cls="space-y-4">
    <Card.Root>
        <Card.Header>
            <div
                class="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between"
            >
                <div class="space-y-2">
                    <div class="flex items-center gap-2">
                        <Icon icon={Smartphone} cls="h-5 w-5 text-primary" />
                        <Card.Title>
                            {currentDevice?.title ||
                                `Device #${page.params.id}`}
                        </Card.Title>
                    </div>

                    {#if currentDevice}
                        <div
                            class="text-muted-foreground flex flex-wrap items-center gap-2 text-sm"
                        >
                            <Badge
                                variant={statusVariant(currentDevice.status)}
                            >
                                {currentDevice.status}
                            </Badge>
                            <span>
                                {currentDevice.isActive ? "Active" : "Inactive"}
                            </span>
                            <span>
                                {currentDevice.inUse ? "In Use" : "Available"}
                            </span>
                            <span>Version {currentDevice.version}</span>
                        </div>
                    {/if}
                </div>

                <div class="flex flex-wrap items-center gap-2">
                    <Button
                        variant="outline"
                        size="sm"
                        onclick={() => void loadDevice()}
                        disabled={deviceDetailsVM.loading}
                    >
                        <Icon
                            icon={RefreshCw}
                            cls={`mr-2 h-4 w-4 ${deviceDetailsVM.loading ? "animate-spin" : ""}`}
                        />
                        Refresh
                    </Button>

                    {#if streamUrl}
                        <a
                            href={streamUrl}
                            target="_blank"
                            rel="noreferrer"
                            class={buttonVariants({
                                variant: "outline",
                                size: "sm",
                            })}
                        >
                            <Icon icon={ExternalLink} cls="mr-2 h-4 w-4" />
                            Open Stream
                        </a>
                    {/if}
                </div>
            </div>
        </Card.Header>

        <Card.Content class="space-y-4">
            {#if deviceDetailsVM.loading && !currentDevice}
                <div class="grid gap-4 xl:grid-cols-[340px_minmax(0,1fr)]">
                    <Card.Root>
                        <Card.Content class="space-y-3 pt-6">
                            <Skeleton class="h-6 w-40" />
                            <Skeleton class="h-16 w-full" />
                            <Skeleton class="h-16 w-full" />
                            <Skeleton class="h-16 w-full" />
                        </Card.Content>
                    </Card.Root>
                    <Card.Root>
                        <Card.Content class="space-y-3 pt-6">
                            <Skeleton class="h-6 w-48" />
                            <Skeleton class="h-10 w-full" />
                            <Skeleton class="h-10 w-full" />
                            <Skeleton class="h-10 w-full" />
                            <Skeleton class="h-10 w-full" />
                        </Card.Content>
                    </Card.Root>
                </div>
                <Card.Root>
                    <Card.Content class="pt-6">
                        <Skeleton class="h-[480px] w-full rounded-xl" />
                    </Card.Content>
                </Card.Root>
            {:else if !currentDevice}
                <div class="rounded-xl border border-dashed p-10 text-center">
                    <p class="text-sm font-medium">Device not found</p>
                    <p class="text-muted-foreground mt-1 text-sm">
                        This device could not be loaded from the admin API.
                    </p>
                </div>
            {:else}
                <!-- Top row: Metadata + Edit Device side by side -->
                <div class="grid gap-4 xl:grid-cols-[340px_minmax(0,1fr)]">
                    <Card.Root>
                        <Card.Header>
                            <div class="flex items-center gap-2">
                                <Icon
                                    icon={Server}
                                    cls="h-4 w-4 text-primary"
                                />
                                <Card.Title class="text-base">
                                    Metadata
                                </Card.Title>
                            </div>
                        </Card.Header>
                        <Card.Content class="space-y-4">
                            <div class="grid gap-3 text-sm">
                                <div>
                                    <p class="text-muted-foreground text-xs">
                                        Device ID
                                    </p>
                                    <p class="font-medium">
                                        {currentDevice.id}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-muted-foreground text-xs">
                                        Host
                                    </p>
                                    <p class="break-all font-mono text-xs">
                                        {currentDevice.host}
                                    </p>
                                </div>
                                <div class="grid grid-cols-2 gap-3">
                                    <div>
                                        <p
                                            class="text-muted-foreground text-xs"
                                        >
                                            WS Port
                                        </p>
                                        <p>{currentDevice.wsPort}</p>
                                    </div>
                                    <div>
                                        <p
                                            class="text-muted-foreground text-xs"
                                        >
                                            In Use
                                        </p>
                                        <p>
                                            {currentDevice.inUse ? "Yes" : "No"}
                                        </p>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-muted-foreground text-xs">
                                        Container ID
                                    </p>
                                    <p class="break-all font-mono text-xs">
                                        {currentDevice.containerId}
                                    </p>
                                </div>
                            </div>

                            <Separator />

                            <div class="grid gap-3 text-sm">
                                <div class="grid grid-cols-2 gap-3">
                                    <div>
                                        <p
                                            class="text-muted-foreground text-xs"
                                        >
                                            Created
                                        </p>
                                        <p class="text-xs">
                                            {formatDate(
                                                currentDevice.createdAt,
                                            )}
                                        </p>
                                    </div>
                                    <div>
                                        <p
                                            class="text-muted-foreground text-xs"
                                        >
                                            Updated
                                        </p>
                                        <p class="text-xs">
                                            {formatDate(
                                                currentDevice.updatedAt,
                                            )}
                                        </p>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-muted-foreground text-xs">
                                        Viewer URL
                                    </p>
                                    <p class="break-all font-mono text-xs">
                                        {streamUrl ||
                                            "Missing host configuration"}
                                    </p>
                                </div>
                            </div>
                        </Card.Content>
                    </Card.Root>

                    <Card.Root>
                        <Card.Header>
                            <div class="flex items-center gap-2">
                                <Icon
                                    icon={RefreshCw}
                                    cls="h-4 w-4 text-primary"
                                />
                                <Card.Title class="text-base">
                                    Edit Device
                                </Card.Title>
                            </div>
                            <Card.Description>
                                Manually update connection details or override
                                <code class="bg-muted rounded px-1 text-xs"
                                    >isActive</code
                                >,
                                <code class="bg-muted rounded px-1 text-xs"
                                    >inUse</code
                                >, and
                                <code class="bg-muted rounded px-1 text-xs"
                                    >status</code
                                > when needed.
                            </Card.Description>
                        </Card.Header>
                        <Card.Content>
                            <DeviceForm
                                fieldPrefix="detail-device"
                                bind:title={editTitle}
                                bind:version={editVersion}
                                bind:host={editHost}
                                bind:containerId={editContainerId}
                                bind:wsPort={editWsPort}
                                bind:isActive={editIsActive}
                                bind:inUse={editInUse}
                                bind:status={editStatus}
                                submitLabel="Update Device"
                                submitting={deviceVM.updating}
                                showAdvanced={true}
                                onsubmit={handleUpdate}
                            />
                        </Card.Content>
                    </Card.Root>
                </div>

                <!-- Full-width Live Device Session below -->
                <Card.Root class="overflow-hidden">
                    <Card.Header>
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <Icon
                                    icon={MonitorSmartphone}
                                    cls="h-4 w-4 text-primary"
                                />
                                <Card.Title class="text-base">
                                    Live Device Session
                                </Card.Title>
                            </div>
                            <div class="flex items-center gap-1">
                                <a
                                    href={WS_SCRCPY_URL}
                                    target="_blank"
                                    rel="noreferrer"
                                    class={buttonVariants({
                                        variant: "ghost",
                                        size: "sm",
                                    })}
                                >
                                    <Icon
                                        icon={ExternalLink}
                                        cls="mr-1.5 h-3.5 w-3.5"
                                    />
                                    Device Viewer Home
                                </a>
                                {#if streamUrl}
                                    <a
                                        href={streamUrl}
                                        target="_blank"
                                        rel="noreferrer"
                                        class={buttonVariants({
                                            variant: "ghost",
                                            size: "sm",
                                        })}
                                    >
                                        <Icon
                                            icon={ExternalLink}
                                            cls="mr-1.5 h-3.5 w-3.5"
                                        />
                                        Pop out
                                    </a>
                                {/if}
                            </div>
                        </div>
                        <Card.Description>
                            Full interactive device access is embedded here so
                            admins do not need to leave the dashboard.
                        </Card.Description>
                    </Card.Header>
                    <Card.Content>
                        {#if streamUrl}
                            <div
                                class="bg-muted overflow-hidden rounded-xl border"
                            >
                                <iframe
                                    title={`Live stream for ${currentDevice.title}`}
                                    src={streamUrl}
                                    class="h-[75vh] min-h-[480px] w-full bg-black"
                                    allow="autoplay; clipboard-read; clipboard-write"
                                ></iframe>
                            </div>
                        {:else}
                            <div
                                class="rounded-xl border border-dashed p-10 text-center"
                            >
                                <p class="text-sm font-medium">
                                    Stream URL unavailable
                                </p>
                                <p class="text-muted-foreground mt-1 text-sm">
                                    Save a valid ws-scrcpy host or host/port for
                                    this device to embed the live session here.
                                </p>
                            </div>
                        {/if}
                    </Card.Content>
                </Card.Root>
            {/if}
        </Card.Content>
    </Card.Root>
</MaxWidthWrapper>
