<script>
    import { t }        from '../../translations.svelte.js';

    import EstimateList from './EstimateList.svelte';
    import ItemList     from './ItemList.svelte';
    import TimeList     from './TimeList.svelte';

    let {
        close = () => {},
        doc = $bindable({}),
        onSelect = (item) => {}
    } = $props();

    let source = $state(0);

    function estimateSelected(estimate){
        onSelect({
            item_code   : t('estimated_time'),
            title       : estimate.name,
            description : estimate.description.source,
            amount      : estimate.est_time,
            unit        : t('hours')
        });
    }

    function itemSelected(item){
        let unit_price = null;
        let unit = t('pieces');
        let description = '';
        let tax = null;
        for (let prop of item.properties) {
            let lowerName = prop.name.toLowerCase();
            if (lowerName.indexOf(t('price').toLowerCase())>-1){
                unit_price = 100*String(prop.value).replace(',','.');
            } else if (lowerName.indexOf(t('unit').toLowerCase())>-1){
                unit = prop.value;
            } else if (lowerName.indexOf(t('tax_rate').toLowerCase())>-1 && prop.unit=='%'){
                tax = prop.value;
            } else {
                description += `* ${prop.name}: ${prop.value}\n`;
            }
        }

        var data = {
            item_code   : item.code,
            title       : item.name,
            description : description,
            amount      : 1,
            unit        : unit,
            unit_price  : unit_price
        };
        if (tax) data['tax'] = tax;

        onSelect(data);
    }

    function timeSelected(time){
        onSelect({
            item_code   : t('timetrack'),
            title       : time.subject,
            description : time.description.source,
            amount      : time.duration,
            unit        : t('hours'),
            time_id     : time.id
        });
    }
</script>

<style>
    div{
        position : fixed;
        top      : 0;
        bottom   : 20px;
        left     : 0;
        right    : 0;
        padding  : 10px;
        overflow : auto;

    }
    span{
        position : sticky;
        top      : 0;
    }
</style>

<div class="position_selector">
    <span class="tabs">
        <button onclick={() => source=0}>{t('items')}</button>
        <button onclick={() => source=1}>{t('estimated_times')}</button>
        <button onclick={() => source=2}>{t('timetrack')}</button>
        <button onclick={close}>{t('abort')}</button>
    </span>
    {#if source == 0}
    <ItemList company_id={doc.company.id} onSelect={itemSelected} />
    {:else if source == 1}
    <EstimateList company_id={doc.company.id} onSelect={estimateSelected}  />
    {:else}
    <TimeList company_id={doc.company.id} hide={doc.positions} onSelect={timeSelected}  />
    {/if}
    <pre>
</div>
