<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import type { ProgressIndicatorVariants, ProgressVariants } from "."
import { computed } from "vue"
import { ProgressIndicator, ProgressRoot } from "reka-ui"
import { cn } from "@/lib/utils"
import { progressIndicatorVariants, progressVariants } from "."

export interface ProgressProps {
  value?: number | null
  max?: number
  size?: ProgressVariants["size"]
  variant?: ProgressIndicatorVariants["variant"]
  class?: HTMLAttributes["class"]
}

const props = withDefaults(defineProps<ProgressProps>(), {
  value: 0,
  max: 100,
})

const percent = computed(() => {
  if (props.value === null || props.value === undefined) {
    return null
  }
  const max = props.max ?? 100
  if (max <= 0) {
    return 0
  }
  return Math.min(100, Math.max(0, (props.value / max) * 100))
})

const indeterminate = computed(() => props.value === null)
</script>

<template>
  <ProgressRoot
    :model-value="indeterminate ? null : (percent ?? 0)"
    :max="100"
    :class="cn(progressVariants({ size }), props.class)"
  >
    <ProgressIndicator
      :class="
        cn(
          progressIndicatorVariants({ variant }),
          indeterminate && 'animate-pulse',
        )
      "
      :style="
        indeterminate
          ? 'transform: translateX(0)'
          : `transform: translateX(-${100 - (percent ?? 0)}%)`
      "
    />
  </ProgressRoot>
</template>
