import {useEffect, useState} from 'react'
import {View} from 'react-native'

import {AuthGate} from '@/components/auth-gate'
import {ExternalLink} from '@/components/external-link'
import {FormError} from '@/components/forms/form-error'
import * as TextField from '@/components/forms/text-field'
import {Button} from '@/components/ui/button'
import {Divider} from '@/components/ui/divider'
import {Layout} from '@/components/ui/layout'
import {Text} from '@/components/ui/typography'
import {useSubmitAction} from '@/hooks/use-submit-action'
import {ApiError} from '@/lib/errors'
import {clearLlmKey, getLlmKey, setLlmKey} from '@/lib/llm-key'
import {goBack} from '@/lib/navigation'
import {atoms as a, useTheme} from '@/sprinkles'
import {useAuth} from '@/stores/auth'

export default function SettingsScreen() {
  return (
    <AuthGate>
      <SettingsScreenInner />
    </AuthGate>
  )
}

function SettingsScreenInner() {
  const t = useTheme()
  const user = useAuth((s) => s.user)
  const updateHandle = useAuth((s) => s.updateHandle)
  const [handle, setHandle] = useState(user?.handle ?? '')
  const [savingHandle, setSavingHandle] = useState(false)
  const [handleError, setHandleError] = useState<string | null>(null)
  const [key, setKey] = useState('')
  const [hasKey, setHasKey] = useState(false)
  const {
    submitting: saving,
    error,
    submit: saveKey,
  } = useSubmitAction(async (value: string) => {
    await setLlmKey(value)
    goBack()
  })

  useEffect(() => {
    void getLlmKey().then((k) => setHasKey(!!k))
  }, [])

  const onSaveHandle = async () => {
    const next = handle.trim().toLowerCase()
    if (!next || next === user?.handle) return
    setSavingHandle(true)
    setHandleError(null)
    try {
      await updateHandle(next)
    } catch (err) {
      setHandleError(
        err instanceof ApiError && err.code === 'handle_taken'
          ? 'That handle is taken. Try another.'
          : 'Could not update your handle. Try again.',
      )
    } finally {
      setSavingHandle(false)
    }
  }

  const onSave = () => {
    if (key.trim()) void saveKey(key.trim())
  }

  const onClear = async () => {
    await clearLlmKey()
    setKey('')
    setHasKey(false)
  }

  return (
    <>
      <Layout.Content>
        <View style={[a.gap_sm, a.py_lg]}>
          <Text>Handle</Text>
          <Text style={t.atoms.text_contrast_medium}>
            Your handle is how other people find you. It must be
            unique.
          </Text>
          <TextField.Input
            label="Handle"
            value={handle}
            onChangeText={setHandle}
            placeholder="e.g. cozy-bagel"
            autoCapitalize="none"
            autoCorrect={false}
          />
          <Button
            label={savingHandle ? 'Saving…' : 'Save handle'}
            onPress={onSaveHandle}
            disabled={
              savingHandle ||
              !handle.trim() ||
              handle.trim().toLowerCase() === user?.handle
            }
            color="primary"
            size="large"
            shape="rectangular"
          />
          {handleError && <FormError error={handleError} />}
        </View>

        <Divider />

        <View style={[a.gap_sm, a.py_lg]}>
          <Text>Anthropic API key</Text>
          <Text style={t.atoms.text_contrast_medium}>
            Paste your Anthropic API key to create crumbs from
            screengrabs. It is stored securely on this device and only
            sent to our server to read your image.
          </Text>
          <ExternalLink href="https://console.anthropic.com/settings/keys">
            <Text style={[a.text_sm, {color: t.palette.primary_500}]}>
              Get a key from the Anthropic console
            </Text>
          </ExternalLink>
          <TextField.Input
            label="API key"
            value={key}
            onChangeText={setKey}
            placeholder={hasKey ? '••••••••••••••••••••' : 'sk-ant-…'}
            secureTextEntry
            autoCapitalize="none"
            autoCorrect={false}
          />
          <Button
            label={saving ? 'Saving…' : 'Save key'}
            onPress={onSave}
            disabled={saving || !key.trim()}
            color="primary"
            size="large"
            shape="rectangular"
          />
          {error && <FormError error={error} />}
          {hasKey && (
            <Button
              label="Remove saved key"
              onPress={onClear}
              variant="ghost"
              color="negative"
              size="large"
              shape="rectangular"
            />
          )}
        </View>
      </Layout.Content>
    </>
  )
}
