<template>
    <label class="input-file-comp" :class="classes">
        <div class="input-file-comp__label">{{ label }}</div>
        <div class="input-file-comp__value" v-show="value !== ''">
            <div class="input-file-comp__value-text">{{ value }}</div>
            <FontAwesomeIcon class="input-file-comp__value-icon" icon="xmark" @click.prevent="clearValue()" />
        </div>
        <input class="input-file-comp__input" type="file" :accept="accept" @change="valueChanged" />
    </label>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";

const props = defineProps<{ label: string; accept: string }>();
const emit = defineEmits(["change"]);

const classes = computed(() => ({
    "input-file-comp--has-value": value.value !== "",
}));

const value = ref("");

function valueChanged(event: Event) {
    const inputElement = event.target as HTMLInputElement;
    const file = inputElement.files?.[0];
    if (file) {
        value.value = file.name;
        emit("change", file);
    }
}

function clearValue() {
    value.value = "";
    emit("change", undefined);
}
</script>

<style lang="scss">
.input-file-comp {
    $p: &;

    position: relative;
    height: r(59);
    min-width: r(200);

    &__label {
        position: absolute;
        bottom: r(21);
        font-size: r(16);
        color: #999;
        z-index: 1;
        transition: 0.18s ease;
    }

    &__input {
        display: none;
    }

    &__value {
        position: absolute;
        bottom: r(15);
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: r(32);
        font-size: r(16);
    }

    &__value-text {
        margin-right: r(10);
        white-space: nowrap;
        overflow: hidden;
    }

    &__value-icon {
        padding: r(5);
        cursor: pointer;
    }

    &::before {
        content: "";
        position: absolute;
        bottom: r(10);
        width: 100%;
        height: r(1);
        background: color("ui-background");
    }

    &--has-value {
        #{$p}__label {
            bottom: r(46);
            font-size: r(13);
        }
    }
}
</style>
