<script setup lang="ts">
import { computed, ref } from 'vue'
import { useColorMode } from '@vueuse/core'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu'
import { SidebarMenuButton } from '@/components/ui/sidebar'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { toast } from 'vue-sonner'
import { useSettings } from '@/composables/useSettings'
import { WT1iser } from '@/services/wt1'
import { useDeleteAllPastedTraces } from '@/composables/useTraces'
import { useTracesStore } from '@/stores/tracesStore'
import { useUiStore } from '@/stores/uiStore'

const mode = useColorMode()
const { defaultTraceView, defaultNodeView } = useSettings()
const tracesStore = useTracesStore()
const uiStore = useUiStore()
const { mutateAsync: deleteAllPastedTraces, isPending: isDeletingAll } = useDeleteAllPastedTraces()

const showDeleteAllConfirm = ref(false)
const hasPastedTraces = computed(() =>
  (tracesStore.traces?.data || []).some((trace) => trace.source === 'pasted'),
)

function handleThemeChange(theme: string) {
  mode.value = theme as 'light' | 'dark' | 'auto'
  WT1iser.themeChange(theme as 'light' | 'dark' | 'auto')
}

async function handleDeleteAllPastedTraces() {
  try {
    await deleteAllPastedTraces()

    if (uiStore.selectedTrace?.source === 'pasted') {
      uiStore.selectTrace(undefined)
    }

    showDeleteAllConfirm.value = false
  } catch (error) {
    const message = error instanceof Error ? error.message : 'An unexpected error occurred'
    toast.error('Failed to delete pasted traces', {
      description: message,
    })
  }
}
</script>

<template>
  <DropdownMenu>
    <DropdownMenuTrigger as-child>
      <SidebarMenuButton tooltip="Settings">
        <i class="dku-icon-gear-20 text-muted-foreground flex-shrink-0" />
        <span>Settings</span>
      </SidebarMenuButton>
    </DropdownMenuTrigger>
    <DropdownMenuContent side="top" align="start" class="w-[220px]">
      <DropdownMenuSub>
        <DropdownMenuSubTrigger>
          <i class="dku-icon-sun-16 mr-2" />
          Theme
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent>
          <DropdownMenuRadioGroup :model-value="mode" @update:model-value="handleThemeChange">
            <DropdownMenuRadioItem value="light">
              <i class="dku-icon-sun-16 mr-2" />
              Light
            </DropdownMenuRadioItem>
            <DropdownMenuRadioItem value="dark">
              <i class="dku-icon-moon-16 mr-2" />
              Dark
            </DropdownMenuRadioItem>
            <DropdownMenuRadioItem value="auto">
              <i class="dku-icon-laptop-16 mr-2" />
              System
            </DropdownMenuRadioItem>
          </DropdownMenuRadioGroup>
        </DropdownMenuSubContent>
      </DropdownMenuSub>

      <DropdownMenuSeparator />

      <DropdownMenuSub>
        <DropdownMenuSubTrigger>
          <i class="dku-icon-sitemap-16 mr-2" />
          Trace view
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent>
          <DropdownMenuRadioGroup
            :model-value="defaultTraceView"
            @update:model-value="defaultTraceView = $event as any"
          >
            <DropdownMenuRadioItem value="explorer">
              <i class="dku-icon-sitemap-16 mr-2" />
              Explorer
            </DropdownMenuRadioItem>
            <DropdownMenuRadioItem value="timeline">
              <i class="dku-icon-chart-horizontal-bar-16 mr-2" />
              Timeline
            </DropdownMenuRadioItem>
            <DropdownMenuRadioItem value="tree">
              <i class="dku-icon-diagram-16 mr-2" />
              Tree
            </DropdownMenuRadioItem>
          </DropdownMenuRadioGroup>
        </DropdownMenuSubContent>
      </DropdownMenuSub>

      <DropdownMenuSub>
        <DropdownMenuSubTrigger>
          <i class="dku-icon-file-text-16 mr-2" />
          Node view
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent>
          <DropdownMenuRadioGroup
            :model-value="defaultNodeView"
            @update:model-value="defaultNodeView = $event as any"
          >
            <DropdownMenuRadioItem value="formatted">
              <i class="dku-icon-file-text-16 mr-2" />
              Formatted
            </DropdownMenuRadioItem>
            <DropdownMenuRadioItem value="raw">
              <i class="dku-icon-code-16 mr-2" />
              Raw
            </DropdownMenuRadioItem>
          </DropdownMenuRadioGroup>
        </DropdownMenuSubContent>
      </DropdownMenuSub>

      <DropdownMenuSeparator />

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm transition-colors hover:bg-sidebar-accent disabled:opacity-50 disabled:cursor-not-allowed"
        :disabled="!hasPastedTraces"
        @click="showDeleteAllConfirm = true"
      >
        <i class="dku-icon-trash-16 text-destructive" />
        Delete all pasted traces
      </button>
    </DropdownMenuContent>
  </DropdownMenu>

  <AlertDialog v-model:open="showDeleteAllConfirm">
    <AlertDialogContent class="p-4">
      <AlertDialogHeader>
        <AlertDialogTitle>Delete all pasted traces?</AlertDialogTitle>
        <AlertDialogDescription>
          This will remove all pasted traces from storage. This action cannot be undone.
        </AlertDialogDescription>
      </AlertDialogHeader>
      <AlertDialogFooter>
        <AlertDialogCancel>Cancel</AlertDialogCancel>
        <AlertDialogAction
          class="bg-destructive hover:bg-destructive/90"
          :disabled="isDeletingAll"
          @click="handleDeleteAllPastedTraces"
        >
          {{ isDeletingAll ? 'Deleting...' : 'Delete all' }}
        </AlertDialogAction>
      </AlertDialogFooter>
    </AlertDialogContent>
  </AlertDialog>
</template>
