"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useQuery } from "@tanstack/react-query"
import {
  AlertTriangleIcon,
  ChevronDownIcon,
  CopyIcon,
  DownloadIcon,
  GitBranchIcon,
  LayersPlusIcon,
  MoreHorizontal,
  PlayIcon,
  SquarePlay,
  Trash2Icon,
  WorkflowIcon,
} from "lucide-react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import React from "react"
import { useForm } from "react-hook-form"
import { z } from "zod"
import type {
  GitBranchInfo,
  ValidationDetail,
  ValidationResult,
  WorkflowDslPublish,
} from "@/client"
import { ApiError, workflowsListWorkflowBranches } from "@/client"
import { ExportMenuItem } from "@/components/export-workflow-dropdown-item"
import { Spinner } from "@/components/loading/spinner"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Kbd } from "@/components/ui/kbd"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Switch } from "@/components/ui/switch"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { ValidationErrorView } from "@/components/validation-errors"
import { useEntitlements } from "@/hooks/use-entitlements"
import { useWorkspaceDetails } from "@/hooks/use-workspace"
import type { TracecatApiError } from "@/lib/errors"
import {
  useCreateDraftWorkflowExecution,
  useOrgAppSettings,
  useWorkflowManager,
} from "@/lib/hooks"
import { cn, copyToClipboard } from "@/lib/utils"
import {
  parseTriggerPayload,
  validateTriggerPayload,
} from "@/lib/workflow-trigger-payload"
import { useWorkflowBuilder } from "@/providers/builder"
import { useWorkflow } from "@/providers/workflow"
import { useWorkspaceId } from "@/providers/workspace-id"

export function BuilderNav() {
  const {
    workflow,
    isLoading: workflowLoading,
    commitWorkflow,
    publishWorkflow,
    validationErrors,
    setValidationErrors,
  } = useWorkflow()

  const workspaceId = useWorkspaceId()
  const { workspace, workspaceLoading } = useWorkspaceDetails()
  const workflowTitle = workflow?.title ?? "Untitled workflow"

  const handleCommit = async () => {
    console.log("Saving changes...")
    try {
      const response = await commitWorkflow()
      const { status, errors } = response
      if (status === "failure") {
        setValidationErrors(errors || null)
      } else {
        setValidationErrors(null)
      }
    } catch (error) {
      console.error("Failed to save workflow:", error)
    }
  }

  if (!workflow || workflowLoading || !workspace || workspaceLoading) {
    return null
  }

  // Always allow running - use draft endpoint when no committed version
  const manualTriggerDisabled = false

  return (
    <div className="flex w-full items-center">
      <div className="mr-4 min-w-0 flex-1">
        <Breadcrumb>
          <BreadcrumbList className="flex-nowrap overflow-hidden whitespace-nowrap">
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href={`/workspaces/${workspaceId}/workflows`}>
                  {workspace.name}
                </Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator className="shrink-0 font-semibold">
              {"/"}
            </BreadcrumbSeparator>
            <BreadcrumbItem>
              <div className="flex min-w-0 items-center gap-2">
                <span className="truncate text-sm text-foreground">
                  {workflowTitle}
                </span>
                {workflow.alias && (
                  <Badge
                    variant="secondary"
                    className="font-mono text-xs font-normal tracking-tighter text-muted-foreground hover:cursor-default"
                  >
                    {workflow.alias}
                  </Badge>
                )}
              </div>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
      </div>

      <div className="flex items-center justify-end space-x-6">
        {/* Workflow tabs */}
        <TabSwitcher workflowId={workflow.id} />
        {/* Workflow manual trigger */}

        <WorkflowManualTrigger
          disabled={manualTriggerDisabled}
          workflowId={workflow.id}
        />
        {/* Save button */}
        <WorkflowSaveActions
          workflow={workflow}
          workspaceId={workspaceId}
          validationErrors={validationErrors}
          onSave={handleCommit}
          onPublish={publishWorkflow}
        />

        {/* Workflow options */}
        <BuilderNavOptions workspaceId={workspaceId} workflowId={workflow.id} />
      </div>
    </div>
  )
}

function TabSwitcher({ workflowId }: { workflowId: string }) {
  const pathname = usePathname()
  const router = useRouter()
  const workspaceId = useWorkspaceId()
  const pendingNavKeyRef = React.useRef<"w" | "r" | null>(null)
  const pendingNavAtRef = React.useRef<number | null>(null)
  let leafRoute: string = "workflow"
  if (pathname && pathname.includes("executions")) {
    leafRoute = "executions"
  }

  const builderPath = `/workspaces/${workspaceId}/workflows/${workflowId}`
  const executionsPath = `${builderPath}/executions`
  const keyOnlyTooltipClassName = "border-0 bg-transparent p-0 shadow-none"

  React.useEffect(() => {
    const DOUBLE_TAP_WINDOW_MS = 1200
    const isEditableTarget = (target: EventTarget | null) => {
      if (!(target instanceof HTMLElement)) {
        return false
      }
      const tagName = target.tagName
      return (
        target.isContentEditable ||
        tagName === "INPUT" ||
        tagName === "TEXTAREA" ||
        tagName === "SELECT" ||
        target.getAttribute("role") === "textbox"
      )
    }

    const handleKeyDown = (event: KeyboardEvent) => {
      if (
        event.repeat ||
        event.metaKey ||
        event.ctrlKey ||
        event.altKey ||
        isEditableTarget(event.target)
      ) {
        return
      }

      const key = event.key.toLowerCase()
      const now = Date.now()
      const pendingKey = pendingNavKeyRef.current
      const pendingAt = pendingNavAtRef.current
      const isWithinWindow =
        pendingKey !== null &&
        pendingAt !== null &&
        now - pendingAt <= DOUBLE_TAP_WINDOW_MS

      if (key !== "w" && key !== "r") {
        pendingNavKeyRef.current = null
        pendingNavAtRef.current = null
        return
      }

      if (!isWithinWindow || pendingKey !== key) {
        pendingNavKeyRef.current = key
        pendingNavAtRef.current = now
        return
      }

      pendingNavKeyRef.current = null
      pendingNavAtRef.current = null

      if (key === "w") {
        event.preventDefault()
        if (leafRoute !== "workflow") {
          router.push(builderPath)
        }
        return
      }

      if (key === "r") {
        event.preventDefault()
        if (leafRoute !== "executions") {
          router.push(executionsPath)
        }
      }
    }

    window.addEventListener("keydown", handleKeyDown)
    return () => window.removeEventListener("keydown", handleKeyDown)
  }, [builderPath, executionsPath, leafRoute, router])

  return (
    <Tabs value={leafRoute}>
      <TabsList className="grid h-8 w-full grid-cols-2">
        <TabsTrigger
          className="w-full px-2 py-0 after:content-none"
          value="workflow"
          asChild
        >
          <Link href={builderPath} className="size-full text-xs" passHref>
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="flex size-full items-center justify-center">
                  <WorkflowIcon className="mr-2 size-4" />
                  <span>Workflow</span>
                </span>
              </TooltipTrigger>
              <TooltipContent
                side="bottom"
                className={keyOnlyTooltipClassName}
                sideOffset={8}
              >
                <span className="inline-flex items-center gap-1">
                  <Kbd>W</Kbd>
                  <span className="inline-flex h-5 items-center rounded border bg-muted px-1.5 text-[10px] font-medium text-muted-foreground">
                    then
                  </span>
                  <Kbd>W</Kbd>
                </span>
              </TooltipContent>
            </Tooltip>
          </Link>
        </TabsTrigger>
        <TabsTrigger
          className="w-full px-2 py-0 after:content-none"
          value="executions"
          asChild
        >
          <Link href={executionsPath} className="size-full text-xs" passHref>
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="flex size-full items-center justify-center">
                  <SquarePlay className="mr-2 size-4" />
                  <span>Runs</span>
                </span>
              </TooltipTrigger>
              <TooltipContent
                side="bottom"
                className={keyOnlyTooltipClassName}
                sideOffset={8}
              >
                <span className="inline-flex items-center gap-1">
                  <Kbd>R</Kbd>
                  <span className="inline-flex h-5 items-center rounded border bg-muted px-1.5 text-[10px] font-medium text-muted-foreground">
                    then
                  </span>
                  <Kbd>R</Kbd>
                </span>
              </TooltipContent>
            </Tooltip>
          </Link>
        </TabsTrigger>
      </TabsList>
    </Tabs>
  )
}

const publishFormSchema = z.object({
  message: z.string().optional(),
  branch: z.string().trim().min(1, "Target branch is required"),
  createPr: z.boolean().default(false),
})
type TPublishForm = z.infer<typeof publishFormSchema>
const CREATE_NEW_BRANCH_VALUE = "__create_new_branch__"

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null
}

function isValidationDetail(value: unknown): value is ValidationDetail {
  if (!isRecord(value)) {
    return false
  }
  if (typeof value.type !== "string" || typeof value.msg !== "string") {
    return false
  }
  if ("loc" in value && value.loc !== null && !Array.isArray(value.loc)) {
    return false
  }
  return true
}

function isValidationResult(value: unknown): value is ValidationResult {
  if (!isRecord(value)) {
    return false
  }
  if (value.status !== "success" && value.status !== "error") {
    return false
  }
  return typeof value.type === "string"
}

function toDslApiErrorResult(message: string): ValidationResult {
  return {
    type: "dsl",
    status: "error",
    msg: message,
    ref: null,
    detail: [{ type: "api_error", msg: message }],
  }
}

function normalizeRunValidationErrors(
  detail: unknown
): ValidationResult[] | null {
  if (
    Array.isArray(detail) &&
    detail.length > 0 &&
    detail.every(isValidationResult)
  ) {
    return detail
  }
  if (
    Array.isArray(detail) &&
    detail.length > 0 &&
    detail.every(isValidationDetail)
  ) {
    return [
      {
        type: "dsl",
        status: "error",
        msg: "Workflow validation failed",
        ref: null,
        detail,
      },
    ]
  }

  let message: string | undefined
  let nestedDetail: unknown

  if (typeof detail === "string") {
    message = detail
  } else if (isRecord(detail)) {
    if (typeof detail.message === "string") {
      message = detail.message
    }
    nestedDetail = detail.detail
  } else if (detail) {
    try {
      message = JSON.stringify(detail)
    } catch {
      message = undefined
    }
  }

  if (
    Array.isArray(nestedDetail) &&
    nestedDetail.length > 0 &&
    nestedDetail.every(isValidationResult)
  ) {
    return nestedDetail
  }
  if (
    Array.isArray(nestedDetail) &&
    nestedDetail.length > 0 &&
    nestedDetail.every(isValidationDetail)
  ) {
    return [
      {
        type: "dsl",
        status: "error",
        msg: message || "Workflow validation failed",
        ref: null,
        detail: nestedDetail,
      },
    ]
  }

  if (!message) {
    return null
  }
  return [toDslApiErrorResult(message)]
}

function WorkflowManualTrigger({
  disabled = true,
  workflowId,
}: {
  disabled: boolean
  workflowId: string
}) {
  const { expandSidebarAndFocusEvents, setCurrentExecutionId, triggerPayload } =
    useWorkflowBuilder()
  // Always use draft execution endpoint - runs the current draft workflow graph
  const { createDraftExecution, createDraftExecutionIsPending } =
    useCreateDraftWorkflowExecution(workflowId)
  const [manualTriggerErrors, setManualTriggerErrors] = React.useState<
    ValidationResult[] | null
  >(null)
  const [isTriggering, setIsTriggering] = React.useState(false)

  React.useEffect(() => {
    setManualTriggerErrors(null)
  }, [triggerPayload])

  const runWorkflow = async () => {
    if (disabled || createDraftExecutionIsPending) return
    const payloadError = validateTriggerPayload(triggerPayload)
    if (payloadError) {
      setManualTriggerErrors([toDslApiErrorResult(payloadError)])
      return
    }
    setIsTriggering(true)
    setTimeout(() => setIsTriggering(false), 1000)
    setManualTriggerErrors(null)
    try {
      const result = await createDraftExecution({
        workflow_id: workflowId,
        inputs: parseTriggerPayload(triggerPayload),
      })

      // Store the execution ID directly
      if (result && result.wf_exec_id) {
        setCurrentExecutionId(result.wf_exec_id)
      }

      // Expand sidebar immediately
      expandSidebarAndFocusEvents()
    } catch (error) {
      if (error instanceof ApiError) {
        const tracecatError = error as TracecatApiError<{
          type?: string
          message?: string
          detail?: unknown
        }>
        console.error("Error details", tracecatError.body)
        const validationErrors = normalizeRunValidationErrors(
          tracecatError.body.detail
        )
        if (validationErrors && validationErrors.length > 0) {
          setManualTriggerErrors(validationErrors)
        } else {
          setManualTriggerErrors([
            toDslApiErrorResult("Failed to start workflow"),
          ])
        }
      }
    }
  }

  const executionPending = createDraftExecutionIsPending || isTriggering
  return (
    <ValidationErrorView
      side="bottom"
      validationErrors={manualTriggerErrors || []}
      noErrorTooltip={
        <span>
          {disabled
            ? "Cannot run workflow."
            : executionPending
              ? "Starting workflow execution..."
              : "Run the current draft workflow with the trigger payload from the trigger node."}
        </span>
      }
    >
      <Button
        type="button"
        variant={manualTriggerErrors ? "destructive" : "default"}
        className="h-7 justify-center gap-2 rounded-lg px-5 py-0 text-xs font-medium"
        disabled={disabled || executionPending}
        onClick={runWorkflow}
      >
        {executionPending ? (
          <Spinner className="size-3.5" segmentColor="currentColor" />
        ) : manualTriggerErrors ? (
          <AlertTriangleIcon className="size-3.5" />
        ) : (
          <PlayIcon className="size-3.5" />
        )}
        <span>Run</span>
      </Button>
    </ValidationErrorView>
  )
}

function WorkflowSaveActions({
  workflow,
  workspaceId,
  validationErrors,
  onSave,
  onPublish,
}: {
  workflow: { version?: number | null; git_sync_branch?: string | null }
  workspaceId: string
  validationErrors: ValidationResult[] | null
  onSave: () => Promise<void>
  onPublish: (params: WorkflowDslPublish) => Promise<unknown>
}) {
  const { hasEntitlement } = useEntitlements()
  const isGitSyncEnabled = hasEntitlement("git_sync")
  const [publishOpen, setPublishOpen] = React.useState(false)
  const [isPublishing, setIsPublishing] = React.useState(false)
  const [isCreatingBranch, setIsCreatingBranch] = React.useState(false)
  const { data: repoBranches, isLoading: branchesLoading } = useQuery<
    Array<GitBranchInfo>,
    ApiError
  >({
    queryKey: ["workflow-sync-branches", workspaceId],
    queryFn: async () =>
      await workflowsListWorkflowBranches({
        workspaceId,
        limit: 200,
      }),
    enabled: isGitSyncEnabled && publishOpen,
  })
  const hasBranches = (repoBranches?.length ?? 0) > 0

  const publishForm = useForm<TPublishForm>({
    resolver: zodResolver(publishFormSchema),
    defaultValues: {
      message: "",
      branch: workflow.git_sync_branch ?? "",
      createPr: false,
    },
  })

  React.useEffect(() => {
    if (!publishOpen) {
      return
    }
    setIsCreatingBranch(false)
    publishForm.reset({
      message: "",
      branch: workflow.git_sync_branch ?? "",
      createPr: false,
    })
  }, [publishOpen, publishForm, workflow.git_sync_branch])

  React.useEffect(() => {
    if (
      !publishOpen ||
      !repoBranches ||
      repoBranches.length === 0 ||
      isCreatingBranch
    ) {
      return
    }

    const branchNames = new Set(repoBranches.map((branch) => branch.name))
    const currentBranch = publishForm.getValues("branch")
    if (currentBranch && branchNames.has(currentBranch)) {
      return
    }

    const preferredBranch = workflow.git_sync_branch
    const defaultBranch =
      (preferredBranch && branchNames.has(preferredBranch)
        ? preferredBranch
        : undefined) ??
      repoBranches.find((branch) => branch.is_default)?.name ??
      repoBranches[0]?.name

    if (defaultBranch) {
      publishForm.setValue("branch", defaultBranch, { shouldValidate: true })
    }
  }, [
    isCreatingBranch,
    publishForm,
    publishOpen,
    repoBranches,
    workflow.git_sync_branch,
  ])

  const selectedBranch = publishForm.watch("branch")
  const createPrEnabled = publishForm.watch("createPr")
  const selectedBranchInfo = repoBranches?.find(
    (branch) => branch.name === selectedBranch
  )
  const isDefaultBranchSelected = selectedBranchInfo?.is_default ?? false

  const handlePublish = async (data: TPublishForm) => {
    setIsPublishing(true)
    try {
      await onPublish({
        message: data.message || undefined,
        branch: data.branch,
        create_pr: data.createPr,
      })
    } finally {
      setIsPublishing(false)
      setPublishOpen(false)
      setIsCreatingBranch(false)
      publishForm.reset({
        message: "",
        branch: workflow.git_sync_branch ?? "",
        createPr: false,
      })
    }
  }

  return (
    <div className="flex items-center space-x-2">
      <div className="flex h-7 gap-px rounded-lg border border-input">
        {/* Main Publish Button */}
        <ValidationErrorView
          side="bottom"
          validationErrors={validationErrors || []}
          noErrorTooltip={
            <span>
              Publish workflow v{(workflow.version || 0) + 1} with your changes.
            </span>
          }
        >
          <Button
            variant="outline"
            onClick={onSave}
            className={cn(
              "h-full border-none px-3 py-0 text-xs text-muted-foreground",
              isGitSyncEnabled ? "rounded-r-none" : "rounded-lg",
              validationErrors &&
                "border-rose-400 text-rose-400 hover:bg-transparent hover:text-rose-500"
            )}
          >
            {validationErrors ? (
              <AlertTriangleIcon className="mr-2 size-3.5 fill-red-500 stroke-white" />
            ) : (
              <LayersPlusIcon className="mr-2 size-3.5" />
            )}
            Publish
          </Button>
        </ValidationErrorView>

        {/* Dropdown Button - Only show if git-sync is enabled */}
        {isGitSyncEnabled && (
          <DropdownMenu open={publishOpen} onOpenChange={setPublishOpen}>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                className="h-full w-7 rounded-l-none border-none px-1 py-0 text-xs text-muted-foreground"
              >
                <ChevronDownIcon className="size-3" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-96 p-3">
              <Form {...publishForm}>
                <form
                  onSubmit={publishForm.handleSubmit(handlePublish)}
                  className="flex flex-col"
                >
                  <span className="mb-2 text-xs text-muted-foreground">
                    Version control
                  </span>
                  <FormField
                    control={publishForm.control}
                    name="branch"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-xs text-muted-foreground">
                          Target branch
                        </FormLabel>
                        <Select
                          value={
                            isCreatingBranch ||
                            !repoBranches?.some(
                              (branch) => branch.name === field.value
                            )
                              ? CREATE_NEW_BRANCH_VALUE
                              : field.value
                          }
                          onValueChange={(value) => {
                            if (value === CREATE_NEW_BRANCH_VALUE) {
                              setIsCreatingBranch(true)
                              field.onChange("")
                              return
                            }
                            setIsCreatingBranch(false)
                            field.onChange(value)
                          }}
                          disabled={branchesLoading || !hasBranches}
                        >
                          <FormControl>
                            <SelectTrigger className="h-7 px-3 text-xs">
                              {branchesLoading ? (
                                <Skeleton className="h-3.5 w-full rounded-sm" />
                              ) : (
                                <SelectValue placeholder="Select branch" />
                              )}
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {hasBranches ? (
                              <>
                                <SelectItem value={CREATE_NEW_BRANCH_VALUE}>
                                  Create new branch...
                                </SelectItem>
                                <SelectSeparator />
                                {(repoBranches ?? []).map((branch) => (
                                  <SelectItem
                                    key={branch.name}
                                    value={branch.name}
                                  >
                                    <div className="flex items-center gap-2">
                                      <span>{branch.name}</span>
                                      {branch.is_default && (
                                        <Badge
                                          variant="secondary"
                                          className="h-4 rounded-sm px-1 text-[10px] font-normal"
                                        >
                                          default
                                        </Badge>
                                      )}
                                    </div>
                                  </SelectItem>
                                ))}
                              </>
                            ) : (
                              <SelectItem value="__no_branches" disabled>
                                No branches found
                              </SelectItem>
                            )}
                          </SelectContent>
                        </Select>
                        {isCreatingBranch && (
                          <div className="mt-2">
                            <Input
                              value={field.value}
                              onChange={field.onChange}
                              placeholder="feature/my-workflow"
                              className="h-7 px-3 text-xs"
                            />
                            <p className="mt-1 text-[11px] text-muted-foreground">
                              The branch will be created from the repository
                              default branch if it does not exist.
                            </p>
                          </div>
                        )}
                        {!branchesLoading && !hasBranches && (
                          <p className="text-[11px] text-muted-foreground">
                            No branches available from the configured
                            repository.
                          </p>
                        )}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={publishForm.control}
                    name="message"
                    render={({ field }) => (
                      <FormItem className="mt-2">
                        <FormLabel className="text-xs text-muted-foreground">
                          Commit message
                        </FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder="Add a short description of your changes (optional)"
                            className="h-7 px-3 text-xs"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={publishForm.control}
                    name="createPr"
                    render={({ field }) => (
                      <FormItem className="mt-2 flex items-center justify-between rounded-md border px-3 py-2">
                        <div className="space-y-0.5">
                          <p className="text-xs">Create pull request</p>
                          <p className="text-[11px] text-muted-foreground">
                            Reuse an open PR for this branch when available.
                          </p>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                            size="sm"
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  {isDefaultBranchSelected && !createPrEnabled && (
                    <p className="mt-2 text-[11px] text-amber-700">
                      Pushing to the default branch will create a direct commit.
                    </p>
                  )}
                  <Button
                    type="submit"
                    disabled={isPublishing || branchesLoading || !hasBranches}
                    className="mt-2 flex h-7 w-full items-center justify-center gap-2 bg-primary px-3 py-0 text-xs text-white hover:bg-primary/80"
                  >
                    {isPublishing ? (
                      <>
                        <Spinner className="size-3" />
                        Pushing changes...
                      </>
                    ) : (
                      <>
                        <GitBranchIcon className="size-3" />
                        Push changes
                      </>
                    )}
                  </Button>
                </form>
              </Form>
            </DropdownMenuContent>
          </DropdownMenu>
        )}
      </div>

      <Badge
        variant="secondary"
        className="h-7 text-xs font-normal text-muted-foreground hover:cursor-default"
      >
        {workflow.version ? `v${workflow.version}` : "Draft"}
      </Badge>
    </div>
  )
}

function BuilderNavOptions({
  workspaceId,
  workflowId,
}: {
  workspaceId: string
  workflowId: string
}) {
  const router = useRouter()
  const { appSettings } = useOrgAppSettings()
  const { deleteWorkflow } = useWorkflowManager(undefined, {
    listEnabled: false,
  })
  const enabledExport = appSettings?.app_workflow_export_enabled

  const handleDelete = async () => {
    await deleteWorkflow(workflowId)
    router.push(`/workspaces/${workspaceId}/workflows`)
  }

  return (
    <AlertDialog>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" size="icon">
            <MoreHorizontal className="size-4" />
            <span className="sr-only">More</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent>
          <ExportMenuItem
            enabledExport={enabledExport}
            format="yaml"
            workspaceId={workspaceId}
            workflowId={workflowId}
            draft={true}
            label="Export draft"
            icon={<DownloadIcon className="mr-2 size-3.5" />}
          />
          <ExportMenuItem
            enabledExport={enabledExport}
            format="yaml"
            workspaceId={workspaceId}
            workflowId={workflowId}
            draft={false}
            label="Export saved"
            icon={<DownloadIcon className="mr-2 size-3.5" />}
          />
          <DropdownMenuItem
            onClick={() =>
              copyToClipboard({
                value: workflowId,
                message: "Copied workflow ID to clipboard",
              })
            }
          >
            <CopyIcon className="mr-2 size-3.5" />
            Copy workflow ID
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <AlertDialogTrigger asChild>
            <DropdownMenuItem className="text-destructive focus:text-destructive">
              <Trash2Icon className="mr-2 size-3.5" />
              Delete workflow
            </DropdownMenuItem>
          </AlertDialogTrigger>
        </DropdownMenuContent>
      </DropdownMenu>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete workflow</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete this workflow? This action cannot be
            undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction variant="destructive" onClick={handleDelete}>
            Delete
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
