<script setup lang="ts">
import { ref } from 'vue'

import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Textarea } from '@/components/ui/textarea'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Label } from '@/components/ui/label'
import { useProcessTrace } from '@/composables/useTraces'
import { useNavigation } from '@/composables/useNavigation'
import { WT1iser } from '@/services/wt1'

const { goToTrace } = useNavigation()
const { mutateAsync: processTrace, isPending, isError, error } = useProcessTrace()

// paste trace dialog state
const pastedJson = ref('')
const dialogOpen = ref(false)

async function addLocalTrace() {
  try {
    const result = await processTrace({ traceJson: pastedJson.value })
    const trace = result.data

    WT1iser.addTrace()

    // reset UI
    pastedJson.value = ''
    dialogOpen.value = false
    goToTrace(trace.id)
  } catch (err) {
    console.error(err)
  }
}

function handleDialogChange(open: boolean) {
  if (!open && pastedJson.value) {
    WT1iser.cancelPasteTrace()
  }
  dialogOpen.value = open
}
</script>

<template>
  <!-- Action Area: Paste New Trace -->
  <Dialog :open="dialogOpen" @update:open="handleDialogChange">
    <DialogTrigger as-child>
      <slot />
    </DialogTrigger>
    <DialogContent class="sm:max-w-[800px] p-0">
      <!-- Dialog Header -->
      <DialogHeader class="px-6 py-4 border-b">
        <DialogTitle>Add a local trace</DialogTitle>
        <DialogDescription> Paste a JSON trace to inspect it locally. </DialogDescription>
      </DialogHeader>

      <!-- Dialog Body -->
      <div class="grid gap-2 px-6">
        <Label for="trace">Trace JSON</Label>
        <Textarea
          id="trace"
          placeholder="{ ... }"
          class="my-2 h-[300px] resize-none break-all font-mono text-sm"
          v-model="pastedJson"
        />
        <Alert v-if="isError" variant="destructive" class="mb-2">
          <AlertDescription class="font-semibold">{{ error }}</AlertDescription>
        </Alert>
      </div>

      <!-- Dialog Footer -->
      <DialogFooter class="px-6 pb-4">
        <DialogClose as-child>
          <Button size="sm" variant="secondary" :disabled="isPending"> Cancel </Button>
        </DialogClose>
        <Button size="sm" type="submit" @click="addLocalTrace" :disabled="isPending">
          {{ isPending ? 'Processing...' : 'Import Trace' }}
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>
