import React, { useEffect, useState } from "react"

// Redux
import { useDispatch, useSelector } from "react-redux"
import { actionCreators as loaderActionCreators } from '../../store/reducers/Loader'

import { Link } from "react-router-dom"
import { Button, Container, Form, FormGroup, Input, Label } from "reactstrap"
import { ApplicationState } from "../../store"

import './scss/style.scss'

interface IStateProp {
  [key: string]: string;
}

interface IState extends IStateProp {
  username: string,
  password: string
}

const Signin = () => {
  const dispatch = useDispatch()
  const { content } = useSelector((state: ApplicationState) => state)
  
  const {
    title = "",
    email = {
      title: "",
      placeHolder: ""
    },
    password = {
      title: "",
      placeHolder: ""
    },
    dontHaveAnAccount = "",
    signUpLink = {
      target: "#",
      anchorText: ""
    },
    submit = {
      title: ""
    }
  } = content?.signIn ? content.signIn : {}


  useEffect(() => {
    content?.isLoading
      ? dispatch(loaderActionCreators.show())
      : setTimeout(() => {
        dispatch(loaderActionCreators.hide())
      }, 1000)
  }, [content?.isLoading])

  const [state, hookState] = useState<IState>({
    username: '',
    password: ''
  })

  const setState = (props: IStateProp) => {
    const newState = { ...state }
    Object.keys(props).forEach(key => newState[key] = props[key])
    hookState(newState)
    return newState
  }

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setState({ [name]: value })
  }

  return <Container className="container">
    <h2>{title}</h2>
    <Form className="form">
      <FormGroup>
        <Label for="username">{email.title}</Label>
        <Input
          type="text"
          name="username"
          id="username"
          placeholder={email.placeHolder}
          value={state.username}
          onChange={onChange} />
      </FormGroup>
      <FormGroup>
        <Label for="password">{password.title}</Label>
        <Input
          type="password"
          name="password"
          id="password"
          placeholder={password.placeHolder}
          value={state.password}
          onChange={onChange} />
      </FormGroup>
      <FormGroup>
        {dontHaveAnAccount} <Link to={signUpLink.target}>{signUpLink.anchorText}</Link>.
      </FormGroup>
      <Button>{submit.title}</Button>
    </Form>

    
  </Container>
}

export {
  Signin
}