<script>
    import { createEventDispatcher } from 'svelte';
    import { slide } from 'svelte/transition';

    import NewSshKey from './NewSshKey.svelte';
    import EditSshKey from './EditSshKey.svelte';
    import Icon from '../../ui/Icon.svelte';

    export let record;

    const dispatch = createEventDispatcher();

    function copy(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    let local = copy(record);
    $: isModified = JSON.stringify(local) !== JSON.stringify(record);
    let showDetails = record?.isNew;

    function handleSave(evt) {
        local = copy(evt.detail);
        showDetails = false;
    }
</script>


<div class="rounded-box space-y-4 bg-base-200">
    <div class="flex items-center px-6 py-4 gap-x-4">
        {#if !record.isNew}
            {#if showDetails}
                <input 
                    type="text"
                    class="input input-bordered bg-transparent text-lg font-bold"
                    bind:value={local.name}
                >
            {:else}
                <h3 class="text-lg font-bold">
                    {record.name}
                </h3>
            {/if}
        {/if}

        <div class="join ml-auto">
            <button
                type="button"
                class="btn btn-outline join-item"
                on:click={() => showDetails = !showDetails}
            >
                <Icon name="pencil" class="size-6" />
            </button>
            <button
                type="button"
                class="btn btn-outline btn-error join-item"
                on:click={() => dispatch('delete', record)}
            >
                <Icon name="trash" class="size-6" />
            </button>
        </div>
    </div>

    {#if record && showDetails}
        <div transition:slide|local={{duration: 200}} class="px-6 pb-4 space-y-4">
            {#if record.isNew}
                <NewSshKey {record} on:save on:save={handleSave} />
            {:else}
                <EditSshKey bind:local={local} {isModified} on:save={handleSave} on:save />
            {/if}
        </div>
    {/if}
</div>
