<script setup lang="ts">
import type { NuxtError } from "#app";

defineProps({
  error: {
    type: Object as () => NuxtError,
    default: () => ({}) as NuxtError,
  },
});

// Reactive data
const stackTraceExpanded = ref(false);

const isDevelopment = computed(() => {
  // Check if we're in development mode
  return process.env.NODE_ENV === "development" || import.meta.dev;
});

const refresh = () => {
  if (import.meta.client) {
    window.location.reload();
  }
};

const goBack = () => {
  if (import.meta.client) {
    window.history.back();
  }
};

const goHome = () => {
  if (import.meta.client) {
    // Use replace to prevent going back to this error page
    window.location.replace("/");
  }
};

const getErrorLocation = () => {
  const props = getCurrentInstance()?.props as { error?: NuxtError };
  const error = props?.error;

  if (!error?.stack) return "";

  // Extract the first meaningful line from stack trace
  const stackLines = error.stack.split("\n");

  for (const line of stackLines) {
    // Look for file paths with line numbers
    const match = line.match(/at .+? \((.+?):(\d+):(\d+)\)/);
    if (match) {
      const [, filePath, lineNum, colNum] = match;
      // Clean up the file path to show only relevant parts
      const cleanPath = filePath.replace(/^.*[/\\]/g, "").replace(/\?.*$/g, "");
      return `${cleanPath}:${lineNum}:${colNum}`;
    }

    // Alternative pattern for different stack trace formats
    const match2 = line.match(/\s+at (.+?):(\d+):(\d+)/);
    if (match2) {
      const [, filePath, lineNum, colNum] = match2;
      const cleanPath = filePath.replace(/^.*[/\\]/g, "").replace(/\?.*$/g, "");
      return `${cleanPath}:${lineNum}:${colNum}`;
    }
  }

  return "";
};
</script>

<template>
  <div dir="ltr" class="bg-background flex h-screen flex-col">
    <!-- Dashboard Header -->
    <div
      class="border-surface-border bg-surface-background flex-shrink-0 border-b px-5 py-4 sm:px-5"
    >
      <div
        class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"
      >
        <div class="flex items-center gap-3">
          <div
            class="flex h-10 w-10 items-center justify-center rounded-lg bg-red-100 sm:h-12 sm:w-12 dark:bg-red-900/30"
          >
            <SvgWarningTriangleIcon
              class="h-5 w-5 text-red-600 sm:h-6 sm:w-6 dark:text-red-400"
            />
          </div>
          <div class="min-w-0 flex-1">
            <h1
              class="text-lg font-semibold text-slate-900 sm:text-xl dark:text-slate-100"
            >
              Error {{ error?.statusCode || "Unknown" }}
            </h1>
            <p
              class="truncate text-sm text-slate-500 sm:text-base dark:text-slate-400"
            >
              {{
                error?.statusMessage ||
                error?.message ||
                "An unexpected error occurred"
              }}
            </p>
          </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
          <div class="flex gap-2 sm:gap-3">
            <button
              class="inline-flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm font-medium text-green-700 transition-colors hover:bg-green-100 sm:flex-none sm:px-4 dark:border-green-800 dark:bg-green-900/20 dark:text-green-400 dark:hover:bg-green-900/30"
              @click="refresh()"
            >
              <SvgRefreshIcon class="h-4 w-4" />
              <span class="hidden sm:inline">Reload</span>
              <span class="sm:hidden">Reload</span>
            </button>
            <button
              class="inline-flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 sm:flex-none sm:px-4 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-300 dark:hover:bg-slate-600"
              @click="goBack"
            >
              <SvgArrowLeftV2Icon class="h-4 w-4" />
              <span class="hidden sm:inline">Go Back</span>
              <span class="sm:hidden">Back</span>
            </button>
          </div>
          <button
            class="inline-flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm font-medium text-blue-700 transition-colors hover:bg-blue-100 sm:w-auto sm:px-4 dark:border-blue-800 dark:bg-blue-900/20 dark:text-blue-400 dark:hover:bg-blue-900/30"
            @click="goHome"
          >
            <SvgGeneralHomeIcon class="h-4 w-4" />
            <span class="hidden sm:inline">Go to Home</span>
            <span class="sm:hidden">Home</span>
          </button>
        </div>
      </div>
    </div>
    <!-- Only show in production -->
    <div
      v-if="!isDevelopment"
      class="grid flex-1 place-content-center overflow-auto p-5"
    >
      <SvgWebstdyLogo class="size-64 md:size-80 lg:size-96" />
    </div>

    <!-- Dashboard Main Content - Only show in development -->
    <div v-if="isDevelopment" class="flex-1 overflow-auto p-5">
      <div
        class="grid min-h-full grid-cols-1 gap-6 lg:grid-cols-3"
        style="min-height: calc(580px - 120px)"
      >
        <div class="contents h-full">
          <!-- Error Overview Panel -->
          <div class="lg:col-span-1">
            <div
              class="border-surface-border bg-surface-background h-full rounded-lg border p-6"
            >
              <div class="mb-6 flex items-center gap-3">
                <SvgInfoCircleIcon
                  class="h-5 w-5 text-blue-600 dark:text-blue-400"
                />
                <h2
                  class="text-lg font-semibold text-slate-900 dark:text-slate-100"
                >
                  Error Details
                </h2>
              </div>

              <div class="space-y-4">
                <div
                  v-if="error?.statusCode"
                  class="flex items-center justify-between border-b border-slate-100 py-3 dark:border-slate-700"
                >
                  <span
                    class="text-sm font-medium text-slate-600 dark:text-slate-400"
                    >Status Code</span
                  >
                  <span
                    class="rounded bg-red-100 px-2 py-1 font-mono text-xs text-red-800 dark:bg-red-900/30 dark:text-red-300"
                  >
                    {{ error.statusCode }}
                  </span>
                </div>

                <div
                  v-if="error?.name"
                  class="flex items-center justify-between border-b border-slate-100 py-3 dark:border-slate-700"
                >
                  <span
                    class="text-sm font-medium text-slate-600 dark:text-slate-400"
                    >Error Type</span
                  >
                  <span
                    class="rounded bg-orange-100 px-2 py-1 font-mono text-xs text-orange-800 dark:bg-orange-900/30 dark:text-orange-300"
                  >
                    {{ error.name }}
                  </span>
                </div>

                <div
                  v-if="getErrorLocation()"
                  class="border-b border-slate-100 py-3 dark:border-slate-700"
                >
                  <span
                    class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-400"
                    >Location</span
                  >
                  <code
                    class="rounded bg-slate-50 px-2 py-1 text-xs text-red-600 dark:bg-slate-700 dark:text-red-400"
                  >
                    {{ getErrorLocation() }}
                  </code>
                </div>

                <div
                  v-if="
                    error?.message && error.message !== error?.statusMessage
                  "
                  class="py-3"
                >
                  <span
                    class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-400"
                    >Message</span
                  >
                  <p
                    class="rounded bg-slate-50 p-3 text-sm text-slate-700 dark:bg-slate-700 dark:text-slate-300"
                  >
                    {{ error.message }}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <!-- Technical Details Panel -->
          <div class="lg:col-span-2">
            <div
              class="border-surface-border bg-surface-background flex h-full flex-col rounded-lg border p-6"
            >
              <div class="mb-6 flex items-center gap-3">
                <SvgCodeIcon
                  class="h-5 w-5 text-purple-600 dark:text-purple-400"
                />
                <h2
                  class="text-lg font-semibold text-slate-900 dark:text-slate-100"
                >
                  Technical Information
                </h2>
              </div>

              <div class="flex-1 overflow-hidden">
                <div class="h-full space-y-6">
                  <!-- Additional Data Section -->
                  <div v-if="error?.data" class="">
                    <h3
                      class="mb-3 text-sm font-medium text-slate-600 dark:text-slate-400"
                    >
                      Additional Data
                    </h3>
                    <div
                      class="max-h-48 overflow-auto rounded-lg bg-slate-50 p-4 dark:bg-slate-700"
                    >
                      <pre
                        class="text-xs text-slate-800 dark:text-slate-200"
                      ><code>{{ JSON.stringify(error.data, null, 2) }}</code></pre>
                    </div>
                  </div>

                  <!-- Stack Trace Section -->
                  <div v-if="error?.stack" class="flex flex-1 flex-col">
                    <div class="mb-3 flex items-center gap-2">
                      <h3
                        class="text-sm font-medium text-slate-600 dark:text-slate-400"
                      >
                        Stack Trace
                      </h3>
                      <button
                        class="inline-flex items-center gap-1 px-2 py-1 text-xs text-slate-500 transition-colors hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
                        @click="stackTraceExpanded = !stackTraceExpanded"
                      >
                        <SvgChevronRightIcon
                          :is-open="stackTraceExpanded"
                          class="h-3 w-3 transition-transform"
                          :class="{ 'rotate-90': stackTraceExpanded }"
                        />
                        {{ stackTraceExpanded ? "Collapse" : "Expand" }}
                      </button>
                    </div>

                    <div
                      v-if="stackTraceExpanded"
                      class="flex-1 overflow-auto rounded-lg bg-slate-900 p-4 dark:bg-slate-950"
                    >
                      <pre
                        class="font-mono text-xs text-green-400"
                      ><code>{{ error.stack }}</code></pre>
                    </div>

                    <div
                      v-else
                      class="cursor-pointer rounded-lg bg-slate-50 p-4 transition-colors hover:bg-slate-100 dark:bg-slate-700 dark:hover:bg-slate-600"
                      @click="stackTraceExpanded = true"
                    >
                      <p
                        class="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400"
                      >
                        <SvgChevronRightIcon :is-open="false" class="h-3 w-3" />
                        Click to expand and view full stack trace
                      </p>
                    </div>
                  </div>

                  <!-- Development Mode Info -->
                  <div
                    v-if="isDevelopment"
                    class="rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"
                  >
                    <div class="mb-2 flex items-center gap-2">
                      <SvgWarningTriangleIcon
                        class="h-4 w-4 text-amber-600 dark:text-amber-400"
                      />
                      <span
                        class="text-sm font-medium text-amber-800 dark:text-amber-200"
                        >Development Mode</span
                      >
                    </div>
                    <p class="text-xs text-amber-700 dark:text-amber-300">
                      This detailed error information is only shown in
                      development mode.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
