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'

type LoginPageProps = {
  onLogin: (username: string, password: string) => Promise<void>
}

export function LoginPage({ onLogin }: LoginPageProps) {
  const navigate = useNavigate()
  const [username, setUsername] = 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 onLogin(username, password)
      navigate('/', { replace: true })
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Login failed.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Flex minH="100vh" bg="page" align="center" justify="center" px="6" py="10">
      <CalledItCard cardTitle="Sign in" maxW="420px" w="full">
        <form onSubmit={handleSubmit}>
          <Stack gap="4">
            <CalledItTextInput
              label="Username"
              value={username}
              onChange={(e) => setUsername(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}>
              Sign in
            </CalledItButton>
            <Text color="muted" fontSize="sm">
              Don't have an account?{' '}
              <Link to="/register" style={{ color: 'inherit', textDecoration: 'underline' }}>
                Create account
              </Link>
            </Text>
          </Stack>
        </form>
      </CalledItCard>
    </Flex>
  )
}
