<script setup lang="ts">
import { ResumeComponentPlacement, ResumeInputData } from '@/types/resume';
import Button from '../ui/button/Button.vue';
import { ChevronLeft } from 'lucide-vue-next';
import { SidebarGroup, SidebarGroupLabel } from '@/components/ui/sidebar';
import ResumeComponentEditForm from './ResumeComponentEditForm.vue';
import { httpApi } from '@/lib/utils';
import { useResumesStore } from '@/stores/resume';

const SEND_CHANGED_DATA_DELAY = 500;

const resumeStore = useResumesStore();
const selectedComponent = resumeStore.currentSelectedResumePlacement;

let delayedSendTimeout: ReturnType<typeof setTimeout> | null = null
async function sendChangedData(newData: ResumeInputData[]) {
    const newSelectedComponent: ResumeComponentPlacement = {
        ...selectedComponent.value,
        component_data: {
            ...selectedComponent.value?.component_data,
            input_data: newData
        }
    };

    let data, error;

    if (delayedSendTimeout) {
        clearTimeout(delayedSendTimeout);
    }
    delayedSendTimeout = setTimeout(async () => {
        // const { data, error } = await httpApi(route('resume-component-placements.update', newSelectedComponent), {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //         'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
        //         'Accept': 'application/json'
        //     },
        //     body: JSON.stringify({ ...newSelectedComponent, _method: 'PUT' })
        // }, {immediate: true});
        // // Handle error
        // if (error) {
        //     console.error('Failed to update component placement:', error, data);
        //     return;
        // }
        resumeStore.modifyCurrentSelectedResumePlacementToApi(newSelectedComponent!);
    }, SEND_CHANGED_DATA_DELAY);


    // Handle error
    if (error) {
        console.error('Failed to update component placement:', error, data);
        return;
    }

    resumeStore.modifyCurrentSelectedResumePlacement(newSelectedComponent!);
}
</script>

<template>
    <div class="h-full w-full">
        <Button @click="resumeStore.clearSelectedResumePlacement();" variant="outline" size="icon" class="cursor-pointer"><ChevronLeft class="w-4 h-4" /></Button>
        <SidebarGroup class="w-full p-0">
            <SidebarGroupLabel>{{ selectedComponent?.component_data?.component?.name }}</SidebarGroupLabel>
            <ResumeComponentEditForm
                v-if="selectedComponent?.component_data?.input_data"
                :data="selectedComponent?.component_data?.input_data!"
                @data-changed="sendChangedData($event)"
            />
            <p v-else class="text-destructive">No component input data : {{ selectedComponent?.component_data }}</p>
        </SidebarGroup>
    </div>
</template>
