<script setup lang="ts">
import { computed, ref, watch, type Slot } from 'vue'
import { useAttrsWithDefaults } from '../../../composables/useAttrsWithDefaults'
import { useHasSlot } from '../../../composables/useHasSlots'
import { useFdsI18n } from '../../../plugin/useFdsI18n'
import FdsButtonIcon from '../../Buttons/FdsButtonIcon/FdsButtonIcon.vue'
import FdsIcon from '../../FdsIcon/FdsIcon.vue'
import type { FdsAlertBlockProps } from './types'

const props = withDefaults(defineProps<FdsAlertBlockProps>(), {
  visible: true,
  closeable: false,
  collapsable: false,
  expanded: false,
  heading: undefined,
  dataTestid: undefined,
})

const { id } = useAttrsWithDefaults(props)
const { t } = useFdsI18n()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'toggle'): void
  (e: 'update:visible', value: boolean): void
}>()

const isExpanded = ref(props.expanded)
const isVisible = ref<boolean>(props.visible)
const expandLabel = computed(() => t('FdsBlockAlert.showMore'))
const collapseLabel = computed(() => t('FdsBlockAlert.showLess'))
const closeLabel = computed(() => t('FdsBlockAlert.close'))

const hasSlot = useHasSlot()

watch(
  () => props.visible,
  (v) => {
    isVisible.value = v
  },
)

const alertClasses = computed(() => [
  'bg-yellow-200 border-yellow-300 border-1 rounded-md p-4 mb-4',
  (props.collapsable && !isExpanded.value) || !hasSlot.value ? 'pb-4' : 'pb-6',
])

const autoId = `fds-alert-${Math.random().toString(36).slice(2, 9)}`
const alertId = computed(() => id.value ?? autoId)

const rootAttrs = computed(() => ({
  id: alertId.value,
  ...(props.dataTestid && { 'data-testid': props.dataTestid }),
})) as any

function handleClose() {
  isVisible.value = false
  emit('update:visible', false)
  emit('close')
}

function handleToggle() {
  isExpanded.value = !isExpanded.value
  emit('toggle')
}

defineSlots<{
  default?: Slot
}>()
</script>

<template>
  <div v-if="isVisible" v-bind="rootAttrs" :class="alertClasses">
    <div>
      <div>
        <div
          v-if="heading"
          class="font-bold w-full justify-between items-start flex gap-2"
          :class="{ 'mb-2': (isExpanded || !collapsable) && hasSlot }"
        >
          <div class="flex items-start gap-2">
            <div class="h-7 flex items-center">
              <FdsIcon name="alert" :size="24" class="fill-yellow-700" />
            </div>
            <span class="leading-7">{{ heading }}</span>
          </div>
          <div class="relative h-7">
            <FdsButtonIcon
              v-if="closeable"
              icon="cross"
              :size="28"
              @click="handleClose"
              v-bind="{ 'aria-label': closeLabel }"
              :class="['fill-gray-900! hover:bg-gray-100 active:bg-gray-200']"
            />
            <FdsButtonIcon
              v-if="collapsable"
              icon="arrowDown"
              :size="28"
              @click="handleToggle"
              v-bind="{ 'aria-label': isExpanded ? collapseLabel : expandLabel }"
              :class="[
                'fill-gray-900! hover:bg-gray-100 active:bg-gray-200',
                '[&_svg]:transition-transform [&_svg]:duration-200',
                isExpanded ? '[&_svg]:-rotate-180' : '[&_svg]:rotate-0',
              ]"
            />
          </div>
        </div>
        <div v-if="isExpanded || !collapsable" class="fds-block-alert-slot mb-0-last-child">
          <slot />
        </div>
      </div>
    </div>
  </div>
</template>
