import { useSync } from "@tui/context/sync"
import { useDialog } from "@tui/ui/dialog"
import { useSDK } from "../context/sdk"
import { DialogPrompt } from "../ui/dialog-prompt"
import { useTheme } from "../context/theme"
import { DialogModel } from "./dialog-model"

export function DialogProvider() {
  return <ApiMethod />
}

function ApiMethod() {
  const dialog = useDialog()
  const sdk = useSDK()
  const sync = useSync()
  const { theme } = useTheme()

  return (
    <DialogPrompt
      title="Connect Tinfoil"
      placeholder="API key"
      description={
        <box gap={1}>
          <text fg={theme.textMuted}>
            Tinfoil provides secure, encrypted access to AI models with end-to-end encryption.
          </text>
          <text fg={theme.text}>
            Go to <span style={{ fg: theme.primary }}>https://tinfoil.sh</span> to get an API key
          </text>
        </box>
      }
      onConfirm={async (value) => {
        if (!value) return
        sdk.client.auth.set({
          providerID: "tinfoil",
          auth: {
            type: "api",
            key: value,
          },
        })
        await sdk.client.instance.dispose()
        await sync.bootstrap()
        dialog.replace(() => <DialogModel />)
      }}
    />
  )
}
