<script setup>
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import VnInput from 'src/components/common/VnInput.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import FormModel from 'src/components/FormModel.vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import VnPaginate from 'components/ui/VnPaginate.vue';
import WagonCreateTray from './WagonCreateTray.vue';

const { t } = useI18n();
const { notify } = useQuasar();
const route = useRoute();
const entityId = computed(() => route.params.id);
const wagonTrays = ref([]);
const createTrayFormDialogRef = ref();
const selectedEntityId = ref();

async function loadTrays() {
    try {
        const res = await axios.get('WagonTypeTrays');
        const filteredTrays = res.data.filter(
            (tray) => tray.wagonTypeFk === entityId.value
        );
        wagonTrays.value = filteredTrays;
        return;
    } catch (err) {
        console.error('Error loading trays:', err);
    }
}

async function addTray(newTray) {
    const res = await axios.post(`WagonTypeTrays`, newTray);
    wagonTrays.value.push(res.data);
    notify({
        message: t(`Tray added successfully`),
        type: 'positive',
    });
}

async function deleteTray(trayToDelete) {
    await axios.delete(`WagonTypeTrays/${trayToDelete.id}`);
    const index = wagonTrays.value.findIndex((tray) => tray.id === trayToDelete.id);
    if (index !== -1) {
        wagonTrays.value.splice(index, 1);
    }
    notify({
        message: t('Tray deleted successfully'),
        type: 'positive',
    });
}

const filter = {
    where: { wagonTypeFk: entityId.value },
    include: {
        relation: 'color',
        scope: {
            fields: ['rgb'],
        },
    },
};

const formFilter = { where: { wagonTypeFk: entityId.value } };

const showCreateTrayForm = (id) => {
    selectedEntityId.value = id;
    createTrayFormDialogRef.value.show();
};

watch(
    () => wagonTrays.value,
    async (newVal, oldVal) => {
        if (newVal.length !== oldVal.length) {
            await loadTrays();
        }
    },
    { deep: true }
);
</script>

<template>
    <VnSubToolbar />
    <QPage class="q-pa-sm q-mx-xl">
        <FormModel
            :url="`WagonTypes/ ${entityId}`"
            :url-update="`WagonTypes/ ${entityId}`"
            :filter="formFilter"
            model="WagonType"
            auto-load
        >
            <template #form="{ data }">
                <QCard class="q-pa-md">
                    <VnInput
                        filled
                        v-model="data.name"
                        :label="t('wagon.type.name')"
                        :rules="[(val) => !!val || t('wagon.warnings.nameNotEmpty')]"
                    />
                    <QCheckbox
                        class="q-mb-sm"
                        v-model="data.divisible"
                        label="Divisible"
                    />

                    <VnPaginate
                        data-key="wagonTypeTray"
                        url="WagonTypeTrays"
                        order="id DESC"
                        :filter="filter"
                        auto-load
                        ref="vnPaginateRef"
                        v-bind="$attrs"
                        :key="wagonTrays.length"
                    >
                        <template #body="{ rows }">
                            <div v-for="row in rows" :key="row.id">
                                <div class="shelving"></div>
                                <div class="action-button">
                                    <div class="wagon-tray q-mx-lg">
                                        <div class="position">
                                            <VnInput
                                                borderless
                                                type="number"
                                                disable
                                                class="input-tray q-mb-sm"
                                                :label="t('Height') + ': '"
                                                v-model="row.height"
                                            />
                                        </div>
                                        <div class="shelving">
                                            <div class="shelving-half">
                                                <div class="shelving-up"></div>
                                                <div
                                                    class="shelving-down"
                                                    :style="{
                                                        backgroundColor: row.color.rgb,
                                                    }"
                                                ></div>
                                            </div>
                                            <div
                                                class="shelving-divisible"
                                                :class="{ isVisible: !data.divisible }"
                                            ></div>
                                            <div class="shelving-half">
                                                <div class="shelving-up"></div>
                                                <div
                                                    class="shelving-down"
                                                    :style="{
                                                        backgroundColor: row.color.rgb,
                                                    }"
                                                ></div>
                                            </div>
                                        </div>
                                        <div class="action-button">
                                            <QBtn
                                                v-if="row.height === 0"
                                                flat
                                                round
                                                color="primary"
                                                :icon="'add'"
                                                class="btn-tray"
                                                @click="showCreateTrayForm(entityId)"
                                            />
                                            <QBtn
                                                v-else
                                                flat
                                                round
                                                color="primary"
                                                :icon="'delete'"
                                                class="btn-tray"
                                                @click="deleteTray(row)"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </VnPaginate>
                    <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>
                </QCard>
                <QDialog ref="createTrayFormDialogRef">
                    <WagonCreateTray :entity-id="entityId" @on-submit="addTray($event)" />
                </QDialog>
            </template>
        </FormModel>
    </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;
}

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

    .position {
        width: 26%;
        border-right: 1rem solid gray;
        display: flex;
        align-items: flex-start;
        justify-content: flex-start;
        padding-right: 2rem;
        padding-left: 3rem;
    }

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

        .shelving-half {
            width: 100%;
            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: 20%;
        border-left: 1rem solid gray;
        align-items: baseline;
        padding-left: 3rem;
    }

    .isVisible {
        display: none;
    }
}
.btn-tray {
    margin-right: 100%;
    margin-top: 100%;
}
.input-tray {
    margin-top: 100%;
    margin-left: 40%;
}
</style>

<i18n>
    en:
        tray: Tray
        wagonColor: Wagon color
        Select a tray: Select a tray
    es:
        tray: Bandeja
        wagonColor: Color de la bandeja
        Select a tray: Seleccione una bandeja
        Create new Wagon type: Crear nuevo tipo de vagón
        Add new tray: Añadir nueva bandeja
        Height: Altura
        Tray added successfully: Bandeja añadida correctamente
        Tray deleted successfully: Bandeja eliminada correctamente
</i18n>
