<script lang="ts">
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { api } from '$lib/api';
// import Element_data_store from '$lib/element_data_store.svelte';

// import { core_func } from '$lib/ae_core_functions';
import {
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { db_core } from '$lib/ae_core/db_core';
import { core_func } from '$lib/ae_core/ae_core_functions';
import {
    CalendarDays,
    Download,
    FolderOpen,
    MinusCircle,
    Pencil,
    PlusCircle,
    RefreshCw,
    Trash2
} from '@lucide/svelte';
// export let allow_basic: boolean = false;

interface Props {
    log_lvl?: number;
    class_li_default?: string;
    class_li?: string;
    lq__hosted_file_obj_li: any;
    link_to_type: string;
    link_to_id: string;
    // export let allow_moderator: boolean = false;
    display_mode?: string; // 'default', 'compact', 'minimal', 'launcher'
    max_file_count?: number;
    file_type?: string; // 'image', 'video', 'audio', 'document', 'other'
    slct_hosted_file_kv?: key_val;
    slct_hosted_file_id?: any;
    slct_hosted_file_obj?: any;
}

let {
    log_lvl = 0,
    class_li_default = 'flex flex-col gap-1 items-center justify-center w-fit max-w-4xl mx-auto my-1 max-h-96 overflow-auto',
    class_li = '',
    lq__hosted_file_obj_li = $bindable([]),
    link_to_type,
    link_to_id,
    display_mode = 'default',
    max_file_count = $bindable(49),
    file_type = $bindable('all'),
    slct_hosted_file_kv = $bindable({}),
    slct_hosted_file_id = $bindable(null),
    slct_hosted_file_obj = $bindable(null)
}: Props = $props();

// export let show_convert_btn: null|boolean = null;

// let ae_placeholder_li: key_val = {};
let ae_promises: key_val = {};
let ae_tmp: key_val = $state({});
ae_tmp.show__file_li = true;
ae_tmp.show__direct_download = $ae_loc.core?.show__direct_download ?? false;
// let ae_triggers: key_val = {};
</script>

<section class="{class_li_default} {class_li}">
    <h3
        class="h3"
        class:hidden={!$lq__hosted_file_obj_li?.length ||
            display_mode != 'default'}>
        Manage Files:
        <span
            class="bg-success-100 border-success-200 rounded-lg border px-4 font-bold"
            title="Files for {link_to_type ?? '-- not set --'}: {link_to_id ??
                '-- not set --'} (files: {$lq__hosted_file_obj_li?.length ??
                'None'})">
            <FolderOpen size="1em" class="mx-1" />
            {@html $lq__hosted_file_obj_li
                ? `${$lq__hosted_file_obj_li.length}&times;`
                : '-- none --'}
        </span>
    </h3>

    <div class="flex flex-row flex-wrap items-center justify-center gap-1">
        <button
            type="button"
            onclick={() => {
                console.log('*** Refresh button clicked ***');

                db_core.file.clear();

                // let params = {
                //     qry__enabled: 'all',
                //     qry__hidden: 'all',
                // }

                core_func.load_ae_obj_li__hosted_file({
                    api_cfg: $ae_api,
                    for_obj_type: link_to_type,
                    for_obj_id: link_to_id,
                    enabled: 'enabled',
                    hidden: 'not_hidden',
                    limit: 250,
                    // params: params,
                    try_cache: true,
                    log_lvl: 0
                });

                // ae_tmp.show__file_li = false;
                // console.log(`$lq__hosted_file_obj_li:`, $lq__hosted_file_obj_li);
                // $slct_trigger = 'load__hosted_file_obj_li';
                // ae_tmp.show__file_li = true;
            }}
            class="btn btn-sm preset-tonal-tertiary hover:preset-tonal-warning border-warning-500 m-1 border p-1 transition hover:transition-all *:hover:inline"
            class:hidden={!$ae_loc.edit_mode || !$ae_loc.authenticated_access}
            title="Refresh the list of files">
            <RefreshCw size="1em" class="m-1" />
            <div class="hidden">Files</div>
        </button>

        <button
            type="button"
            onclick={() => {
                console.log('*** Show Alt Download button clicked ***');
                ae_tmp.show__direct_download = !ae_tmp.show__direct_download;
            }}
            class="btn btn-sm preset-tonal-tertiary hover:preset-tonal-warning border-warning-500 m-1 border p-1 transition hover:transition-all *:hover:inline"
            class:hidden={!$ae_loc.edit_mode || !$ae_loc.trusted_access}
            title="Toggle direct download link and copy link button">
            <Download size="1em" class="m-1" />
            <div class="hidden">
                {ae_tmp.show__direct_download ? 'Alt On' : 'Alt Download Off'}
            </div>
        </button>
    </div>

    {#if $lq__hosted_file_obj_li && $lq__hosted_file_obj_li.length}
        <div class="w-full overflow-auto">
            <ol class="list-inside list-decimal">
                {#each [...$lq__hosted_file_obj_li]
                    .reverse()
                    .slice(0, max_file_count) as hosted_file_obj (hosted_file_obj.hosted_file_id)}
                    <li>
                        <button
                            type="button"
                            disabled={!$ae_loc.trusted_access}
                            onclick={() => {
                                // This (uploaded_file_kv) is referenced by other AE components. Currently it is only used for the video clipper. This should be a toggle of Add/Remove.
                                if (
                                    $ae_loc.files.uploaded_file_kv[
                                        hosted_file_obj.hosted_file_id
                                    ]
                                ) {
                                    delete $ae_loc.files.uploaded_file_kv[
                                        hosted_file_obj.hosted_file_id
                                    ];
                                    $ae_loc.files.uploaded_file_kv = {
                                        ...$ae_loc.files.uploaded_file_kv
                                    };

                                    delete slct_hosted_file_kv[
                                        hosted_file_obj.hosted_file_id
                                    ];
                                    slct_hosted_file_id = null;
                                    slct_hosted_file_obj = null;
                                } else {
                                    $ae_loc.files.uploaded_file_kv[
                                        hosted_file_obj.hosted_file_id
                                    ] = hosted_file_obj;
                                    lq__hosted_file_obj_li[
                                        hosted_file_obj.hosted_file_id
                                    ] = hosted_file_obj;

                                    slct_hosted_file_kv[
                                        hosted_file_obj.hosted_file_id
                                    ] = hosted_file_obj;
                                    slct_hosted_file_id =
                                        hosted_file_obj.hosted_file_id;
                                    slct_hosted_file_obj = hosted_file_obj;
                                }
                            }}
                            class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500"
                            title="Add/Remove file to/from the locally stored uploaded file list. This is referenced by other AE components.">
                            {#if $ae_loc.files.uploaded_file_kv[hosted_file_obj.hosted_file_id]}
                                <MinusCircle size="1em" class="m-1" />
                                <span class="hidden">Remove</span>
                            {:else}
                                <PlusCircle size="1em" class="m-1" />
                                <span class="hidden">Add</span>
                            {/if}
                        </button>

                        <button
                            type="button"
                            disabled={!$ae_loc.administrator_access}
                            onclick={() => {
                                if (
                                    !confirm(
                                        `Are you sure you want to delete this hosted file?\n${hosted_file_obj.filename} [${hosted_file_obj.hosted_file_id}]`
                                    )
                                ) {
                                    return false;
                                }

                                ae_promises.delete__hosted_file_obj =
                                    core_func.delete_ae_obj_id__hosted_file({
                                        api_cfg: $ae_api,
                                        hosted_file_id:
                                            hosted_file_obj.hosted_file_id,
                                        link_to_type: link_to_type,
                                        link_to_id: link_to_id,
                                        rm_orphan: true,
                                        fake_delete: false,
                                        log_lvl: 0
                                    });
                            }}
                            class:hidden={!$ae_loc.administrator_access}
                            class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500"
                            title="Delete a file from the host server.">
                            <Trash2 size="1em" class="m-1" />
                            <span class="hidden">Delete</span>
                        </button>

                        <button
                            type="button"
                            disabled={!$ae_loc.administrator_access}
                            class:hidden={!$ae_loc.administrator_access}
                            onclick={() => {
                                // This should show/hide the editable fields for the file. This might need to be in a little modal.
                            }}
                            class="btn btn-sm preset-tonal-primary hover:preset-filled-primary-500"
                            title="Edit file details">
                            <Pencil size="1em" class="m-1" />
                            <span class="hidden">Edit</span>
                        </button>

                        <span class="text-xs text-gray-500">
                            <CalendarDays size="1em" class="mx-1" />
                            <span class="hidden">Created on:</span>
                            {ae_util.iso_datetime_formatter(
                                hosted_file_obj.created_on,
                                'datetime_medium_sec'
                            )}
                            {#if hosted_file_obj.updated_on}
                                <RefreshCw size="1em" class="mx-1" />
                                Updated on
                                {ae_util.iso_datetime_formatter(
                                    hosted_file_obj.updated_on,
                                    'datetime_medium_sec'
                                )}
                            {/if}
                        </span>

                        <span class="text-sm font-semibold">
                            <!-- <a href="" class="underline text-blue-500"> -->
                            {hosted_file_obj.filename}
                            <!-- </a> -->
                        </span>
                        <span class="text-xs text-gray-500">
                            {ae_util.format_bytes(hosted_file_obj.size)}
                        </span>

                        <span
                            class:hidden={!$ae_loc.edit_mode}
                            class="text-xs text-gray-500">
                            {hosted_file_obj.hash_sha256?.slice(0, 5)}...
                        </span>
                    </li>
                {/each}
            </ol>
        </div>
    {:else}
        <p
            class="w-96 text-center text-gray-500"
            class:hidden={display_mode != 'default'}>
            No files available to display
        </p>
    {/if}
</section>

<style>
</style>
