<template>
    <div class="recipe-reviews my-3">
        <div class="d-flex justify-content-end" v-if="!hasUserReviewed && isLoggedIn">
            <button type="button" class="btn btn-primary fw-bold w-25 mt-3 text-light" data-bs-toggle="modal"
                data-bs-target="#add-review-modal">
                Tambah Ulasan
            </button>
        </div>

        <!-- Add Review Modal -->
        <div class="modal fade modal-lg" id="add-review-modal" tabindex="-1" aria-labelledby="" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Beri Ulasan</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="addReview">
                            <div class="row container">
                                <p class="col-4">Rating</p>
                                <div class="rating-input col">
                                    <label v-for="star in stars" :key="star.value"
                                        :style="{ color: getStarColor(star.value) }">
                                        <input type="radio" name="rating" :value="star.value" v-model="review.rating"
                                            class="radio-button" />
                                        <span class="icon" @click="selectStar(star.value)">
                                            <i class="fa-solid fa-star fa-xl"></i>
                                        </span>
                                    </label>
                                </div>
                            </div>
                            <div class="my-3">
                                <textarea class="form-control" name="comment" placeholder="Tulis ulasan di sini"
                                    v-model="review.comment"></textarea>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                <button type="submit" class="btn btn-primary" name="add_review"
                                    data-bs-dismiss="modal">Kirim</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reviews -->
        <div class="reviews">
            <h2 class="fw-bolder">Ulasan</h2>
            <div v-if="errorMessage" class="review-not-found">
                <p class="fs-4 text-center my-3">{{ errorMessage }}</p>
            </div>
            <div v-else v-for="review in reviews" :key="review.id" class="review">
                <div class="card px-4 py-2 mt-3 mb-2">
                    <!-- Review content -->
                    <div class="d-flex align-items-start my-3">
                        <img :src="getPhotoUrl(review.user.profile_picture)" class="rounded-circle float-start"
                            alt="Profile pict" style="width:70px;height:70px;">
                        <div class="w-100">
                            <div class="flex-column ms-3 mt-1">
                                <span class="fw-bold d-inline-block">{{ review.user.name }}</span>
                                <div class="star d-block my-1">
                                    <Rating :rating="review.rating" />
                                </div>
                                <p class="pt-2">{{ review.comment }}</p>
                            </div>
                        </div>
                        <div v-if="review.user.id === loggedInUserId" class="flex-shrink-1">
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary dropdown-toggle border border-0" type="button"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fa-solid fa-ellipsis"></i>
                                </button>
                                <ul class="dropdown-menu">
                                    <li>
                                        <a class="dropdown-item" href="#" data-bs-toggle="modal"
                                            :data-bs-target="`#edit-review-modal-${review.id}`"
                                            @click="setReviewValue(review)">
                                            <i class="fa-solid fa-pen-to-square mx-1 text-warning"></i> Edit
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="#" data-bs-toggle="modal"
                                            :data-bs-target="`#delete-review-modal-${review.id}`">
                                            <i class="fa-solid fa-trash-can mx-1 text-danger"></i> Delete
                                        </a>
                                    </li>
                                </ul>
                            </div>

                            <div class="modal fade modal-lg" :id="`edit-review-modal-${review.id}`" tabindex="-1"
                                aria-labelledby="">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">Beri Ulasan</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <form @submit.prevent="editReview(review)">
                                                <div class="row container">
                                                    <p class="col-4">Rating</p>
                                                    <div class="rating-input col">
                                                        <label v-for="star in stars" :key="star.value"
                                                            :style="{ color: getStarColor(star.value) }">
                                                            <input type="radio" name="rating" :value="star.value"
                                                                v-model="review.rating" class="radio-button" />
                                                            <span class="icon" @click="selectStar(star.value)">
                                                                <i class="fa-solid fa-star fa-xl"></i>
                                                            </span>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="my-3">
                                                    <textarea class="form-control" name="comment"
                                                        placeholder="Tulis ulasan di sini"
                                                        v-model="review.comment"></textarea>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary"
                                                        data-bs-dismiss="modal">Batal</button>
                                                    <button type="submit" class="btn btn-primary" name="edit_review"
                                                        data-bs-dismiss="modal">Kirim</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="modal fade" :id="`delete-review-modal-${review.id}`" tabindex="-1"
                                aria-labelledby="">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">Hapus Review</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <form @submit.prevent="deleteReview(review.id)">
                                            <div class="modal-body">
                                                <label for="delete_review">Apa kamu yakin ingin menghapus review
                                                    ini?</label>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary"
                                                    data-bs-dismiss="modal">Batal</button>
                                                <button type="submit" class="btn btn-primary" name="delete_review"
                                                    data-bs-dismiss="modal">Hapus</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
  
<script>
import Rating from './Rating.vue';
import api from "@/api";
import { isUserLoggedIn } from "@/utils/token.js";

export default {
    props: {
        recipeId: {
            type: Number,
            required: true,
        },
    },
    data() {
        return {
            loggedInUserId: null,
            reviews: [],
            stars: [
                { value: 1 },
                { value: 2 },
                { value: 3 },
                { value: 4 },
                { value: 5 },
            ],
            review: {
                rating: 0,
                comment: '',
            },
            isReviewed: false,
            errorMessage: '',
        };
    },
    mounted() {
        this.fetchLoggedInUserId();
        this.fetchReviews();
    },
    computed: {
        hasUserReviewed() {
            return this.reviews.some(review => review.user.id === this.loggedInUserId);
        },
        isLoggedIn() {
            return isUserLoggedIn();
        },
    },
    methods: {
        getPhotoUrl(photo) {
            return `http://easycookapi.dummybox.my.id${photo}`;
        },
        async fetchLoggedInUserId() {
            try {
                if (this.isLoggedIn) {
                    const response = await api.get("/profiles/account/");
                    this.loggedInUserId = response.data.user.id;
                }
            } catch (error) {
                console.error(error);
            }
        },
        async fetchReviews() {
            try {
                const response = await api.get(`/recipes/${this.recipeId}/reviews/`);
                this.reviews = response.data;
            } catch (error) {
                if (error.response && error.response.status === 404) {
                    this.reviews = [];
                    this.errorMessage = error.response.data.message;
                }
            }
        },
        getStarColor(starValue) {
            return starValue <= this.review.rating ? "#F29D38" : "#CCC";
        },
        selectStar(starValue) {
            this.review.rating = starValue;
        },
        async addReview() {
            try {
                if (this.isLoggedIn) {
                    const reviewData = {
                        rating: this.review.rating,
                        comment: this.review.comment,
                    };

                    await api.post(`/recipes/${this.recipeId}/reviews/`, reviewData);
                    this.fetchReviews();
                    this.$emit("review-updated");
                    document.getElementById('add-review-modal').classList.remove('show');
                }
            } catch (error) {
                console.error(error);
            }
        },
        async fetchReview(reviewId) {
            try {
                if (this.isLoggedIn) {
                    const response = await api.get(`/recipes/${this.recipeId}/reviews/${reviewId}/`);
                    this.review = response.data;
                }
            } catch (error) {
                console.error(error);
            }
        },
        setReviewValue(review) {
            this.review.rating = review.rating;
            this.review.comment = review.comment;
        },
        async editReview(review) {
            try {
                if (this.isLoggedIn) {
                    const reviewData = {
                        rating: review.rating,
                        comment: review.comment,
                    };

                    await api.put(`/recipes/${this.recipeId}/reviews/${review.id}/`, reviewData);

                    this.$emit("review-updated");
                    document.getElementById(`edit-review-modal-${review.id}`).classList.remove('show');
                }
            } catch (error) {
                console.error(error);
            }
        },
        async deleteReview(reviewId) {
            try {
                if (this.isLoggedIn) {
                    await api.delete(`/recipes/${this.recipeId}/reviews/${reviewId}/`);

                    this.fetchReviews();
                    this.$emit("review-updated");
                    this.isReviewed = false
                    document.getElementById(`delete-review-modal-${reviewId}`).classList.remove('show');
                }
            } catch (error) {
                console.error(error);
            }
        },
    },
    components: {
        Rating
    },
};
</script>
  
<style scoped>
.rating-input {
    display: inline-flex;
    align-items: center;
}

.rating-input label {
    margin-right: 5px;
    cursor: pointer;
}

.rating-input input[type='radio'] {
    display: none;
}

.rating-input .icon {
    cursor: pointer;
}

.review {
    display: flex;
    align-items: center;
}

.star {
    display: flex;
    align-items: center;
}

.review .card {
    flex: 1;
}

.review .card img {
    width: 70px;
    height: 70px;
}
</style>
  