import { type FormEvent, useState } from 'react'
import { Flex, Stack, Text } from '@chakra-ui/react'
import { Link, useNavigate } from 'react-router-dom'
import { CalledItButton, CalledItCard, CalledItTextInput } from '../components'
import { registerUser } from '../features/auth/authApi'

export function RegisterPage() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: FormEvent) {
    e.preventDefault()
    setSubmitting(true)
    setError(null)

    try {
      await registerUser(username, email, password)
      navigate('/login', { replace: true })
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Registration failed.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Flex minH="100vh" bg="page" align="center" justify="center" px="6" py="10">
      <CalledItCard cardTitle="Create account" maxW="420px" w="full">
        <form onSubmit={handleSubmit}>
          <Stack gap="4">
            <CalledItTextInput
              label="Name"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
            <CalledItTextInput
              label="Email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <CalledItTextInput
              label="Password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            {error && (
              <Text color="red.600" fontSize="sm">
                {error}
              </Text>
            )}
            <CalledItButton type="submit" loading={submitting}>
              Create account
            </CalledItButton>
            <Text color="muted" fontSize="sm">
              Already have an account?{' '}
              <Link to="/login" style={{ color: 'inherit', textDecoration: 'underline' }}>
                Sign in
              </Link>
            </Text>
          </Stack>
        </form>
      </CalledItCard>
    </Flex>
  )
}
