<template>
  <div class="slider-wrapper ccb-default-multi-range-field">
    <div class="slider-min-max">
      <div class="slider-min-max-item first">
        <span class="label">{{ formatMinMax(field.min) }}</span>
      </div>
      <div class="slider-min-max-item">
        <span class="label">{{ formatMinMax(field.max) }}</span>
      </div>
    </div>
    <Slider
      style="margin: 10px 0"
      v-model="model"
      :format="getFormatValue"
      :min="field.min"
      :max="field.max"
      :step="field.step"
      :disabled="field.disabled"
      @change="onChange"
      show-tooltip="focus"
    ></Slider>
  </div>
</template>

<script setup lang="ts">
import { toRefs, computed } from "vue";
import { IMultiRangeField } from "@/widget/shared/types/fields";
import Slider from "@vueform/slider";
import { useFieldsExtraOptions } from "@/widget/features/calculator-fields/composable/useFieldsExtraOptions";

type Props = {
  field: IMultiRangeField;
  modelValue: number[];
};

const props = defineProps<Props>();
const { field } = toRefs(props);

const { formatMinMax } = useFieldsExtraOptions(field);

const emit = defineEmits<{
  (event: "update:modelValue", value: number[]): void;
}>();

const model = computed<number[]>({
  get: () =>
    props.modelValue && props.modelValue.length
      ? props.modelValue
      : field.value.values || [0, 50],
  set: (val: number[]) => emit("update:modelValue", val),
});

const onChange = (value: number | number[]) => {
  if (Array.isArray(value)) {
    emit("update:modelValue", value);
  } else {
    emit("update:modelValue", [value, value]);
  }
};

const getFormatValue = (num: number): string => {
  const rounded = num.toFixed(2);
  return parseFloat(rounded).toString();
};
</script>

<style lang="scss">
.ccb-default-multi-range-field {
  position: relative;
  .slider-min-max {
    display: flex;
    width: 102%;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    top: 20px;
    left: -3px;

    @media (max-width: 640px) {
      top: 44px;
    }

    &-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &.first {
        .tick {
          background: var(--ccb-accent-color);
        }
      }

      &.done {
        .tick {
          background-color: var(--ccb-accent-color);
        }
      }
    }

    .tick {
      height: 8px;
      width: 8px;
      border-radius: 50%;
      background: color-mix(in srgb, var(--ccb-container-color), black 10%);
      margin: 0 auto 4px;
    }

    .label {
      color: var(--ccb-fields-description-color);
      font-size: 12px;
      font-weight: 500;
      line-height: 100%;
      pointer-events: none;
    }
  }

  @media (max-width: 640px) {
    --slider-handle-width: 28px;
    --slider-handle-height: 28px;
    --slider-height: 12px;

    .slider-target {
      padding: 16px 0;
      margin: -16px 0;
      box-sizing: content-box;
    }
  }
}
</style>
