<script>
    // @ts-nocheck

    import { browser } from "$app/environment";
    import { page } from "$app/stores";
    import { getAuthInfo, makeAuthHeaderForAxios } from "$lib/auth/Auth";
    import { makePost } from "$lib/tools/requests/requests";
    import { sayError } from "$lib/tools/toaster/Toaster";
    import Pagination from "$lib/ui-components/pagination.svelte";
    import { el } from "date-fns/locale";

    let currenciesCurrentPage = 1;
    let currenciesMaxPage = 1;
    let currenciesFilter = "-1";
    let showCurrenciesLoading = false;
    let currencies = [];
    async function getCurrencies() {
        showCurrenciesLoading = true;
        const res = await makePost(
            "admin/loadCurrencies",
            {
                page: currenciesCurrentPage,
                status:
                    Number(currenciesFilter) > -1
                        ? Number(currenciesFilter)
                        : undefined,
            },
            makeAuthHeaderForAxios(getAuthInfo()?.a),
        );
        // console.log(res);
        if (res.error) {
            sayError("Не удалось загрузить валюты");
            console.error(
                {
                    page: currenciesCurrentPage,
                    status:
                        Number(currenciesFilter) > -1
                            ? Number(currenciesFilter)
                            : undefined,
                },
                "- ERROR",
            );
            showCurrenciesLoading = false;
            return;
        }
        currencies = res.data.data ?? [];
        currenciesMaxPage = Number(res.data.pages);
        showCurrenciesLoading = false;
    }

    if (browser) {
        getCurrencies();
    }

    $: if (currenciesFilter.length > 0) {
        console.log(currenciesFilter);

        currenciesCurrentPage = 1;
        getCurrencies();
    }

    let selectedCurrency = {};
    let showChangeCurrency = false;
    let showChangeCurrencyLoading = false;

    let newBankValue = "";
    let newVolumeValue = "";

    async function changeCurrency() {
        if (newBankValue.length < 1 && newVolumeValue.length < 1) {
            sayError("Укажите хотябы одно изменение");
            return;
        }
        showChangeCurrencyLoading = true;

        const res = await makePost("admin/updateCurrency", {
            bank: newBankValue.length >= 1 ? newBankValue:undefined,
            volume: newVolumeValue.length > 1 ? newVolumeValue:undefined,
            code: selectedCurrency['code']
        }, makeAuthHeaderForAxios(getAuthInfo()?.a));

        if(res.error)
        {
            sayError("Не удалось обновить валюту");
            showChangeCurrencyLoading = false;
            return;
        }

        showChangeCurrencyLoading = false;
        showChangeCurrency = false;
        newBankValue = "";
        newVolumeValue = "";
        getCurrencies();
    }
</script>

<div class="w-full flex flex-col gap-8">
    <div class="flex gap-4">
        <div class="bg-accent rounded-[4px] w-[10px] h-full"></div>
        <h1 class="text-2xl font-semibold">Валюты</h1>
    </div>
    <div
        class="flex w-full flex-col bg-base-300 p-4 rounded-box overflow-x-auto"
    >
        <div class="flex justify-center items-center p-4">
            <Pagination
                pageChangedCallback={(n) => {
                    currenciesCurrentPage = n;
                    getCurrencies();
                }}
                totalPages={currenciesMaxPage}
                css={"btn-neutral"}
                disableButtons={showCurrenciesLoading}
            />
        </div>
        <div class="flex justify-center items-center p-2">
            <select
                bind:value={currenciesFilter}
                class="select select-bordered"
            >
                <option value="-1">Все</option>
                <option value="0">Активные</option>
                <option value="1">Неактивные</option>
            </select>
        </div>
        {#if showCurrenciesLoading}
            <span class="loading self-center mt-4"></span>
        {:else}
            <table class="table">
                <thead>
                    <tr>
                        <th>Код</th>
                        <th>Номер (ISO)</th>
                        <th>Страна</th>
                        <th>Статус</th>
                        <th>Minor Units</th>
                        <th>Приоритетный банк (Bybit)</th>
                        <th>Объем</th>
                        <th>ID</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {#each currencies as cur}
                        <tr class="hover">
                            <td>{cur["code"]}</td>
                            <td>{cur["num"]}</td>
                            <td>{cur["country"]}</td>
                            <td
                                class={cur["is_active"] === "t"
                                    ? "text-success"
                                    : "text-error"}
                                >{cur["is_active"] === "t"
                                    ? "Активна"
                                    : "Неактивна"}</td
                            >
                            <td>{cur["minor_unit"]}</td>
                            <td>{cur["priority_bank_bybit"]}</td>
                            <td>{cur["volume"]}</td>
                            <td>{cur["id"]}</td>
                            <td>
                                <button
                                    on:click={() => {
                                        selectedCurrency = cur;
                                        showChangeCurrency = true;
                                    }}
                                    class="btn btn-outline">Изменить</button
                                >
                            </td>
                        </tr>
                    {/each}
                </tbody>
            </table>
        {/if}
    </div>
</div>

{#if showChangeCurrency}
    <div
        class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center"
    >
        <div class="flex flex-col p-4 bg-base-300 rounded-md">
            <p class="font-bold">Изменение валюты {selectedCurrency["code"]}</p>
            <p class="text-sm mt-4">Банк</p>
            <input
                bind:value={newBankValue}
                type="text"
                class="input input-bordered"
            />
            <p class="mt-2 text-sm">Объем</p>
            <input
                bind:value={newVolumeValue}
                type="text"
                class="input input-bordered"
            />

            <button on:click={()=>{
                changeCurrency();
            }} class="btn btn-outline btn-success mt-4">
                Сохранить
            </button>
            <button
                on:click={() => {
                    showChangeCurrency = false;
                }}
                class="btn btn-outline mt-1">Закрыть</button
            >
        </div>
    </div>
{/if}
