<script setup lang="ts">
import { getColorNameFromRal } from '@/components/ral'
import type { ralTypes } from '@/components/ral'

const config = useRuntimeConfig()
const apiBase = config.public.apiBase
const { data: calculatorData } = await useFetch(`${apiBase}/calculator/5/`)

const isModalOpen = useState('modal_open', () => false)

const lamelles_count = useState<number>('lamelles_count')
const fence_section = useState<number>('fence_section')
const pillar_color = useState<ralTypes>('pillar_color')
const lamelle_color = useState<ralTypes>('lamelle_color')
const section_count = useState('section_count')
const extra_section = useState('extra_section')
const total_length = useState('total_length')
const remove_pillar = useState<boolean>('remove_pillar')

const toggleModal = () => {
    modal_data.phone = undefined
    modal_data.name = undefined
    modal_state.show_form = false
    isModalOpen.value = !isModalOpen.value
}
type modalDataType = {
    phone?: string
    name?: string
}
const modal_data = reactive<modalDataType>({
    phone: undefined,
    name: undefined
})
const modal_form = reactive({
    disabled: true,
    errors: [],
})
const modal_state = reactive({
    show_form: false
})
const openForm = () => {
    modal_state.show_form = !modal_state.show_form
}
const validateInput = (evt: KeyboardEvent) => {
    const valid_symbols = /[a-zA-Z0-9\+(\\)\ @\.]/
    if (!valid_symbols.test(evt.key)) {
        evt.preventDefault()
        return
    }
}
const validate = () => {
    const phone_regexp = /^\+?[\d\s-()]{0,14}\d{11}$/
    const email_regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/

    if (!modal_data.phone) {
        modal_form.disabled = true
        return
    }
    if (modal_data.phone.length < 3) {
        modal_form.disabled = true
        return
    }
    if (phone_regexp.test(modal_data.phone) || email_regex.test(modal_data.phone)) {
        modal_form.disabled = false
        return
    }
}
const submit = (e: any) => {
    fetch(`${apiBase}/custom_request/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: modal_data.name || `ref from site ${new Date}`,
            phone: modal_data.phone,
            fence_info: [
                ...Object.values(total_txt.value).map(el => el.join('\n')), 
                total_colors.value.join('\n')
            ].join('\n\n'),
        })
    })
    modal_data.phone = undefined
    modal_data.name = undefined
    isModalOpen.value = false
}
const roubleSign = new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB',
});
const total_colors = computed(() => {
    return [
        `Ламели ${lamelle_color.value} ${getColorNameFromRal(lamelle_color.value)}`,
        `Столбы ${pillar_color.value} ${getColorNameFromRal(pillar_color.value)}`,
    ]
})
const total_txt = computed(() => {
    let { mortgage, pillar, lamella, rivets, bar, guide } = calculatorData.value
    mortgage = parseFloat(mortgage)
    pillar = parseFloat(pillar)
    lamella = parseFloat(lamella)
    rivets = parseFloat(rivets)
    bar = parseFloat(bar)
    guide = parseFloat(guide)
    const sections = section_count.value as number
    const extra_m = extra_section.value as number * 0.001
    const length_m = fence_section.value as number
    const lam_count = lamelles_count.value as number

    const prices = {
        pillar: mortgage + pillar,
        lamella: rivets * 2 + lamella * length_m,
        lamella_extra: rivets * 2 + lamella * extra_m,
        guide: guide * lam_count * 0.115,
        top: bar * length_m,
        top_extra: bar * extra_m
    }

    const extra = {
        pillar: !remove_pillar.value && {
            txt: `Дополнительная секция, столб, 1шт`,
            value: prices.pillar * 1
        },
        lamella: {
            txt: `Дополнительная секция, ламели, ${lam_count}шт`,
            value: prices.lamella_extra * lam_count
        },
        guide: {
            txt: `Направляющие, 2шт`,
            value: prices.guide * 2
        },
        top: {
            txt: `Верхняя планка`,
            value: prices.top * 1
        },

    }
    const regular = {
        pillar: !remove_pillar.value && {
            txt: `Столб, ${(1 + sections)}шт`,
            value: prices.pillar * (1 + sections)
        },
        lamella: {
            txt: `Ламели, ${(lam_count * sections)}шт`,
            value: prices.lamella * (lam_count * sections)
        },
        guide: {
            txt: `Направляющие, ${(2 + sections)}шт`,
            value: prices.guide * (2 * sections)
        },
        top: {
            txt: `Верхняя планка ${(1 + sections)}шт`,
            value: prices.top * sections
        },
    }

    const total = [extra, regular].map(item => Object.values(item).map(el => el ? el.value : 0)).flat().reduce((a, b) => a + b, 0)

    const res_regular = Object.values(regular).map(item =>
        Object.entries(item).map(el => el[0] == 'value' ? roubleSign.format(el[1] as number) : el[1]).join(': ')
    ).filter(Boolean)
    const res_extra = extra_section.value ? Object.values(extra).map(item =>
        Object.entries(item).map(el => el[0] == 'value' ? roubleSign.format(el[1] as number) : el[1]).join(': ')
    ).filter(Boolean) : []

    const res_total = [`Итого ${roubleSign.format(total)}`]
    return {
        regular: res_regular,
        extra: res_extra,
        total: res_total
    }
})
</script>
<template>
    <div v-if="isModalOpen" class="modal-backdrop" @click.self="toggleModal">
        <div class="modal">
            <template v-if="modal_state.show_form">
                <h2>Оставьте контакты для связи </h2>
                <form @submit.prevent="submit">
                    <input type="text" placeholder="Ваше имя" v-model="modal_data.name" @keyup="validate" />
                    <input type="phone" placeholder="Номер телефона или e-mail" v-model="modal_data.phone"
                        @keypress="validateInput" @keyup="validate" />
                    {{ total_txt.extra[0] }}
                    <div class="flex gap-4">
                        <button class="not-prose" :disabled="modal_form.disabled" type="submit">Отправить</button>
                        <button class="not-prose" type="reset" @click="toggleModal">Отмена</button>
                    </div>
                </form>
            </template>
            <template v-else>
                <h2>данные расчета</h2>
                <div class="flex gap-4 flex-col mb-4">
                    <p>Ламелей: {{ lamelles_count }}<br />
                        Длина секции: {{ (fence_section * 1000).toFixed(0) }}<br />
                        Общая длина: {{ total_length }}<br />
                        Секций: {{ section_count }}<br />
                        Цвет столба: {{ getColorNameFromRal(pillar_color) }}<br />
                        Цвет ламелей: {{ getColorNameFromRal(lamelle_color) }}
                    </p>
                    <template v-for="item in total_txt">
                        <p v-if="item.length">
                            <template v-for="i in item">{{ i }}<br /></template>
                        </p>
                    </template>
                </div>
                <div class="flex gap-4">
                    <button class="not-prose" @click="openForm">Данные верны</button>
                    <button class="not-prose neutral" @click="toggleModal">Закрыть окно</button>
                </div>
            </template>
        </div>
    </div>
</template>