Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

6.1 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import React, { useState } from 'react'
import { CreateRegion, CreateRegionResponse } from '@boxlite-ai/api-client'
import { Button } from '@/components/ui/button'
import { CopyableValue } from '@/components/ui/copyable-value'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { toast } from 'sonner'
import { Plus } from '@/components/ui/icon'
import { getMaskedToken } from '@/lib/utils'

const DEFAULT_FORM_DATA = {
  name: '',
  proxyUrl: '',
}

interface CreateRegionDialogProps {
  onCreateRegion: (data: CreateRegion) => Promise<CreateRegionResponse | null>
  writePermitted: boolean
  loadingData: boolean
}

export const CreateRegionDialog: React.FC<CreateRegionDialogProps> = ({
  onCreateRegion,
  writePermitted,
  loadingData,
}) => {
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)

  const [createdRegion, setCreatedRegion] = useState<CreateRegionResponse | null>(null)
  const [isProxyApiKeyRevealed, setIsProxyApiKeyRevealed] = useState(false)

  const [formData, setFormData] = useState(DEFAULT_FORM_DATA)

  const handleCreate = async () => {
    setLoading(true)
    try {
      const createRegionData: CreateRegion = {
        name: formData.name,
        proxyUrl: formData.proxyUrl.trim() || null,
      }

      const region = await onCreateRegion(createRegionData)
      if (region) {
        if (!region.proxyApiKey) {
          setOpen(false)
          setCreatedRegion(null)
        } else {
          setCreatedRegion(region)
        }
        setFormData(DEFAULT_FORM_DATA)
      }
    } finally {
      setLoading(false)
    }
  }

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      toast.success('Copied to clipboard')
    } catch (err) {
      console.error('Failed to copy text:', err)
      toast.error('Failed to copy to clipboard')
    }
  }

  if (!writePermitted) {
    return null
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(isOpen) => {
        setOpen(isOpen)
        if (!isOpen) {
          setCreatedRegion(null)
          setFormData(DEFAULT_FORM_DATA)
          setIsProxyApiKeyRevealed(false)
        }
      }}
    >
      <DialogTrigger asChild>
        <Button variant="default" size="sm" disabled={loadingData} className="w-auto px-4" title="Create Region">
          <Plus className="w-4 h-4" />
          Create Region
        </Button>
      </DialogTrigger>

      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{createdRegion ? 'New Region Created' : 'Create New Region'}</DialogTitle>
          <DialogDescription>
            {!createdRegion
              ? 'Add a new region for grouping runners and boxes.'
              : createdRegion.proxyApiKey
                ? "Save these credentials securely. You won't be able to see them again."
                : ''}
          </DialogDescription>
        </DialogHeader>

        {createdRegion && createdRegion.proxyApiKey ? (
          <div className="space-y-6">
            {createdRegion.proxyApiKey && (
              <div className="space-y-3">
                <Label htmlFor="proxy-api-key">Proxy API Key</Label>
                <CopyableValue
                  displayValue={
                    isProxyApiKeyRevealed ? createdRegion.proxyApiKey : getMaskedToken(createdRegion.proxyApiKey)
                  }
                  copyValue={createdRegion.proxyApiKey}
                  copyLabel="proxy API key"
                  onCopy={copyToClipboard}
                  valueProps={{
                    onMouseEnter: () => setIsProxyApiKeyRevealed(true),
                    onMouseLeave: () => setIsProxyApiKeyRevealed(false),
                  }}
                />
              </div>
            )}
          </div>
        ) : (
          <form
            id="create-region-form"
            className="space-y-6 overflow-y-auto px-1 pb-1"
            onSubmit={async (e) => {
              e.preventDefault()
              await handleCreate()
            }}
          >
            <div className="space-y-3">
              <Label htmlFor="name">Region Name</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => {
                  setFormData((prev) => ({ ...prev, name: e.target.value }))
                }}
                placeholder="us-east-1"
              />
              <p className="text-body text-muted-foreground mt-1 pl-1">
                Region name must contain only letters, numbers, underscores, periods, and hyphens.
              </p>
            </div>

            <div className="space-y-3">
              <Label htmlFor="proxy-url">Proxy URL</Label>
              <Input
                id="proxy-url"
                value={formData.proxyUrl}
                onChange={(e) => {
                  setFormData((prev) => ({ ...prev, proxyUrl: e.target.value }))
                }}
                placeholder="https://proxy.example.com"
              />
              <p className="text-body text-muted-foreground mt-1 pl-1">
                (Optional) URL of the custom proxy for this region
              </p>
            </div>
          </form>
        )}

        <DialogFooter>
          <DialogClose asChild>
            <Button type="button" variant="secondary">
              {createdRegion ? 'Close' : 'Cancel'}
            </Button>
          </DialogClose>
          {!createdRegion &&
            (loading ? (
              <Button type="button" variant="default" disabled>
                Creating...
              </Button>
            ) : (
              <Button type="submit" form="create-region-form" variant="default" disabled={loading}>
                Create
              </Button>
            ))}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}