<template>
    <SearchBar />
    <div class="d-flex align-items-center">
        <CategoryBtn :lists="yearCategory" />
        <WriteBtn class="mt-2 ms-auto" @click="openModal" />
        <CenterModal :display="isModalOpen" @close="closeModal">
            <template #title> 프로젝트 등록 </template>
            <template #body>
                <FormInput
                    title="이름"
                    name="name"
                    :is-essential="true"
                    :is-alert="nameAlert"
                    @update:modelValue="name = $event"
                />

                <FormSelect
                    title="컬러"
                    name="color"
                    :is-essential="true"
                    :is-label="true"
                    :is-common="true"
                    :data="colorList"
                    @update:data="color = $event"
                />

                <FormInput
                    title="시작 일"
                    type="date"
                    name="startDay"
                    v-model="startDay"
                    :is-essential="true"
                />

                <FormInput
                    title="종료 일"
                    name="endDay"
                    :type="'date'"
                    @update:modelValue="endDay = $event"
                />

                <FormInput
                    title="설명"
                    name="description"
                    @update:modelValue="description = $event"
                />

                <ArrInput
                    title="주소"
                    name="address"
                    :isEssential="true"
                    :is-row="true"
                    :is-alert="addressAlert"
                    @update:data="handleAddressUpdate"
                    @update:alert="addressAlert = $event"
                />
            </template>
            <template #footer>
                <button class="btn btn-secondary" @click="closeModal">Close</button>
                <button class="btn btn-primary" @click="handleSubmit">Save</button>
            </template>
        </CenterModal>
    </div>
    <ProjectCardList :category="selectedCategory" />
</template>

<script setup>
    import SearchBar from '@c/search/SearchBar.vue';
    import ProjectCardList from '@c/list/ProjectCardList.vue';
    import CategoryBtn from '@c/category/CategoryBtn.vue';
    import commonApi from '@/common/commonApi';
    import { inject, onMounted, ref } from 'vue';
    import WriteBtn from '../button/WriteBtn.vue';
    import CenterModal from '../modal/CenterModal.vue';
    import FormSelect from '../input/FormSelect.vue';
    import FormInput from '../input/FormInput.vue';
    import ArrInput from '../input/ArrInput.vue';
    import { useToastStore } from '@s/toastStore';
    import $api from '@api';
    import { useUserInfoStore } from '@/stores/useUserInfoStore';

    const dayjs = inject('dayjs');

    const today = dayjs().format('YYYY-MM-DD');

    const toastStore = useToastStore();
    const userStore = useUserInfoStore();

    const user = ref(null);

    const name = ref('');
    const color = ref('');
    const address = ref('');
    const detailAddress = ref('');
    const postcode = ref('');
    const startDay = ref(today);
    const endDay = ref('');
    const description = ref('');

    const isModalOpen = ref(false);
    const nameAlert = ref(false);
    const addressAlert = ref(false);

    const openModal = () => {
        isModalOpen.value = true;
    };

    const closeModal = () => {
        isModalOpen.value = false;
    };


    const selectedCategory = ref(null);

    const { yearCategory, colorList } = commonApi({
        loadColor: true,
        colorType: 'YNP',
        loadYearCategory: true,
    });

    // 주소 업데이트 핸들러
    const handleAddressUpdate = addressData => {
        address.value = addressData.address;
        detailAddress.value = addressData.detailAddress;
        postcode.value = addressData.postcode;
    };


    onMounted(async () => {
        await userStore.userInfo(); // 로그인한 사용자 정보
        user.value = userStore.user;
    });

    const handleSubmit = async () => {

        nameAlert.value = name.value.trim() === '';
        addressAlert.value = address.value.trim() === '';

        if (nameAlert.value ||  addressAlert.value ) {
            return;
        }

        $api.post('project/insert', {
            projctNam: name.value,
            projctCol: String(color.value),
            projctStr: startDay.value,
            projctEnd: endDay.value || null,
            projctDes: description.value || null,
            projctAdd: address.value,
            projctDtl: detailAddress.value,
            projctZip: postcode.value,
            projctCmb: user.value.name,
        })
        .then(res => {
            if (res.status === 200) {
                toastStore.onToast('프로젝트가 등록되었습니다.', 's');
                closeModal();
                location.reload();
            }
        })
    };

</script>
