<script>
    import { t }  from '../../translations.svelte.js';
    import { api } from '../../urls.svelte.js';
    import { user } from '../../user.svelte.js';
    import { onMount } from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import MarkdownEditor from '../../Components/MarkdownEditor.svelte';
    import MemberEditor from '../../Components/MemberEditor.svelte';

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

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

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

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

    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;
            console.log({prj:project_id});
            error = null;
            project = null; // TODO
        } else {
            error = await resp.text();
        }
    }

    async function loadProject(){
        var url = api(`project/${project_id}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            project = await resp.json();
            task.project_id = +project_id;
            task.members = JSON.parse(JSON.stringify(parent_task?parent_task.members:project.members)); // deep copy
            error = null;
        } else {
            error = await resp.text();
        }
    }

    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);
    }

    async function saveTask(){
        var 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`);
            error = null;
        } else {
            error = await resp.text();
        }
    }

    function toggleSettings(){
        extendedSettings = !extendedSettings;
    }

    onMount(load);
</script>


<fieldset>
    <legend>{t('add_task')}</legend>
    <table>
        <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>
            {#if extendedSettings}
            <tr>
                <th>
                    {t('members')}
                </th>
                <td>
                    <MemberEditor 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_task')}</button>
</fieldset>