<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte.js';
    import { user }          from '../../user.svelte.js';

    import MarkdownEditor    from '../../Components/MarkdownEditor.svelte';
    import PermissionEditor  from '../../Components/PermissionEditor.svelte';
    import Tags              from '../tags/TagList.svelte';

    let { project_id = null, parent_task_id } = $props();
    let project          = $state(null);
    let extendedSettings = $state(false);
    let parent_task      = $state(null);
    let task = $state({
        name           : '',
        description    : { source : '', rendered : '' },
        due_date       : null,
        estimated_time : null,
        no_index       : false,
        show_closed    : false,
        start_date     : null,
        tags           : []
    });
    let router = useTinyRouter();

    function addMember(member){
        for (let uid of Object.keys(member)) task.members[uid] = project.members[uid];
    }

    function flat(json){
        return JSON.parse(JSON.stringify(json));
    }

    function dropMember(member){
        delete task.members[member.user.id];
        console.log({drop:member.user.id});
        ///  TODO: ?
    }

    async function load(){
        if (parent_task_id) await loadParent();
        if (project_id) loadProject();
        loadTags();
    }

    async function loadParent(){
        const url  = api(`task/${parent_task_id}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            parent_task         = await resp.json();
            task.parent_task_id = +parent_task_id;
            project_id          = parent_task.project_id;
            yikes();
            project             = null; // TODO
        } else {
            error(resp);
        }
    }

    async function loadProject(){
        const url  = api(`project/${project_id}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            project           = await resp.json();
            task.project_id   = +project_id;
            yikes();
        } else {
            error(resp);
        }
    }

    async function loadTags(){
        let url = null;
        if (project_id) url = api(`tags/project/${project_id}`);
        if (parent_task_id) url = api(`tags/task/${parent_task_id}`);
        if (url) {
            const resp = await fetch(url,{credentials:'include'});
            if (resp.ok) task.tags = await resp.json();
        }
    }

    async function getCandidates(text){
        const origin = parent_task ? parent_task.members : project.members;
        const candidates = Object.values(origin)
            .filter(member => member.user.name.toLowerCase().includes(text.toLowerCase()))
            .map(member => [member.user.id,member.user.name]);
        return Object.fromEntries(candidates);
    }


    function onkeydown(e){
        if (e.ctrlKey && e.keyCode === 83) {
            e.preventDefault();
            saveTask();
        }
    }

    async function saveTask(){
        const url  = api('task/add');
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify(task)
        });
        if (resp.ok) {
            task = await resp.json();
            if (task.parent_task_id){
                router.navigate(`/task/${task.parent_task_id}/view`);
            } else router.navigate(`/task/${task.id}/view`);
            yikes();
        } else {
            error(resp);
        }
    }

    function toggleSettings(){
        extendedSettings = !extendedSettings;
    }

    onMount(load);
</script>

<svelte:head>
    <title>Umbrella – {t('add_object',{object:t('task')})}</title>
</svelte:head>

<fieldset>
    <legend>{t('add_object',{object:t('task')})}</legend>
    <table {onkeydown}>
        <tbody>
            <tr>
                <th>
                    {t('name')}
                </th>
                <td>
                    <input bind:value={task.name} autofocus>
                </td>
            </tr>
            {#if project}
            <tr>
                <th>
                    {t('project')}
                </th>
                <td>
                    {project.name}
                </td>
            </tr>
            {/if}
            {#if parent_task}
            <tr>
                <th>
                    {t('parent_task')}
                </th>
                <td>
                    {parent_task.name}
                </td>
            </tr>
            {/if}

            <tr>
                <th>
                    {t('description')}
                </th>
                <td>
                    <MarkdownEditor bind:value={task.description} simple={true} />
                </td>
            </tr>
            <tr>
                <th>
                    {t('tags')}
                </th>
                <td>
                    <Tags module="task" bind:tags={task.tags} />
                </td>
            </tr>
            {#if extendedSettings}
            <tr>
                <th>
                    {t('members')}
                </th>
                <td>
                    <PermissionEditor members={task.members} {addMember} {getCandidates} {dropMember} />
                </td>
            </tr>
            <tr>
                <th>
                    {t('estimated_time')}
                </th>
                <td>
                    <input type="number" bind:value={task.estimated_time} /> {t('hours')}
                </td>
            </tr>
            <tr>
                <th>
                    {t('start_date')}
                </th>
                <td>
                    <input type="date" bind:value={task.start_date} />
                </td>
            </tr>
            <tr>
                <th>
                    {t('due_date')}
                </th>
                <td>
                    <input type="date" bind:value={task.due_date} />
                </td>
            </tr>
            <tr>
                <th>
                    {t('subtasks')}
                </th>
                <td>
                    <label>
                        <input type="checkbox" bind:checked={task.show_closed} >
                        {t('display_closed_tasks')}
                    </label>
                </td>
            </tr>
            <tr>
                <th>
                    {t('index_page')}
                </th>
                <td>
                    <label>
                        <input type="checkbox" bind:checked={task.no_index} >
                        {t('hide_on_index_page')}
                    </label>
                </td>
            </tr>
            {:else}
            <tr>
                <th>
                    {t('extended_settings')}
                </th>
                <td>
                    <button onclick={toggleSettings}>{t('show')}</button>
                </td>
            </tr>
            {/if}
        </tbody>
    </table>
    <button onclick={saveTask}>{t('save_object',{object:t('task')})}</button>
</fieldset>