<script lang="ts">
    import Icon from "$lib/components/atoms/icon.svelte";
    import * as AlertDialog from "$lib/components/ui/alert-dialog/index.js";
    import { Button, buttonVariants } from "$lib/components/ui/button";
    import * as Card from "$lib/components/ui/card";
    import * as Dialog from "$lib/components/ui/dialog";
    import { Input } from "$lib/components/ui/input";
    import { Label } from "$lib/components/ui/label";
    import * as Table from "$lib/components/ui/table";
    import MaxWidthWrapper from "$lib/components/molecules/max-width-wrapper.svelte";
    import { mainNavTree } from "$lib/core/constants";
    import { supportedAppVM } from "$lib/domains/supported-app/supported-app.vm.svelte";
    import { breadcrumbs } from "$lib/global.stores";
    import AppWindow from "@lucide/svelte/icons/app-window";
    import Pencil from "@lucide/svelte/icons/pencil";
    import Plus from "@lucide/svelte/icons/plus";
    import RefreshCw from "@lucide/svelte/icons/refresh-cw";
    import Trash2 from "@lucide/svelte/icons/trash-2";
    import { onMount } from "svelte";

    breadcrumbs.set([mainNavTree[0], mainNavTree[2]]);

    let title = $state("");
    let packageName = $state("");
    let editId = $state<number | null>(null);
    let editTitle = $state("");
    let editPackageName = $state("");
    let showEditDialog = $state(false);

    onMount(async () => {
        await supportedAppVM.fetchSupportedApps();
    });

    function resetCreateForm() {
        title = "";
        packageName = "";
    }

    function resetEditForm() {
        editId = null;
        editTitle = "";
        editPackageName = "";
    }

    async function handleCreate(e: Event) {
        e.preventDefault();
        const success = await supportedAppVM.createSupportedApp({
            title,
            packageName,
        });
        if (success) resetCreateForm();
    }

    function openEditDialog(app: (typeof supportedAppVM.supportedApps)[number]) {
        editId = app.id;
        editTitle = app.title;
        editPackageName = app.packageName;
        showEditDialog = true;
    }

    async function handleUpdate(e: Event) {
        e.preventDefault();
        if (!editId) return;
        const success = await supportedAppVM.updateSupportedApp(editId, {
            title: editTitle,
            packageName: editPackageName,
        });
        if (success) {
            showEditDialog = false;
            resetEditForm();
        }
    }

    function formatDate(value: Date | string): string {
        return new Date(value).toLocaleString();
    }

    $effect(() => {
        if (showEditDialog) return;
        resetEditForm();
    });
</script>

<MaxWidthWrapper cls="space-y-4">
    <Card.Root>
        <Card.Header>
            <div
                class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
            >
                <div class="flex items-center gap-2">
                    <Icon icon={AppWindow} cls="h-5 w-5 text-primary" />
                    <Card.Title>Supported Apps</Card.Title>
                    <span class="text-muted-foreground text-xs">
                        {supportedAppVM.supportedApps.length} total
                    </span>
                </div>
                <div class="flex items-center gap-2">
                    <Button
                        variant="outline"
                        size="sm"
                        onclick={() => void supportedAppVM.fetchSupportedApps()}
                        disabled={supportedAppVM.loading}
                    >
                        <Icon
                            icon={RefreshCw}
                            cls={`mr-2 h-4 w-4 ${supportedAppVM.loading ? "animate-spin" : ""}`}
                        />
                        Refresh
                    </Button>
                    <Button
                        size="sm"
                        onclick={() => (supportedAppVM.showCreateDialog = true)}
                    >
                        <Icon icon={Plus} cls="mr-2 h-4 w-4" />
                        Add Supported App
                    </Button>
                </div>
            </div>
        </Card.Header>

        <Card.Content>
            {#if !supportedAppVM.loading && supportedAppVM.supportedApps.length === 0}
                <div class="py-10 text-center text-sm text-muted-foreground">
                    No supported apps configured yet.
                </div>
            {:else}
                <div class="space-y-3 md:hidden">
                    {#each supportedAppVM.supportedApps as app (app.id)}
                        <div class="rounded-lg border bg-background p-3">
                            <div class="space-y-1">
                                <p class="text-sm font-medium">{app.title}</p>
                                <p
                                    class="text-muted-foreground break-all font-mono text-xs"
                                >
                                    {app.packageName}
                                </p>
                            </div>
                            <div class="text-muted-foreground mt-3 text-xs">
                                Updated {formatDate(app.updatedAt)}
                            </div>
                            <div class="mt-3 flex justify-end gap-2">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onclick={() => openEditDialog(app)}
                                >
                                    <Icon icon={Pencil} cls="h-4 w-4" />
                                </Button>
                                <AlertDialog.Root>
                                    <AlertDialog.Trigger
                                        class={buttonVariants({
                                            variant: "destructive",
                                            size: "sm",
                                        })}
                                        disabled={supportedAppVM.deletingId ===
                                            app.id}
                                    >
                                        <Icon icon={Trash2} cls="h-4 w-4" />
                                    </AlertDialog.Trigger>
                                    <AlertDialog.Content>
                                        <AlertDialog.Header>
                                            <AlertDialog.Title>
                                                Delete supported app?
                                            </AlertDialog.Title>
                                            <AlertDialog.Description>
                                                This removes "{app.title}" from
                                                the supported app catalogue.
                                            </AlertDialog.Description>
                                        </AlertDialog.Header>
                                        <AlertDialog.Footer>
                                            <AlertDialog.Cancel>
                                                Cancel
                                            </AlertDialog.Cancel>
                                            <AlertDialog.Action
                                                onclick={() =>
                                                    supportedAppVM.deleteSupportedApp(
                                                        app.id,
                                                    )}
                                            >
                                                Delete
                                            </AlertDialog.Action>
                                        </AlertDialog.Footer>
                                    </AlertDialog.Content>
                                </AlertDialog.Root>
                            </div>
                        </div>
                    {/each}
                </div>

                <div class="hidden md:block">
                    <Table.Root>
                        <Table.Header>
                            <Table.Row>
                                <Table.Head>Title</Table.Head>
                                <Table.Head>Package Name</Table.Head>
                                <Table.Head>Updated</Table.Head>
                                <Table.Head>Actions</Table.Head>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            {#each supportedAppVM.supportedApps as app (app.id)}
                                <Table.Row>
                                    <Table.Cell class="font-medium">
                                        {app.title}
                                    </Table.Cell>
                                    <Table.Cell class="font-mono text-xs">
                                        {app.packageName}
                                    </Table.Cell>
                                    <Table.Cell class="text-xs">
                                        {formatDate(app.updatedAt)}
                                    </Table.Cell>
                                    <Table.Cell>
                                        <div class="flex items-center gap-1">
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onclick={() =>
                                                    openEditDialog(app)}
                                            >
                                                <Icon
                                                    icon={Pencil}
                                                    cls="h-4 w-4"
                                                />
                                                Edit
                                            </Button>
                                            <AlertDialog.Root>
                                                <AlertDialog.Trigger
                                                    class={buttonVariants({
                                                        variant: "destructive",
                                                        size: "sm",
                                                    })}
                                                    disabled={supportedAppVM.deletingId ===
                                                        app.id}
                                                >
                                                    <Icon
                                                        icon={Trash2}
                                                        cls="h-4 w-4"
                                                    />
                                                    Delete
                                                </AlertDialog.Trigger>
                                                <AlertDialog.Content>
                                                    <AlertDialog.Header>
                                                        <AlertDialog.Title>
                                                            Delete supported
                                                            app?
                                                        </AlertDialog.Title>
                                                        <AlertDialog.Description>
                                                            This removes
                                                            "{app.title}" from
                                                            the supported app
                                                            catalogue.
                                                        </AlertDialog.Description>
                                                    </AlertDialog.Header>
                                                    <AlertDialog.Footer>
                                                        <AlertDialog.Cancel>
                                                            Cancel
                                                        </AlertDialog.Cancel>
                                                        <AlertDialog.Action
                                                            onclick={() =>
                                                                supportedAppVM.deleteSupportedApp(
                                                                    app.id,
                                                                )}
                                                        >
                                                            Delete
                                                        </AlertDialog.Action>
                                                    </AlertDialog.Footer>
                                                </AlertDialog.Content>
                                            </AlertDialog.Root>
                                        </div>
                                    </Table.Cell>
                                </Table.Row>
                            {/each}
                        </Table.Body>
                    </Table.Root>
                </div>
            {/if}
        </Card.Content>
    </Card.Root>
</MaxWidthWrapper>

<Dialog.Root bind:open={supportedAppVM.showCreateDialog}>
    <Dialog.Content class="sm:max-w-[425px]">
        <Dialog.Header>
            <Dialog.Title>Add Supported App</Dialog.Title>
            <Dialog.Description>
                Register an app that links are allowed to lease.
            </Dialog.Description>
        </Dialog.Header>
        <form onsubmit={handleCreate} class="space-y-4">
            <div class="space-y-2">
                <Label for="title">Title</Label>
                <Input id="title" bind:value={title} required />
            </div>
            <div class="space-y-2">
                <Label for="packageName">Package Name</Label>
                <Input
                    id="packageName"
                    bind:value={packageName}
                    placeholder="com.example.app"
                    required
                />
            </div>
            <Dialog.Footer>
                <Button
                    variant="outline"
                    type="button"
                    onclick={() => (supportedAppVM.showCreateDialog = false)}
                >
                    Cancel
                </Button>
                <Button type="submit" disabled={supportedAppVM.creating}>
                    {supportedAppVM.creating ? "Creating..." : "Create"}
                </Button>
            </Dialog.Footer>
        </form>
    </Dialog.Content>
</Dialog.Root>

<Dialog.Root bind:open={showEditDialog}>
    <Dialog.Content class="sm:max-w-[425px]">
        <Dialog.Header>
            <Dialog.Title>Edit Supported App</Dialog.Title>
            <Dialog.Description>
                Update the supported app record used by the links flow.
            </Dialog.Description>
        </Dialog.Header>
        <form onsubmit={handleUpdate} class="space-y-4">
            <div class="space-y-2">
                <Label for="edit-title">Title</Label>
                <Input id="edit-title" bind:value={editTitle} required />
            </div>
            <div class="space-y-2">
                <Label for="edit-packageName">Package Name</Label>
                <Input
                    id="edit-packageName"
                    bind:value={editPackageName}
                    placeholder="com.example.app"
                    required
                />
            </div>
            <Dialog.Footer>
                <Button
                    variant="outline"
                    type="button"
                    onclick={() => {
                        showEditDialog = false;
                        resetEditForm();
                    }}
                >
                    Cancel
                </Button>
                <Button type="submit" disabled={supportedAppVM.updating}>
                    {supportedAppVM.updating ? "Saving..." : "Save Changes"}
                </Button>
            </Dialog.Footer>
        </form>
    </Dialog.Content>
</Dialog.Root>
