import { FC, useCallback, useState } from "react"
import {
  Button,
  Group,
  Modal,
  PasswordInput,
  Stack,
  Text,
  TextInput,
} from "@mantine/core"
import { useDisclosure } from "@mantine/hooks"
import { IconLogin, IconLogout } from "@tabler/icons-react"
import { deleteCookie } from "cookies-next"
import { notifyFoTokenChanged } from "@/shared/lib/fo-token-events"
import { CookieKeysEnum } from "@/shared/constants/cookie"
import { useFoTokenPresent } from "@/shared/hooks/useFoTokenPresent"
import { useMegafonAuthMutation } from "@/models/megafon"

const AuthBlock: FC = () => {
  const [opened, { open, close }] = useDisclosure(false)
  const [loginValue, setLoginValue] = useState("")
  const [passwordValue, setPasswordValue] = useState("")
  const [formError, setFormError] = useState<string | null>(null)

  const hasToken = useFoTokenPresent()
  const [login, loginState] = useMegafonAuthMutation()

  const handleClose = useCallback(() => {
    close()
    setFormError(null)
    setPasswordValue("")
  }, [close])

  const handleSubmit = useCallback(async () => {
    setFormError(null)
    const trimmedLogin = loginValue.trim()
    if (!trimmedLogin || !passwordValue) {
      setFormError("Введите логин и пароль")
      return
    }
    try {
      await login({
        login: trimmedLogin,
        password: passwordValue,
      }).unwrap()
      setLoginValue("")
      setPasswordValue("")
      handleClose()
    } catch {
      setFormError("Неверный логин или пароль")
    }
  }, [login, loginValue, passwordValue, handleClose])

  const handleLogout = useCallback(() => {
    deleteCookie(CookieKeysEnum.TOKEN)
    notifyFoTokenChanged()
  }, [])

  return (
    <>
      <Group gap="sm" wrap="wrap" justify="flex-end">
        {hasToken ? (
          <>
            <Text size="sm" c="dimmed" visibleFrom="sm">
              Вы авторизованы
            </Text>
            <Button
              variant="light"
              size="compact-sm"
              leftSection={<IconLogout size={16} />}
              onClick={handleLogout}
            >
              Выйти
            </Button>
          </>
        ) : (
          <Button
            variant="light"
            size="compact-sm"
            leftSection={<IconLogin size={16} />}
            onClick={open}
          >
            Войти
          </Button>
        )}
      </Group>

      <Modal
        opened={opened}
        onClose={handleClose}
        title="Вход в МегаФон"
        centered
      >
        <Stack gap="md">
          <Text size="sm" c="dimmed">
            Нужен для заливки лендингов и других действий через фронт-офис.
          </Text>
          <TextInput
            label="Логин"
            value={loginValue}
            onChange={e => setLoginValue(e.currentTarget.value)}
            autoComplete="username"
            autoFocus
          />
          <PasswordInput
            label="Пароль"
            value={passwordValue}
            onChange={e => setPasswordValue(e.currentTarget.value)}
            autoComplete="current-password"
            onKeyDown={e => {
              if (e.key === "Enter") void handleSubmit()
            }}
          />
          {formError && (
            <Text size="sm" c="red">
              {formError}
            </Text>
          )}
          <Button
            loading={loginState.isLoading}
            onClick={() => void handleSubmit()}
          >
            Войти
          </Button>
        </Stack>
      </Modal>
    </>
  )
}

export default AuthBlock
