<template>
    <MalioDrawer v-model="isOpen">
        <template #header>
            <h2 class="text-xl font-bold">{{ isEditing ? $t('prospects.editProspect') : $t('prospects.addProspect') }}</h2>
        </template>
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.name"
                :label="$t('prospects.fields.name')"
                input-class="w-full"
                :error="touched.name && !form.name.trim() ? $t('prospects.validation.nameRequired') : ''"
                @blur="touched.name = true"
            />
            <MalioInputText
                v-model="form.company"
                :label="$t('prospects.fields.company')"
                input-class="w-full"
            />
            <MalioInputText
                v-model="form.email"
                :label="$t('prospects.fields.email')"
                input-class="w-full"
            />
            <MalioInputText
                v-model="form.phone"
                :label="$t('prospects.fields.phone')"
                input-class="w-full"
            />
            <MalioInputText
                v-model="form.street"
                :label="$t('prospects.fields.street')"
                input-class="w-full"
            />
            <MalioInputText
                v-model="form.city"
                :label="$t('prospects.fields.city')"
                input-class="w-full"
            />
            <MalioInputText
                v-model="form.postalCode"
                :label="$t('prospects.fields.postalCode')"
                input-class="w-full"
            />
            <MalioSelect
                v-model="form.status"
                :label="$t('prospects.fields.status')"
                :options="statusOptions"
                group-class="w-full"
            />
            <MalioInputText
                v-model="form.source"
                :label="$t('prospects.fields.source')"
                input-class="w-full"
            />
            <MalioInputTextArea
                v-model="form.notes"
                :label="$t('prospects.fields.notes')"
            />

            <div class="mt-6 flex items-center justify-between gap-2">
                <MalioButton
                    v-if="isEditing && !isConverted"
                    :label="$t('prospects.convert')"
                    variant="secondary"
                    icon-name="mdi:account-convert"
                    icon-position="left"
                    button-class="w-auto px-4"
                    :disabled="isSubmitting"
                    @click="handleConvert"
                />
                <span v-else-if="isConverted" class="text-sm text-green-700">
                    {{ $t('prospects.alreadyConverted') }}
                </span>
                <span v-else />
                <MalioButton
                    :label="$t('common.save')"
                    button-class="w-auto px-6"
                    :disabled="isSubmitting"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import type { Prospect, ProspectStatus, ProspectWrite } from '~/modules/directory/services/dto/prospect'
import { useProspectService } from '~/modules/directory/services/prospects'

const props = defineProps<{
    modelValue: boolean
    prospect: Prospect | null
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'saved'): void
}>()

const { t } = useI18n()

const isOpen = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

const isEditing = computed(() => !!props.prospect)
const isConverted = computed(() => !!props.prospect?.convertedClient)
const isSubmitting = ref(false)

const statusOptions = [
    { label: t('prospects.status.new'), value: 'new' },
    { label: t('prospects.status.contacted'), value: 'contacted' },
    { label: t('prospects.status.qualified'), value: 'qualified' },
    { label: t('prospects.status.won'), value: 'won' },
    { label: t('prospects.status.lost'), value: 'lost' },
]

const form = reactive<{
    name: string
    company: string
    email: string
    phone: string
    street: string
    city: string
    postalCode: string
    status: ProspectStatus
    source: string
    notes: string
}>({
    name: '',
    company: '',
    email: '',
    phone: '',
    street: '',
    city: '',
    postalCode: '',
    status: 'new',
    source: '',
    notes: '',
})

const touched = reactive({
    name: false,
})

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.prospect) {
            form.name = props.prospect.name ?? ''
            form.company = props.prospect.company ?? ''
            form.email = props.prospect.email ?? ''
            form.phone = props.prospect.phone ?? ''
            form.street = props.prospect.street ?? ''
            form.city = props.prospect.city ?? ''
            form.postalCode = props.prospect.postalCode ?? ''
            form.status = props.prospect.status ?? 'new'
            form.source = props.prospect.source ?? ''
            form.notes = props.prospect.notes ?? ''
        } else {
            form.name = ''
            form.company = ''
            form.email = ''
            form.phone = ''
            form.street = ''
            form.city = ''
            form.postalCode = ''
            form.status = 'new'
            form.source = ''
            form.notes = ''
        }
        touched.name = false
    }
})

const { create, update, convert } = useProspectService()

async function handleSubmit() {
    touched.name = true
    if (!form.name.trim()) return

    isSubmitting.value = true
    try {
        const payload: ProspectWrite = {
            name: form.name.trim(),
            company: form.company.trim() || null,
            email: form.email.trim() || null,
            phone: form.phone.trim() || null,
            street: form.street.trim() || null,
            city: form.city.trim() || null,
            postalCode: form.postalCode.trim() || null,
            status: form.status,
            source: form.source.trim() || null,
            notes: form.notes.trim() || null,
        }

        if (isEditing.value && props.prospect) {
            await update(props.prospect.id, payload)
        } else {
            await create(payload)
        }

        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleConvert() {
    if (!props.prospect) return
    isSubmitting.value = true
    try {
        await convert(props.prospect.id)
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}
</script>
