<template>
  <v-card class="tw:m-2 tw:border tw:border-red-300 tw:bg-red-50">
    <v-card-title
      class="tw:text-red-700 tw:text-base tw:font-semibold tw:flex tw:items-center tw:gap-2"
    >
      <v-icon color="red" size="small">mdi-alert-circle</v-icon>
      Widget Load Error
    </v-card-title>

    <v-card-text class="tw:text-red-600">
      <div class="tw:mb-2">There was an error while loading your widget</div>

      <div v-if="!isDev" class="tw:text-sm tw:text-red-500">
        Please contact support if this issue persists.
      </div>

      <div v-if="isDev" class="tw:space-y-3">
        <div class="tw:text-sm">
          <strong>Plugin:</strong> {{ pluginKey || "Unknown" }}<br />
          <strong>Widget:</strong> {{ widgetName || "Unknown" }}<br />
          <strong>UUID:</strong> {{ uuid || "Not provided" }}
        </div>

        <div v-if="error" class="tw:bg-red-100 tw:p-3 tw:rounded tw:text-xs">
          <strong>Error:</strong>
          <pre class="tw:mt-1 tw:whitespace-pre-wrap">{{ errorMessage }}</pre>
        </div>

        <div
          v-if="stackTrace"
          class="tw:bg-red-100 tw:p-3 tw:rounded tw:text-xs"
        >
          <strong>Stack Trace:</strong>
          <pre
            class="tw:mt-1 tw:whitespace-pre-wrap tw:max-h-32 tw:overflow-y-auto"
            >{{ stackTrace }}</pre
          >
        </div>

        <details v-if="props" class="tw:text-xs">
          <summary class="tw:cursor-pointer tw:font-medium">Raw Props</summary>
          <pre
            class="tw:mt-2 tw:bg-red-100 tw:p-2 tw:rounded tw:whitespace-pre-wrap tw:max-h-32 tw:overflow-y-auto"
            >{{ JSON.stringify(props, null, 2) }}</pre
          >
        </details>
      </div>
    </v-card-text>
  </v-card>
</template>

<script setup lang="ts">
import { computed } from "vue"
import { isDevelopmentMode } from "@racletteCore/helpers/devMode"

const props = defineProps<{
  uuid?: string
  pluginKey?: string
  widgetName?: string
  error?: Error
}>()

const isDev = computed(() => isDevelopmentMode())

const errorMessage = computed(
  () => props.error?.message || "Unknown error occurred",
)

const stackTrace = computed(() => {
  if (!props.error?.stack) return null

  const cleanedStack = props.error.stack
    .split("\n")
    .map((line) => line.replace(/\.vue\?t=\d+:\d+:\d+/g, ".vue"))
    .filter(
      (line) =>
        line.includes(".vue") ||
        line.includes("setup") ||
        line.includes("render") ||
        line.includes(props.widgetName || ""),
    )
    .slice(0, 5)
    .join("\n")

  return cleanedStack || props.error.stack
})
</script>
