<script setup lang="ts">

import {onMounted, ref} from "vue";

const props = withDefaults(defineProps<{
    value: any,
    label?: string,
    disabled?: boolean,
    type?: string,
    dateFormat?: "string" | "number" | "date",
    focus?: boolean
}>(), {
    dateFormat: "string"
})

const emit = defineEmits(["update:value"])
const inputEl = ref<HTMLInputElement | undefined>()
const focus = ref(false)

onMounted(() => {
    if(props.focus) {
        inputEl.value?.focus()
    }
})

function update($event) {
    if(props.type == "date" && props.dateFormat == "number") {
        console.log($event.target.value)
        emit("update:value", new Date($event.target.value).getTime())
    }else{
        emit('update:value', $event.target.value)
    }
}

function zeros(val) {
    return val < 10 ? "0" + val : val + ""
}
function leading(val) {
    let leading = ""
    if(val < 10) leading = "000"
    else if(val < 100) leading = "00"
    else if(val < 1000) leading = "0"
    return leading + val
}

function getValue(){
    if(props.type == "date" && props.dateFormat == "number") {
        const date = new Date(props.value)
        return leading(date.getFullYear()) + "-" + zeros(date.getMonth() + 1) + "-" + zeros(date.getDate())
    } if(props.type == "date" && props.dateFormat == "date") {
        const date = new Date(props.value)
        return leading(date.getFullYear()) + "-" + zeros(date.getMonth() + 1) + "-" + zeros(date.getDate())
    } else {
        return props.value
    }
}

</script>

<template>
    <div class="input">
        <label v-if="label" :class="{up: props.value != '' || focus || type == 'date', focus}">{{ label }}</label>
        <input
            :value="getValue()"
            @input="update"
            :type="props.type ? props.type : 'text'"
            :disabled="disabled"
            @focusin="focus = true"
            @focusout="focus = false"
            ref="inputEl">
    </div>
</template>

<style scoped lang="less">

.input {
    display: inline-block;
    position: relative;

    label {
        display: block;
        font-size: 14px;
        padding: 2px 4px;
        color: #727272;
        position: absolute;
        top: 12px;
        left: 10px;
        z-index: 1;
        background: #ffffff;
        pointer-events: none;
        transition: 100ms top;
        &.up {
            top: -8px;
            font-size: 12px;
        }
        &.focus {
            color: #464646;
        }
    }

    input {
        position: relative;
        font-family: sans-serif;
        width: calc(100% - 30px);
        min-width: 0px;
        outline: none;
        margin: 0;
        padding: 15px 15px;
        color: #121212;
        border: 1px solid transparent;
        border-radius: 4px;
        font-size: 14px;
        transition: 100ms border-color;

        &:not(:disabled) {
            border: 1px solid #cecece;
            &:focus{
                border-color: #919191;
            }
        }
    }
}

</style>
