import { useLoginMutation } from "@/hooks/mutations/useLoginMutation"
import { useAuth, useAuthLogin, useAuthLogout } from "@/hooks/useAuth"
import { useMutation } from "@tanstack/react-query"
import { useRouter } from "expo-router"
import { useRef, useState } from "react"
import { Appbar, Button, Dialog, Portal, Surface, Text, TextInput } from "react-native-paper"

export default function Login() {
  const router = useRouter()

  const auth = useAuth()
  const authLogin = useAuthLogin()
  const authLogout = useAuthLogout()

  const isLoggedIn = auth.loggedIn
  const [name, setName] = useState(auth.name ?? "")
  const [password, setPassword] = useState("")
  const [errorDialogVisible, setErrorDialogVisible] = useState(false)
  const [errorTitle, setErrorTitle] = useState("")
  const [errorText, setErrorText] = useState("")

  const loginRef = useRef<any | null>()
  const passwordRef = useRef<any | null>()

  const hideErrorDialog = () => setErrorDialogVisible(false)

  const loginMutation = useLoginMutation({
    authLogin,
    onPostSuccess: () => {
      if (router.canGoBack())
        router.back()
      else
        router.navigate('/')
    },
    onError: ({ response, error }) => {
      setErrorDialogVisible(true)
      if (response) {
        setErrorTitle(response.error)
        setErrorText(response.message)
      }
      else {
        setErrorTitle("Erreur")
        setErrorText(`Une erreur est survenue lors de la connexion : ${error}`)
      }
    }
  })

  return (
    <Surface style={{ flex: 1 }}>
      <Appbar.Header>
        {isLoggedIn && router.canGoBack() ? <Appbar.BackAction onPress={() => router.back()} /> : undefined}
        <Appbar.Content title={"Connexion"} />
        {isLoggedIn ? <Appbar.Action icon={"logout"} onPress={authLogout} /> : undefined}
      </Appbar.Header>
      <TextInput
          ref={loginRef}
          label="Nom"
          value={name}
          onChangeText={setName}
          onSubmitEditing={() => passwordRef?.current.focus()}
          style={{ margin: 8 }} />
      <TextInput
          ref={passwordRef}
          label="Mot de passe"
          value={password}
          onChangeText={setPassword}
          onSubmitEditing={() => loginMutation.mutate({ name, password })}
          secureTextEntry={true}
          style={{ margin: 8 }} />
      <Button
          key={loginMutation.isPending ? "disabledLoginButton" : "loginButton"}
          onPress={() => loginMutation.mutate({ name, password })}
          mode={"contained"}
          icon="login"
          disabled={loginMutation.isPending}
          style={{ margin: 8 }}>
        Se connecter
      </Button>
      <Portal>
        <Dialog visible={errorDialogVisible} onDismiss={hideErrorDialog}>
          <Dialog.Title>{errorTitle}</Dialog.Title>
          <Dialog.Content>
            <Text variant="bodyMedium">{errorText}</Text>
          </Dialog.Content>
          <Dialog.Actions>
            <Button onPress={hideErrorDialog}>Ok</Button>
          </Dialog.Actions>
        </Dialog>
      </Portal>
    </Surface>
  )
}
