<template>
  <div class="rounded-lg border p-4 shadow-sm">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <div
          class="flex h-10 w-10 items-center justify-center rounded-lg"
          :class="iconBgClass"
        >
          <FeatherIcon :name="iconName" class="h-5 w-5" :class="iconClass" />
        </div>
        <div>
          <p class="text-sm text-ink-gray-5">{{ label }}</p>
          <p class="text-2xl font-semibold text-ink-gray-9">
            {{ formattedValue }}
          </p>
        </div>
      </div>
      <div v-if="trend !== undefined" class="flex items-center gap-1" :class="trendClass">
        <FeatherIcon :name="trend > 0 ? 'trending-up' : 'trending-down'" class="h-4 w-4" />
        <span class="text-sm font-medium">{{ Math.abs(trend) }}%</span>
      </div>
    </div>
    <div v-if="subtitle" class="mt-2 text-xs text-ink-gray-5">
      {{ subtitle }}
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { FeatherIcon } from 'frappe-ui'

const props = defineProps({
  label: {
    type: String,
    required: true,
  },
  value: {
    type: [Number, String],
    required: true,
  },
  iconName: {
    type: String,
    default: 'activity',
  },
  color: {
    type: String,
    default: 'blue',
    validator: (v) => ['blue', 'green', 'red', 'yellow', 'purple', 'gray'].includes(v),
  },
  trend: {
    type: Number,
    default: undefined,
  },
  subtitle: {
    type: String,
    default: '',
  },
  format: {
    type: String,
    default: 'number',
    validator: (v) => ['number', 'currency', 'percent'].includes(v),
  },
})

const colorClasses = {
  blue: { bg: 'bg-blue-100', icon: 'text-blue-600' },
  green: { bg: 'bg-green-100', icon: 'text-green-600' },
  red: { bg: 'bg-red-100', icon: 'text-red-600' },
  yellow: { bg: 'bg-orange-100', icon: 'text-orange-600' },
  purple: { bg: 'bg-purple-100', icon: 'text-purple-600' },
  gray: { bg: 'bg-surface-gray-2', icon: 'text-ink-gray-5' },
}

const iconBgClass = computed(() => colorClasses[props.color]?.bg || colorClasses.blue.bg)
const iconClass = computed(() => colorClasses[props.color]?.icon || colorClasses.blue.icon)

const trendClass = computed(() => {
  if (props.trend > 0) return 'text-green-600'
  if (props.trend < 0) return 'text-red-600'
  return 'text-ink-gray-5'
})

const formattedValue = computed(() => {
  const num = typeof props.value === 'number' ? props.value : parseFloat(props.value)
  if (isNaN(num)) return props.value

  switch (props.format) {
    case 'currency':
      return new Intl.NumberFormat('ru-RU', {
        style: 'currency',
        currency: 'RUB',
        minimumFractionDigits: 0,
      }).format(num)
    case 'percent':
      return `${num}%`
    default:
      return new Intl.NumberFormat('ru-RU').format(num)
  }
})
</script>
