<template>
  <div
    :style="getStyle"
    class="relative overflow-hidden box-border flex items-center justify-center"
  >
    <canvas ref="qrcodeCanvas" class="max-w-full max-h-full"></canvas>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue'
import { useWidgetStyle } from '../hooks/useWidgetStyle'
import QRCode from 'qrcode'

const props = defineProps<{
  styles: any
  state?: string
  part?: string
  lightColor?: string
  darkColor?: string
  size?: number
  text?: string
}>()

const qrcodeCanvas = ref<HTMLCanvasElement | null>(null)

const styleMap = useWidgetStyle({
  widget: 'qrcode',
  props
})

const getStyle = computed(() => {
  return {
    width: props.size + 'px',
    height: props.size + 'px',
    ...styleMap.value
  }
})

const qrcodeSize = computed(() => {
  return Math.max(1, props.size || 1)
})

const renderQrcode = async () => {
  if (!qrcodeCanvas.value) return

  const context = qrcodeCanvas.value.getContext('2d')
  context?.clearRect(0, 0, qrcodeCanvas.value.width, qrcodeCanvas.value.height)

  try {
    await QRCode.toCanvas(qrcodeCanvas.value, props.text?.trim() || 'https://www.sv-elec.com', {
      width: qrcodeSize.value,
      margin: 0,
      color: {
        dark: props.darkColor || '#000000ff',
        light: props.lightColor || '#ffffffff'
      }
    })
  } catch (error) {
    console.error('Failed to render QR code:', error)
  }
}

watch(
  () => [props.text, props.size, props.darkColor, props.lightColor],
  () => {
    renderQrcode()
  }
)

onMounted(() => {
  renderQrcode()
})
</script>
