<template>
    <v-row no-gutters class="pa-3">
        <v-col cols="12">
            <v-card width="100%" variant="outlined" border="thin" rounded="lg" max-width="700" max-height="500"
                style="overflow-y: auto;">
                <v-toolbar density="compact" color="grey-lighten-4 pl-2 pr-4">
                    <v-row v-if="!hideTitle" no-gutters class="px-3 font-weight-bold">
                        Delivery Companies
                    </v-row>

                    <template #append>
                        <v-btn v-if="!props.readOnly" variant="flat" color="primary" class="text-none"
                            @click="handleAdd">
                            Add
                        </v-btn>
                    </template>
                </v-toolbar>

                <v-card-text class="pa-0" style="min-height: 100px;">
                    <template v-if="companies.length > 0">
                        <draggable :list="companies" item-key="index" class="drag-area"
                            :disabled="editingIndex !== null">
                            <v-list-item v-for="(item, index) in companies" :key="index" class="mt-1">
                                <v-row class="d-flex justify-space-between align-center" no-gutters>
                                    <span class="d-flex align-center">
                                        <v-btn icon="mdi-drag" class="drag-handle text-grey mr-2" flat
                                            density="compact" />

                                        <div v-if="editingIndex === index" class="w-full">
                                            <v-text-field v-model="editedValue" class="text-subtitle-2"
                                                prepend-icon="mdi-truck" style="min-width: 300px;" density="compact"
                                                hide-details autofocus />
                                        </div>

                                        <div v-else>
                                            <span>
                                                <v-icon icon="mdi-truck" class="text-h6 mr-2" />
                                            </span>
                                            {{ item }}
                                        </div>
                                    </span>

                                    <span class="d-flex align-center ga-2">
                                        <template v-if="editingIndex === index">
                                            <v-btn icon="mdi-check" color="green" density="compact"
                                                @click="saveEdit(index)" />
                                            <v-btn icon="mdi-close" color="grey" density="compact"
                                                @click="cancelEdit" />
                                        </template>

                                        <template v-else>
                                            <v-btn v-if="!props.readOnly" flat icon="mdi-pencil" class="text-grey"
                                                density="compact" @click="startEdit(index)" />
                                            <v-btn v-if="!props.readOnly" flat icon="mdi-trash-outline" class="text-red"
                                                density="compact" @click="handleRemove(index)" />
                                        </template>
                                    </span>
                                </v-row>
                            </v-list-item>
                        </draggable>
                    </template>

                    <div v-else class="text-center py-5">
                        No delivery companies added yet.
                    </div>
                </v-card-text>
            </v-card>
        </v-col>

        <v-dialog v-model="dialog.add" persistent width="450">
            <v-card width="100%">
                <v-toolbar>
                    <v-row no-gutters class="fill-height px-6" align="center">
                        <span class="font-weight-bold text-h5 text-capitalize">
                            Add Delivery Company
                        </span>
                    </v-row>
                </v-toolbar>

                <v-card-text>
                    <v-text-field v-model="editedValue" placeholder="Company Name" autofocus />
                </v-card-text>

                <v-toolbar>
                    <v-row no-gutters justify="end" align="center" class="px-5">
                        <v-btn variant="text" text="Cancel" @click="dialog.add = false" />
                        <v-btn variant="flat" color="primary" class="text-none ml-2"
                            @click="saveEdit(companies.length)">
                            Add
                        </v-btn>
                    </v-row>
                </v-toolbar>
            </v-card>
        </v-dialog>

        <Snackbar v-model="toast.show" :text="toast.message" :color="toast.color" />

        <v-dialog v-model="dialog.delete" persistent width="450">
            <CardDeleteConfirmation
                :prompt-title="`Are you sure you want to delete this ${companies?.[deleteIndex!]}?`"
                @close="dialog.delete = false"
                @delete="removeCompany(deleteIndex!)"
            />
        </v-dialog>
    </v-row>
</template>

<script setup lang="ts">
import useSiteSettings from '../composables/useSiteSettings'

const props = defineProps<{
    site: string
    readOnly?: boolean
    hideTitle?: boolean
}>()

const emit = defineEmits<{
    (e: 'update:companiesValue', value: string[]): void
    (e: 'refresh-site'): void
}>()

const { updateSitebyId } = useSiteSettings()

const initialCompanies = defineModel<string[]>('initial', {
    type: Array,
    default: []
})

const dialog = reactive({
    add: false,
    delete: false,
})

const toast = reactive({
    show: false,
    message: '',
    color: 'success',
})

const companies = ref<string[]>([])
const editingIndex = ref<number | null>(null)
const editedValue = ref('')
const isHydrating = ref(true)
const deleteIndex = ref<number | null>(null)



watch(
    companies,
    async (newVal) => {
        await persistCompanies()
    },
    { deep: true, immediate: false }
)

const startEdit = (index: number) => {
    editingIndex.value = index
    editedValue.value = companies.value[index] || ''
}

const saveEdit = async (index: number) => {
    const value = editedValue.value.trim()
    if (!value) return

    const updated = [...companies.value]

    if (index >= updated.length) {
        updated.push(value)
    } else {
        updated[index] = value
    }

    companies.value = updated
    editingIndex.value = null
    editedValue.value = ''
    dialog.add = false
}

const cancelEdit = () => {
    editingIndex.value = null
    editedValue.value = ''
}

const handleAdd = () => {
    dialog.add = true
    editedValue.value = ''
    editingIndex.value = null
}

const removeCompany = async (index: number) => {
    const updated = [...companies.value]
    updated.splice(index, 1)
    companies.value = updated
    dialog.delete = false
}

const handleRemove = async (index: number) => {
   deleteIndex.value = index;
   dialog.delete = true;
}

const persistCompanies = async () => {
    try {
        const isSame =
            companies.value.length === initialCompanies.value.length &&
            companies.value.every((c, i) => c === initialCompanies.value[i]);
        if (isSame) return


        await updateSitebyId(props.site, {
            deliveryCompanyList: companies.value,
        })

        toast.message = 'Delivery companies updated successfully!'
        toast.color = 'success'
        toast.show = true
        emit('refresh-site')
    } catch (error) {
        console.error('Failed to update delivery companies:', error)
        toast.message = 'Failed to update delivery companies. Please try again.'
        toast.color = 'error'
        toast.show = true
    }
}

watch(initialCompanies, (val) => {
    companies.value = Array.isArray(val) ? [...val] : []
    isHydrating.value = false
}, { immediate: true })
</script>

<style scoped>
.drag-area {
    cursor: grab;
}

.drag-handle {
    cursor: grab;
}
</style>