<script lang="ts">
// Imports
// Import components and elements
// import Element_input_files_tbl from '$lib/element_input_files_tbl.svelte';

// Import storage, functions, and libraries
import type { key_val } from '$lib/stores/ae_stores';

import { api } from '$lib/ae_api/api';
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';

import AE_Comp_Hosted_Files_Download_Button from '$lib/elements/ae_comp__hosted_files_download_button.svelte';
import {
    Check,
    Download,
    LoaderCircle,
    MinusCircle,
    Scissors
} from '@lucide/svelte';
// Exports

// export let input_name = 'file_list';
// export let multiple: boolean = true;
// export let required: boolean = true;

// export let input_class_li: string[] = ['file_drop_area'];

interface Props {
    log_lvl?: number;
    // Expecting these for link_to_type: 'event', 'event_location', 'archive_content', etc
    link_to_type: string;
    link_to_id: string;
    // export let accept: string = 'audio/*, image/*, video/*, .bak, .cfg, .css, .csv, .doc, .docx, .gz, .htm, .html, .ini, .iso, .j2, .json, .key, .keynote, .md, .pdf, .ppt, .pptx, .rar, .rtf, .sql, .svelte, ttf, .txt, .xls, .xlsx, .xz, .zip, .bin, .dmg, .exe, .js, .msi, .php, .py, .sh';
    class_li_default?: string;
    class_li?: string;
    // export let table_class_li: string[] = ['table', 'table-sm', 'table-striped', 'table-hover' , 'text-sm'];
    clip_complete?: boolean;
    // export let upload_complete: boolean = false;
    submit_status?: null | string;
    // hosted_file_id_li?: string[];
    // hosted_file_obj_li?: any[];
    hosted_file_obj_kv?: key_val;
    video_clip_file_kv?: key_val;
}

let {
    log_lvl = $bindable(0),
    link_to_type = $bindable(),
    link_to_id = $bindable(),
    class_li_default = 'flex flex-col gap-1 items-center justify-center w-full max-w-2xl mx-auto my-1',
    class_li = $bindable(''),
    clip_complete = $bindable(false),
    submit_status = $bindable(null),
    // hosted_file_id_li = [],
    // hosted_file_obj_li = [],
    hosted_file_obj_kv = $bindable({}),
    video_clip_file_kv = $bindable({})
}: Props = $props();

// Local Variables
let task_id = link_to_id;
// let input_file_list: any = null;
let ae_promises: key_val = $state({});
// let ae_promises_clipping: key_val = {};
// let ae_triggers: key_val = {};

// let input_element_id = 'ae_comp__hosted_files_upload__input';

// let form_kv: key_val = {
//     start_time: null,
//     end_time: null,
//     reencode: null,
//     video_file: null,
// };
// let download_clip_src: string;
// let download_clip_filename: string;

$ae_sess.files.obj = {
    obj: null
};

// *** Functions and Logic
function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}

function handle_clip_video(event: Event) {
    console.log('*** handle_clip_video() ***');

    submit_status = 'clipping';
    clip_complete = false;

    const form = event.target as HTMLFormElement;
    const formData = new FormData(form);

    let hosted_file_id = formData.get('hosted_file_id') as string;
    let start_time = formData.get('start_time') as string;
    let end_time = formData.get('end_time') as string;
    let reencode = formData.get('reencode') as string;
    let scale_down = formData.get('scale_down') as string;
    let new_filename = formData.get('new_filename') as string;

    $ae_sess.files.processed_file_kv[hosted_file_id] = {};
    $ae_sess.files.processed_file_kv[hosted_file_id].submit_status = 'clipping';
    $ae_sess.files.processed_file_kv[hosted_file_id].clip_complete = false;

    // $ae_sess.files.disable_submit__hosted_file_obj = true;
    $ae_loc.files.processed_file_kv[hosted_file_id] = {};
    $ae_loc.files.processed_file_kv[hosted_file_id].submit_status = 'clipping';
    $ae_loc.files.processed_file_kv[hosted_file_id].start_time = start_time;
    $ae_loc.files.processed_file_kv[hosted_file_id].end_time = end_time;
    $ae_loc.files.processed_file_kv[hosted_file_id].reencode = reencode;
    $ae_loc.files.processed_file_kv[hosted_file_id].scale_down = scale_down;
    $ae_loc.files.processed_file_kv[hosted_file_id].new_filename = new_filename;
    $ae_loc.files.processed_file_kv[hosted_file_id].clip_complete = false;

    let endpoint = `/v3/action/hosted_file/${hosted_file_id}/clip_video`;

    let params = {
        link_to_type: link_to_type,
        link_to_id: link_to_id,
        filename_no_ext: new_filename.replace('.mp4', ''),
        from_type: 'mp4', // Video file type being converted
        to_type: 'mp4', // Video file type to convert to
        start_time: start_time,
        end_time: end_time,
        reencode: reencode,
        scale_down: scale_down
    };

    ae_promises[hosted_file_id] = {};
    // .convert__hosted_file_obj
    ae_promises[hosted_file_id] = api
        .get_object({
            api_cfg: $ae_api,
            endpoint: endpoint,
            params: params,
            timeout: 1800000, // 30 minutes — clip_video runs ffmpeg which can take 5-15 min for long recordings
            // return_blob: true,
            // filename: event.target.new_filename.value,
            // auto_download: false,
            task_id: task_id,
            log_lvl: log_lvl
        })
        .then(function (result) {
            console.log(result);

            // WHY: get_object() returns false/null on network failure (CORS drop,
            // timeout, Gunicorn worker killed). Without this guard, result.hosted_file_id
            // is undefined — JS uses it as an object key without throwing, so all the
            // success state below would run and show "Clipped" on a failed request.
            if (!result || !result.hosted_file_id) {
                console.log('clip_video: request failed or returned no result');
                $ae_sess.files.processed_file_kv[hosted_file_id].submit_status =
                    'error';
                $ae_loc.files.processed_file_kv[hosted_file_id].submit_status =
                    'error';
                submit_status = 'error';
                clip_complete = false;
                return false;
            }

            video_clip_file_kv[result.hosted_file_id] = {};
            video_clip_file_kv[result.hosted_file_id] = result;

            $ae_sess.files.processed_file_kv[hosted_file_id].submit_status =
                'clipped';
            $ae_sess.files.processed_file_kv[hosted_file_id].clip_complete =
                true;

            $ae_loc.files.processed_file_kv[hosted_file_id].submit_status =
                'clipped';
            $ae_loc.files.processed_file_kv[hosted_file_id].clip_complete =
                true;

            submit_status = 'clipped';
            clip_complete = true;

            return true;
        });
}
</script>

<section class="{class_li_default} {class_li}">
    <h3 class="h3">
        {Object.entries(hosted_file_obj_kv).length}× files uploaded
    </h3>

    {#each Object.entries(hosted_file_obj_kv) as [hosted_file_id, hosted_file_obj] (hosted_file_id)}
        <div
            class="border-surface-500/20 preset-tonal-surface m-2 rounded-lg border p-2">
            <!-- Download Button (Standardized) -->
            <div
                class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
                <!-- Remove from uploaded file kv list -->
                <button
                    type="button"
                    onclick={() => {
                        // This (uploaded_file_kv) is referenced by other AE components. Currently it is only used with the manage hosted file list and clip video components.
                        console.log(
                            `Removed hosted file ID: ${hosted_file_id}`,
                            $ae_loc.files.uploaded_file_kv
                        );
                        // delete $ae_sess.files.uploaded_file_kv[hosted_file_id];
                        delete $ae_loc.files.uploaded_file_kv[hosted_file_id];
                        $ae_loc.files.uploaded_file_kv = {
                            ...$ae_loc.files.uploaded_file_kv
                        };
                        delete hosted_file_obj_kv[hosted_file_id];
                        hosted_file_obj_kv = { ...hosted_file_obj_kv };
                        // delete $ae_loc.files.uploaded_file_kv[hosted_file_obj.hosted_file_id];
                        console.log(
                            `Removed hosted file ID: ${hosted_file_obj.hosted_file_id}`,
                            $ae_loc.files.uploaded_file_kv
                        );
                    }}
                    class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500"
                    title={`Remove this file from list of videos:\n${hosted_file_obj.filename}\n[API] SHA256: ${hosted_file_obj?.hash_sha256?.slice(0, 10)}... Hosted ID: ${hosted_file_obj.hosted_file_id}`}>
                    <MinusCircle size="1em" class="m-1" />
                    <span class="">Remove</span>
                </button>

                <!-- Download the file -->
                <div class:hidden={!$ae_loc.edit_mode}>
                    <AE_Comp_Hosted_Files_Download_Button
                        {hosted_file_id}
                        {hosted_file_obj}
                        color="primary"
                        variant="tonal"
                        classes="novi_btn btn-sm lg:btn-md min-w-72 lg:min-w-96 !justify-start"
                        show_divider={true}
                        max_filename={30} />
                </div>
                <span
                    >{ae_util.shorten_filename({
                        filename: hosted_file_obj?.filename,
                        max_length: 30
                    })}</span>
                <span>
                    <span class="text-sm font-bold"> File ID: </span>
                    {hosted_file_obj.hosted_file_id}</span>
                <span>
                    <span class="text-sm font-bold"> Type: </span>
                    {hosted_file_obj.extension}</span>
                <!-- <span>{hosted_file_obj.filename}</span> -->
            </div>

            <form
                onsubmit={prevent_default(handle_clip_video)}
                class="{class_li_default} {class_li}">
                <!-- {$ae_sess?.files[hosted_file_obj?.hosted_file_id ?? 'obj'].submit_status ?? 'not set'} -->

                <input
                    type="hidden"
                    name="hosted_file_id"
                    value={hosted_file_obj.hosted_file_id} />

                <div
                    class="flex w-full flex-row items-center justify-center gap-1">
                    <span class="w-32 text-xs font-bold">New Filename:</span>
                    <input
                        type="text"
                        class="input variant-filled-surface w-full text-sm"
                        name="new_filename"
                        value={hosted_file_obj.filename} />
                </div>

                <div
                    class="flex w-full max-w-(--breakpoint-sm) flex-row items-center justify-center gap-1">
                    <label
                        class="label w-48"
                        title="The start time of the clip. This is the time in the video where the clip will start. You may need to subtract a few seconds to get the exact start time.">
                        <span class="text-xs font-bold"
                            >Start time (HH:MM:SS)</span>
                        <input
                            type="text"
                            name="start_time"
                            value={$ae_loc.files.processed_file_kv &&
                            $ae_loc.files.processed_file_kv[hosted_file_id] &&
                            $ae_loc.files.processed_file_kv[hosted_file_id]
                                .start_time
                                ? $ae_loc.files.processed_file_kv[
                                      hosted_file_id
                                  ].start_time
                                : '00:00:00'}
                            placeholder="HH:MM:SS (00:01:30)"
                            class="input variant-filled-surface w-32" />
                    </label>

                    <label
                        class="label w-48"
                        title="The end time of the clip. This is the time in the video where the clip will end. You may need to add a few seconds to get the exact end time.">
                        <span class="text-xs font-bold"
                            >End time (HH:MM:SS)</span>
                        <input
                            type="text"
                            name="end_time"
                            value={$ae_loc.files.processed_file_kv &&
                            $ae_loc.files.processed_file_kv[hosted_file_id] &&
                            $ae_loc.files.processed_file_kv[hosted_file_id]
                                .end_time
                                ? $ae_loc.files.processed_file_kv[
                                      hosted_file_id
                                  ].end_time
                                : '00:45:59'}
                            placeholder="HH:MM:SS (01:05:25)"
                            class="input variant-filled-surface w-32" />
                    </label>

                    <span
                        class="flex flex-col items-center justify-center gap-1"
                        title="Re-encode the video file? This does cause some minor quality loss. Re-encoding is useful if the audio or video seems to be chopped off at the beginning or end of the clip. It can also help with partially corrupted files.">
                        <span class="text-xs font-bold"> Re-encode? </span>
                        <label class="inline-block">
                            <input
                                type="radio"
                                name="reencode"
                                value="true"
                                class="radio"
                                checked />
                            True
                        </label>
                        <label class="inline-block">
                            <input
                                type="radio"
                                name="reencode"
                                value="false"
                                class="radio" />
                            False
                        </label>
                    </span>

                    <span
                        class="flex flex-col items-center justify-center gap-1"
                        title="Scale the video file down to 1920x1080? This does cause some minor quality loss. Re-encoding is useful if the audio or video seems to be chopped off at the beginning or end of the clip. It can also help with partially corrupted files.">
                        <span class="text-xs font-bold"> Scale down? </span>
                        <label class="inline-block">
                            <input
                                type="radio"
                                name="scale_down"
                                value="true"
                                class="radio"
                                checked />
                            True
                        </label>
                        <label class="inline-block">
                            <input
                                type="radio"
                                name="scale_down"
                                value="false"
                                class="radio" />
                            False
                        </label>
                    </span>
                </div>

                <button
                    type="submit"
                    class="btn btn-lg btn-primary border transition-colors"
                    class:preset-tonal-primary={submit_status !== 'error'}
                    class:border-primary-500={submit_status !== 'error'}
                    class:hover:preset-filled-primary-500={submit_status !== 'error'}
                    class:preset-tonal-error={submit_status === 'error'}
                    class:border-error-500={submit_status === 'error'}
                    disabled={submit_status == 'clipping'}>
                    {#if $ae_loc.files.processed_file_kv[hosted_file_id] && $ae_loc.files.processed_file_kv[hosted_file_id].submit_status == 'clipping'}
                        <LoaderCircle size="1em" class="m-1 animate-spin" />
                        <span class="highlight">Clipping...</span>
                    {:else if $ae_loc.files.processed_file_kv[hosted_file_id] && $ae_loc.files.processed_file_kv[hosted_file_id].submit_status == 'error'}
                        <span class="fas fa-exclamation-triangle m-1"></span>
                        Failed — Retry?
                    {:else if $ae_loc.files.processed_file_kv[hosted_file_id] && $ae_loc.files.processed_file_kv[hosted_file_id].submit_status == 'clipped'}
                        <Check size="1em" class="m-1" />
                        Clipped
                    {:else}
                        <Scissors size="1em" class="m-1" />
                        Clip Video
                    {/if}
                    <!-- <span class="fas fa-cut m-1"></span>
            Clip Video -->
                </button>
            </form>

            {#await ae_promises[hosted_file_id]}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <span class="highlight"
                    >Processing... This may take a few minutes.</span>
            {:then}
                {#if ae_promises[hosted_file_id]}
                    <Download size="1em" /> Ready to download below!
                {:else}
                    <!-- <p>Fill out the form and select the video file to clip.</p> -->
                {/if}
            {/await}
        </div>
    {/each}

    <!-- <hr />

{#await ae_promises.upload__hosted_file_obj}
    <span class="fas fa-spinner fa-spin m-1"></span>
    <p class="highlight">Converting... This may take a few minutes.</p>
{:then}
    {#if ae_promises.upload__hosted_file_obj}
    <a href={download_clip_src} download={download_clip_filename} class="ae_btn btn_lg btn_primary"><span class="fas fa-download"></span> Ready to Download</a>
    {:else}
    <p>Fill out the form and select the video file to clip.</p>
    {/if}
{/await} -->
</section>
