import { Box, Button, Flex, Image, Text } from '@chakra-ui/react';

import avatar from '@/assets/images/avatar_generic.svg';
import { PageLayout } from '@/components/Layout/PageLayout';
import { FormInput } from '@/components/form/FormInput';
import { FormPassword } from '@/components/form/FormPassword';
import { useFormidable } from '@/components/formidable/FormidableConfig';
import { FormidableForm } from '@/components/formidable/FormidableForm';

import { useLogin } from './useLogin';

type LoginFormInputs = {
  login: string;
  password: string;
};

export const SignInPage = () => {
  const form = useFormidable<LoginFormInputs>({
    initialValues: {
      login: '',
      password: '',
    },
    configuration: {
      enableModifyNotification: false,
      enableReset: false,
    },
  });
  const { connect, lastError, isConnectionLoading } = useLogin();

  const onSubmit = () => {
    connect(form.values.login, form.values.password);
  };

  return (
    <>
      {/* <TopBar title="Login" /> */}
      <PageLayout>
        <Flex marginX="auto" width="full" height="90%" direction="column">
          <Box
            bg="white"
            padding="30px"
            shadow="md"
            width="400px"
            margin="auto"
            background={{ _light: 'gray.50', _dark: 'gray.800' }}
          >
            <Text
              width="100%"
              textAlign="center"
              fontWeight="bold"
              fontSize="25px"
            >
              Sign-In
            </Text>
            <Image
              marginX="auto"
              marginY="10px"
              src={avatar}
              width="128px"
              height="128px"
              borderRadius="100%"
            />
            <FormidableForm form={form} onSubmit={onSubmit}>
              <Flex align="center" justify="center" direction="column">
                {lastError && <Text colorPalette="@danger">{lastError}</Text>}
                <FormInput name="login" isRequired label="Username" />
                <FormPassword name="password" isRequired label="Password" />
                <Button
                  marginLeft="55%"
                  marginTop="10px"
                  variant="solid"
                  background="green"
                  width="45%"
                  disabled={isConnectionLoading}
                  type="submit"
                >
                  Login
                </Button>
              </Flex>
            </FormidableForm>
          </Box>
        </Flex>
      </PageLayout>
    </>
  );
};
