import { createMemo, Match, Switch, type JSX } from "solid-js"
import { SplitBorder } from "@tui/component/border"
import { useTheme } from "@tui/context/theme"
import { parseSaeeolErrorCode, saeeolErrorTitle, saeeolErrorDescription } from "@/saeeol/errors"
import type { AssistantMessage } from "@saeeol/sdk/v2"

interface SaeeolErrorBlockProps {
  error: NonNullable<AssistantMessage["error"]>
  fallback: JSX.Element
}

export function SaeeolErrorBlock(props: SaeeolErrorBlockProps) {
  const { theme } = useTheme()

  const saeeolErrorCode = createMemo(() => {
    return parseSaeeolErrorCode(props.error)
  })

  const title = createMemo(() => {
    const code = saeeolErrorCode()
    return code ? saeeolErrorTitle(code) : undefined
  })

  const description = createMemo(() => {
    const code = saeeolErrorCode()
    return code ? saeeolErrorDescription(code) : undefined
  })

  return (
    <Switch fallback={props.fallback}>
      <Match when={saeeolErrorCode()}>
        <box
          border={["left"]}
          paddingTop={1}
          paddingBottom={1}
          paddingLeft={2}
          marginTop={1}
          backgroundColor={theme.backgroundPanel}
          customBorderChars={SplitBorder.customBorderChars}
          borderColor={theme.primary}
        >
          <text fg={theme.text}>{title()}</text>
          <text fg={theme.textMuted}>{description()}</text>
          <text fg={theme.primary}>{"Run /connect or `saeeol auth login` to connect to Saeeol Gateway"}</text>
        </box>
      </Match>
    </Switch>
  )
}
