<template>
    <div class="container mt-4 px-4">
        <div class="card-header pb-2 mb-4">
            <div class="card-title m-0">
                <h6 class="fs-2 fw-bolder m-0 mt-3">Ingredient in Your Pantry</h6>
                <div class="mb-4 mt-2">
                    <form @submit.prevent="handleSubmit">
                        <div class="row">
                            <div class="col-sm-6">
                                <model-select :options="rawMaterials" v-model="item" placeholder="Bahan"
                                    class="form-control">
                                </model-select>
                            </div>
                            <div class="col-sm-3">
                                <model-select :options="units" v-model="unit_id" placeholder="Satuan"
                                    @click="fetchUnitByRawIngredient">
                                </model-select>
                            </div>
                            <div class="col-sm-3">
                                <input type="number" class="form-control" id="amount" v-model="amount" placeholder="Jumlah"
                                    min="0">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary text-light mt-3" style="width: 200px;">Save
                            ingredients</button>
                    </form>
                </div>

                <div class="row">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Stock</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in userRawMaterials" :key="item.raw_ingredient">
                                <td class="text-capitalize">{{ item.raw_ingredient }}</td>
                                <td>{{ item.amount }} {{ item.unit }}</td>
                                <td>
                                    <button class="btn btn-close" @click="deleteItem(item.id)"></button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="text-center mx-auto mt-4">
            <h2 class="fw-bolder">Recipe Recommendation</h2>
            <h6>There are {{ recipes.length }} recipes that suits for you</h6>
        </div>
        <div class="card-body row row-cols-3 py-4 justify-content-evenly">
            <MenuCard v-for="recipe in recipes" :key="recipe.id" :recipe="recipe" :source="source_tag"
                @favorite-updated="fetchRecipeRecommendation" />
        </div>
    </div>
</template>
  
<script>
import MenuCard from '@/components/MenuCard.vue';
import api from '@/api';
import { ModelSelect } from 'vue-search-select'

export default {
    data() {
        return {
            item: 0,
            amount: null,
            unit_id: null,
            userRawMaterials: [],
            rawMaterials: [],
            units: [],
            recipes: [],
            showRecommendations: false,
            source_tag: 'my_pantry',
        };
    },
    mounted() {
        this.fetchAllRawMaterial();
        this.getUserRawMaerial();
        this.fetchRecipeRecommendation();
    },
    computed: {
        filteredItems() {
            return this.rawMaterials.filter(i => {
                return i.text.toLowerCase().indexOf(this.tag.toLowerCase()) !== -1;
            });
        },
    },
    methods: {
        reset() {
            this.item = {}
        },
        selectFromParentComponent1() {
            // select option from parent component
            this.item = this.options[0]
        },
        async fetchAllRawMaterial() {
            try {
                const response = await api.get('/recipes/raw-material/');
                this.rawMaterials = response.data.map(item => {
                    return {
                        ...item,
                        value: item.id,
                        text: item.name,
                    };
                });
            } catch (error) {
                console.error(error.response);
            }
        },
        async handleSubmit() {
            const rawMaterialsByUser = {
                id: this.item,
                amount: this.amount,
                unit_id: this.unit_id
            }

            await api.post('/profiles/pantry/', rawMaterialsByUser)
                .then(response => {
                    this.showRecommendations = true;
                    this.getUserRawMaerial();
                    this.fetchRecipeRecommendation()
                })
                .catch(error => {
                    console.error(error.response.response);
                });
        },
        async fetchRecipeRecommendation() {
            try {
                const response = await api.get('/profiles/pantry/recommendations/');
                this.recipes = response.data
            } catch (error) {
                console.error(error.response);
            }
        },
        async fetchUnitByRawIngredient() {
            try {
                const response = await api.get(`/recipes/units?raw_ingredient_id=${this.item}`)
                this.units = response.data.map(item => {
                    return {
                        ...item,
                        value: item.id,
                        text: item.code,
                    };
                });
            } catch (error) {
                console.error(error.response);
            }
        },
        async getUserRawMaerial() {
            try {
                const response = await api.get('/profiles/pantry/');
                this.userRawMaterials = response.data
            } catch (error) {
                console.error(error.response);
            }
        },
        async deleteItem(pantry_id) {
            try {
                await api.delete(`/profiles/pantry/${pantry_id}`);
                this.getUserRawMaerial();
                this.fetchRecipeRecommendation()
            } catch (error) {
                console.error(error.response.response);
            }
        }
    },
    components: {
        MenuCard,
        ModelSelect
    },
};
</script>