<script setup>
import { computed, ref, onMounted, onUpdated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useQuasar } from 'quasar';

import VnInput from 'src/components/common/VnInput.vue';

import { useI18n } from 'vue-i18n';
import axios from 'axios';

onMounted(() => fetch());
onUpdated(() => fetch());

const { t } = useI18n();
const route = useRoute();
const quasar = useQuasar();
const router = useRouter();
const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});
const entityId = computed(() => $props.id || route.params.id);

const zone = ref([]);
const divisible = ref(false);
const name = ref('');
const colorPickerActive = ref(false);
let originalData = { trays: [] };
let zoneConfig;
let zoneUpcomingColors;
let currentTrayColorPicked;

async function fetch() {
    try {
        await axios.get('ZoneConfigs').then(async (res) => {
            if (res.data) {
                zoneConfig = res.data[0];
            }
        });

        await axios.get(`ZoneUpcomingColors`).then(async (res) => {
            if (res.data) {
                zoneUpcomingColors = res.data;
                if (!entityId.value)
                    zone.value.push({
                        id: 0,
                        position: 0,
                        color: { ...zoneUpcomingColors[0] },
                        action: 'add',
                    });
                else {
                    await axios
                        .get(`ZoneUpcomingTrays`, {
                            params: { filter: { where: { typeFk: entityId.value } } },
                        })
                        .then(async (res) => {
                            if (res.data) {
                                for (let i = 0; i < res.data.length; i++) {
                                    const tray = res.data[i];
                                    zone.value.push({
                                        id: res.data.length - i - 1,
                                        position: tray.height,
                                        color: {
                                            ...zoneUpcomingColors.find((color) => {
                                                return color.id === tray.colorFk;
                                            }),
                                        },
                                        action: tray.height == 0 ? 'add' : 'delete',
                                    });
                                }
                                zone.value.forEach((value) => {
                                    originalData.trays.push({ ...value });
                                });
                            }
                        });
                }
            }
        });

        if (entityId.value) {
            await axios.get(`ZoneUpcomings/${entityId.value}`).then((res) => {
                if (res.data) {
                    originalData.name = name.value = res.data.name;
                    originalData.divisible = divisible.value = res.data.divisible;
                }
            });
        }
    } catch (e) {
        //
    }
}

function addTray() {
    if (
        zone.value.find((tray) => {
            return tray.position == null;
        })
    ) {
        quasar.notify({
            message: t('zone.warnings.uncompleteTrays'),
            type: 'warning',
        });
        return;
    }

    if (zone.value.length < zoneConfig.maxTrays) {
        zone.value.unshift({
            id: zone.value.length,
            position: null,
            color: { ...zoneUpcomingColors[0] },
            action: 'delete',
        });
    } else {
        quasar.notify({
            message: t('zone.warnings.maxTrays'),
            type: 'warning',
        });
    }
}

function deleteTray(trayToDelete) {
    zone.value = zone.value.filter((tray) => tray.id !== trayToDelete.id);
    reorderIds();
}

function reorderIds() {
    for (let index = zone.value.length - 1; index >= 0; index--) {
        zone.value[index].id = index;
    }
}

async function onSubmit() {
    try {
        const path = entityId.value
            ? 'ZoneUpcomings/editZoneUpcoming'
            : 'ZoneUpcomings/createZoneUpcoming';

        const params = {
            id: entityId.value,
            name: name.value,
            divisible: divisible.value,
            trays: zone.value,
        };

        await axios.patch(path, params).then((res) => {
            if (res.status == 204) router.push({ path: `/zone/type/list` });
        });
    } catch (error) {
        //
    }
}

function onReset() {
    name.value = entityId.value ? originalData.name : null;
    divisible.value = entityId.value ? originalData.divisible : false;
    zone.value = entityId.value
        ? [...originalData.trays]
        : [
              {
                  id: 0,
                  position: 0,
                  color: { ...zoneUpcomingColors[0] },
                  action: 'add',
              },
          ];
}

function doAction(tray) {
    if (tray.action == 'add') {
        addTray();
    } else {
        deleteTray(tray);
    }
}

function showColorPicker(tray) {
    colorPickerActive.value = true;
    currentTrayColorPicked = zone.value.findIndex((val) => {
        return val.id === tray.id;
    });
}

function updateColor(newColor) {
    zone.value[currentTrayColorPicked].color = {
        ...zoneUpcomingColors.find((color) => {
            return color.rgb === newColor;
        }),
    };
}

function onPositionBlur(tray) {
    if (tray.position) {
        if (tray.position == '' || tray.position < 0) {
            tray.position = null;
            return;
        }
        tray.position = parseInt(tray.position);
        zone.value.sort((a, b) => b.position - a.position);
        reorderIds();
        for (let index = zone.value.length - 1; index > 0; index--) {
            if (exceedMaxHeight(index - 1)) continue;
            if (
                zone.value[index - 1].position - zone.value[index].position >=
                zoneConfig.minHeightBetweenTrays
            ) {
                continue;
            } else {
                zone.value[index - 1].position +=
                    zoneConfig.minHeightBetweenTrays -
                    (zone.value[index - 1].position - zone.value[index].position);

                quasar.notify({
                    message:
                        t('zone.warnings.minHeightBetweenTrays') +
                        zoneConfig.minHeightBetweenTrays +
                        ' cm',
                    type: 'warning',
                });

                exceedMaxHeight(index - 1);
            }
        }
    }
}

function exceedMaxHeight(pos) {
    if (zone.value[pos].position > zoneConfig.maxZoneHeight) {
        zone.value.splice(pos, 1);
        quasar.notify({
            message: t('zone.warnings.maxZoneHeight') + zoneConfig.maxZoneHeight + ' cm',
            type: 'warning',
        });
        return true;
    }
    return false;
}
</script>

<template>
    <QPage class="q-pa-sm q-mx-xl">
        <QForm @submit="onSubmit()" @reset="onReset()" class="q-pa-sm">
            <QCard class="q-pa-md">
                <VnInput
                    filled
                    v-model="name"
                    :label="t('zone.upcoming.name')"
                    :rules="[(val) => !!val || t('zone.warnings.nameNotEmpty')]"
                />
                <QCheckbox class="q-mb-sm" v-model="divisible" label="Divisible" />
                <div class="zone-tray q-mx-lg" v-for="tray in zone" :key="tray.id">
                    <div class="position">
                        <QInput
                            autofocus
                            filled
                            type="number"
                            :class="{ isVisible: tray.action == 'add' }"
                            v-model="tray.position"
                            @blur="onPositionBlur(tray)"
                        >
                            <QTooltip :delay="2000">
                                {{
                                    t('zone.warnings.minHeightBetweenTrays') +
                                    zoneConfig.minHeightBetweenTrays +
                                    ' cm'
                                }}
                                <QSpace />
                                {{
                                    t('zone.warnings.maxZoneHeight') +
                                    zoneConfig.maxZoneHeight +
                                    ' cm'
                                }}
                            </QTooltip>
                        </QInput>
                    </div>
                    <div class="shelving">
                        <div class="shelving-half">
                            <div class="shelving-up"></div>
                            <div
                                class="shelving-down"
                                :style="{ backgroundColor: tray.color.rgb }"
                                @click="showColorPicker(tray)"
                            ></div>
                        </div>
                        <div
                            class="shelving-divisible"
                            :class="{ isVisible: !divisible }"
                        ></div>
                        <div class="shelving-half">
                            <div class="shelving-up"></div>
                            <div
                                class="shelving-down"
                                :style="{ backgroundColor: tray.color.rgb }"
                                @click="showColorPicker(tray)"
                            ></div>
                        </div>
                    </div>
                    <div class="action-button">
                        <QBtn
                            flat
                            round
                            color="primary"
                            :icon="tray.action"
                            @click="doAction(tray)"
                        />
                    </div>
                </div>
                <div class="q-mb-sm wheels">
                    <QIcon color="grey-6" name="trip_origin" size="xl" />
                    <QIcon color="grey-6" name="trip_origin" size="xl" />
                </div>
                <QDialog
                    v-model="colorPickerActive"
                    position="right"
                    :no-backdrop-dismiss="false"
                >
                    <QCard>
                        <QCardSection>
                            <div class="text-h6">{{ t('zone.upcoming.trayColor') }}</div>
                        </QCardSection>
                        <QCardSection class="row items-center no-wrap">
                            <QColor
                                flat
                                v-model="zone[currentTrayColorPicked].color.rgb"
                                no-header
                                no-footer
                                default-view="palette"
                                :palette="
                                    zoneUpcomingColors.map((color) => {
                                        return color.rgb;
                                    })
                                "
                                @change="updateColor($event)"
                            />
                            <QBtn flat round icon="close" v-close-popup />
                        </QCardSection>
                    </QCard>
                </QDialog>
            </QCard>
            <div class="q-mt-md">
                <QBtn :label="t('zone.upcoming.submit')" type="submit" color="primary" />
                <QBtn
                    :label="t('zone.upcoming.reset')"
                    type="reset"
                    color="primary"
                    flat
                    class="q-ml-sm"
                />
            </div>
        </QForm>
    </QPage>
</template>

<style lang="scss" scoped>
.q-page {
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

.q-form {
    width: 70%;
}

.q-dialog {
    .q-card {
        width: 100%;
    }
}

.wheels {
    margin-left: 5%;
    display: flex;
    justify-content: space-around;
}

.zone-tray {
    display: flex;
    height: 6rem;

    .position {
        width: 20%;
        border-right: 1rem solid gray;
        display: flex;
        align-items: flex-end;
        justify-content: flex-end;
        padding-right: 1rem;
    }

    .shelving {
        display: flex;
        width: 75%;

        .shelving-half {
            width: 50%;
            height: 100%;

            .shelving-up {
                height: 80%;
                width: 100%;
            }

            .shelving-down {
                height: 20%;
                width: 100%;
            }
        }

        .shelving-divisible {
            width: 1%;
            height: 100%;
            border-left: 0.5rem dashed grey;
            border-right: 0.5rem dashed grey;
        }
    }

    .action-button {
        width: 10%;
        border-left: 1rem solid gray;
        display: flex;
        align-items: flex-end;
        justify-content: flex-start;
        padding-left: 1rem;
    }

    .isVisible {
        display: none;
    }
}
</style>
