<template>
    <SearchBar @update:data="search"/>
    <div class="d-flex align-items-center">
        <CategoryBtn :lists="yearCategory" @update:data="selectedCategory = $event" />
        <WriteBtn class="mt-2 ms-auto" @click="openCreateModal" />
    </div>

    <!-- 프로젝트 목록 -->
    <div class="mt-4">
        <div v-if="projectList.length === 0" class="text-center">
            <p class="text-muted mt-4">게시물이 없습니다.</p>
        </div>

        <div v-for="post in projectList" :key="post.PROJCTSEQ" @click="openEditModal(post)" class="cursor-pointer">
            <ProjectCard
                :title="post.PROJCTNAM"
                :description="post.PROJCTDES"
                :strdate="post.PROJCTSTR"
                :enddate="post.PROJCTEND"
                :address="post.PROJCTARR + ' ' + post.PROJCTDTL"
                :projctSeq="post.PROJCTSEQ"
                :projctCol="post.projctcolor"
            />
        </div>
    </div>

    <!-- 등록 모달 -->
    <CenterModal :display="isCreateModalOpen" @close="closeCreateModal">
        <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>
            <BackButton @click="closeCreateModal" />
            <SaveButton @click="handleCreate" />
        </template>
    </CenterModal>

    <!-- 수정 모달 -->
    <CenterModal :display="isEditModalOpen" @close="closeEditModal">
        <template #title> 프로젝트 수정 </template>
        <template #body>
            <FormInput
                title="이름"
                name="name"
                :is-essential="true"
                :is-alert="nameAlert"
                :modelValue="selectedProject.PROJCTNAM"
                @update:modelValue="selectedProject.PROJCTNAM = $event"
            />

            <FormSelect
                title="컬러"
                name="color"
                :is-essential="true"
                :is-label="true"
                :is-common="true"
                :data="allColors"
                :value="selectedProject.PROJCTCOL"
                @update:data="selectedProject.PROJCTCOL = $event"
            />

            <FormInput
                title="시작일"
                type="date"
                name="startDay"
                :is-essential="true"
                :modelValue="selectedProject.PROJCTSTR"
                @update:modelValue="selectedProject.PROJCTSTR = $event"
            />

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

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

            <ArrInput
                title="주소"
                name="address"
                :is-essential="true"
                :is-row="true"
                :modelValue="selectedProject"
                @update:data="updateAddress"
            />
        </template>
        <template #footer>
            <BackButton @click="closeEditModal" />
            <SaveButton @click="handleUpdate" />
        </template>
    </CenterModal>
</template>

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

const dayjs = inject('dayjs');
const today = dayjs().format('YYYY-MM-DD');
const toastStore = useToastStore();
const userStore = useUserInfoStore();

// 상태 관리
const user = ref(null);
const projectList = ref([]);
const filteredProjects = ref([]);
const selectedCategory = ref(null);
const searchText = ref('');

// 등록 모달 상태
const isCreateModalOpen = ref(false);
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 nameAlert = ref(false);
const addressAlert = ref(false);

// 수정 모달 상태
const isEditModalOpen = ref(false);
const originalColor = ref('');
const selectedProject = ref({
    PROJCTSEQ: '',
    PROJCTNAM: '',
    PROJCTSTR: '',
    PROJCTEND: '',
    PROJCTZIP: '',
    PROJCTARR: '',
    PROJCTDTL: '',
    PROJCTDES: '',
    PROJCTCOL: '',
    projctcolor: '',
});

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

// 프로젝트 목록 조회
const getProjectList = async () => {
    const res = await $api.get('project/select', {
        params: {
            searchKeyword : searchText.value,
            category : selectedYear.value,
        },
    });
    projectList.value = res.data.data.projectList;
};

// 검색 처리
const search = async (searchKeyword) => {
    searchText.value = searchKeyword.trim();
    await getProjectList();
};

const selectedYear = computed(() => {
    if (!selectedCategory.value || selectedCategory.value === 900101) {
        return null;
    }
    // 선택된 category 값 label 값으로 변환
    return yearCategory.value.find(item => item.value === selectedCategory.value)?.label || null;
});


// 카테고리 변경 감지
watch(selectedCategory, async () => {
    await getProjectList();
});

// 등록 모달 관리
const openCreateModal = () => {
    isCreateModalOpen.value = true;
};

const closeCreateModal = () => {
    isCreateModalOpen.value = false;
};

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

const handleCreate = 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: color.value,
        projctStr: startDay.value,
        projctEnd: endDay.value || null,
        projctDes: description.value || null,
        projctArr: address.value,
        projctDtl: detailAddress.value,
        projctZip: postcode.value,
        projctCmb: user.value.name,
    })
    .then(res => {
        if (res.status === 200) {
            toastStore.onToast('프로젝트가 등록되었습니다.', 's');
            closeCreateModal();
            location.reload();
        }
    });
};

// 수정 모달 관리
const openEditModal = (post) => {
    isEditModalOpen.value = true;
    selectedProject.value = { ...post };
    originalColor.value = post.PROJCTCOL;
};

const closeEditModal = () => {
    isEditModalOpen.value = false;
};

// 기존 컬러 + 사용 가능 한 컬러
const allColors = computed(() => {
    const existingColor = { value: selectedProject.value.PROJCTCOL, label: selectedProject.value.projctcolor };
    return [existingColor, ...colorList.value];
});

// 변경된 내용 있는지 확인
const hasChanges = computed(() => {
    const original = projectList.value.find(p => p.PROJCTSEQ === selectedProject.value.PROJCTSEQ);
    if (!original) return false;

    return (
        original.PROJCTNAM !== selectedProject.value.PROJCTNAM ||
        original.PROJCTCOL !== selectedProject.value.PROJCTCOL ||
        original.PROJCTARR !== selectedProject.value.PROJCTARR ||
        original.PROJCTDTL !== selectedProject.value.PROJCTDTL ||
        original.PROJCTZIP !== selectedProject.value.PROJCTZIP ||
        original.PROJCTSTR !== selectedProject.value.PROJCTSTR ||
        original.PROJCTEND !== selectedProject.value.PROJCTEND ||
        original.PROJCTDES !== selectedProject.value.PROJCTDES
    );
});

// 수정 :: 주소
const updateAddress = (addressData) => {
    selectedProject.value = {
        ...selectedProject.value,
        PROJCTZIP: addressData.postcode,
        PROJCTARR: addressData.address,
        PROJCTDTL: addressData.detailAddress
    };
};

const handleUpdate = () => {
    if (!hasChanges.value) {
        toastStore.onToast('변경된 내용이 없습니다.', 'e');
        return;
    }

    $api.patch('project/update', {
        projctSeq: selectedProject.value.PROJCTSEQ,
        projctNam: selectedProject.value.PROJCTNAM,
        projctCol: selectedProject.value.PROJCTCOL,
        projctArr: selectedProject.value.PROJCTARR,
        projctDtl: selectedProject.value.PROJCTDTL,
        projctZip: selectedProject.value.PROJCTZIP,
        projctStr: selectedProject.value.PROJCTSTR,
        projctEnd: selectedProject.value.PROJCTEND || null,
        projctDes: selectedProject.value.PROJCTDES,
        projctUmb: user.value.name,
        originalColor: originalColor.value === selectedProject.value.PROJCTCOL ? null : originalColor.value
    }).then(res => {
        if (res.status === 200) {
            toastStore.onToast('수정이 완료 되었습니다.', 's');
            closeEditModal();
            location.reload();
        }
    });
};

onMounted(async () => {
    await getProjectList();
    await userStore.userInfo();
    user.value = userStore.user;
});
</script>
