import * as React from 'react'
import { useRouter } from 'next/router';
import { Container, Col, Form, ButtonToolbar, Button, Input, Content, FlexboxGrid, Stack, Schema } from 'rsuite';
import { useToaster } from 'rsuite';
import { ToastError, ToastSuccess } from '@/components/toasts';
import { toastDefaultProps } from '@/lib/utils/toast';
import SignInWithGoogleButton from '@/components/auth/signInWithGoogle';
import { signInWithEmailAndPasswordHandler, signWithPopupHandler } from '@/lib/firebase/firestore/auth';
import { useAtom } from 'jotai';
import { userAuthAtom } from '@/lib/context/user';
import { UserAuthInfo } from '@/lib/utils/types';
import { useCookies } from 'react-cookie';


const formDefaultValue = {
  email: '',
  password: '',
}


const {StringType} = Schema.Types;
const model = Schema.Model({
  email: StringType()
    .isEmail('Please enter a valid email address.')
    .isRequired('This field is required.'),
  password: StringType()
    .minLength(8, 'Password must be at least 8 characters long.')
    .isRequired('This field is required.'),
});


export default function SignIn() {
  const [formValue, setFormValue] = React.useState<Record<string, any>>(formDefaultValue);
  const ref = React.useRef<any>();
  const [user, setUser] = useAtom(userAuthAtom);
  const toaster = useToaster();
  const router = useRouter();
  const [, setCookie] = useCookies(['auth']);

  async function onSubmit() {
    if (!ref.current.check()) {
      return;
    }

    const res = await signInWithEmailAndPasswordHandler(formValue.email, formValue.password)

    if (res.error) {
      toaster.push(<ToastError msg={res.error}/>, toastDefaultProps)
      return;

    } else {
      toaster.push(<ToastSuccess msg={'You are signed in!'}/>, toastDefaultProps)
      setUser(res.data as UserAuthInfo);
      setCookie('auth', res.data?.uid);
      router.push('/dashboard');
    }

    setFormValue(formDefaultValue);
  }

  async function signInWithGoogle() {
    const res = await signWithPopupHandler();

    if (res.error) {
      toaster.push(<ToastError msg={res.error} />, toastDefaultProps)
      return;

    } else {
      toaster.push(<ToastSuccess msg={'You are signed in!'}/>, toastDefaultProps)
      setUser(res.data as UserAuthInfo);
      setCookie('auth', res.data?.uid)
      router.push('/dashboard');
    }
  }

  return (
    <Container style={{
      backgroundColor: '#F7F7FA',
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      // alignItems: 'center',
    }}>
      {/* Place a div in the middle of the screen */}
      <div style={{
        position: 'absolute',
        top: '50%',
        left: '50%',
        width: 600,
        height: 300,
        borderRadius: 64,
        transform: 'translate(-50%, -50%) skew(0deg, -20deg)',
        backgroundColor: '#F2FAFF',
        boxShadow: '3px 3px 0px 0px rgba(0, 0, 0, 0.12)',
      }}></div>

      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>

        <Content >
          <FlexboxGrid justify="center">
            <FlexboxGrid.Item
              as={Col}
              colspan={8}
              sm={16}
            >
              <Stack spacing={32} direction={'column'} alignItems='stretch'
                style={{
                  padding: "32px 64px",
                  margin: 'auto',
                  maxWidth: 450,
                  borderRadius: 6,
                  backgroundColor: '#fff',
                  boxShadow: '3px 3px 0px 0px rgba(0, 0, 0, 0.12)',
                }}
              >
                <h1>Sign In</h1>
                <Form
                  fluid
                  ref={ref}
                  model={model}
                  onChange={formValue => {setFormValue(formValue)}}
                  onCheck={formError => {setFormValue(formError)}}
                  formValue={formValue}
                >
                  <Form.Group controlId="email">
                    <Form.ControlLabel>Email</Form.ControlLabel>
                    <Form.Control name="email" type="email" placeholder='Type your email...' />
                    <Form.HelpText>Required</Form.HelpText>
                  </Form.Group>

                  <Form.Group controlId="password">
                    <Form.ControlLabel>Password</Form.ControlLabel>
                    <Form.Control name="password" type="password" autoComplete="off" placeholder='Type your password' />
                    <Form.HelpText>If you have sign up using Google, please sign in with google</Form.HelpText>
                  </Form.Group>

                  <Form.Group>
                    <ButtonToolbar>
                      <Button appearance="primary" block onClick={onSubmit}>Sign In</Button>
                    </ButtonToolbar>
                  </Form.Group>
                </Form>

                <p>Or Sign In Using</p>

                <Stack direction='column' alignItems='stretch'>
                  <SignInWithGoogleButton onClick={signInWithGoogle}/>
                </Stack>
                
                
                <a>Forgot password ?</a>
              </Stack>
            </FlexboxGrid.Item>
          </FlexboxGrid>
        </Content>
      </div>
    </Container>
  )
}