import { addTodo, removeTodo } from "@/store/action/todo"
import React, { FormEvent, useRef, useContext } from "react"
import { connect } from "react-redux"
import Header from "./Header"

export interface HomeProps {
  add(text: string): void
  todo: ITodo[]
  remove(id: number): void
}

function Home(props: HomeProps) {
  const { todo, add, remove } = props
  const inputRef = useRef<HTMLInputElement>(null)

  function addOne(e: FormEvent) {
    e.preventDefault()
    let text = inputRef.current!.value
    if (text) {
      inputRef.current!.value = ""
      add(text)
    }
  }

  return (
    <div>
      <Header></Header>
      <div>
        <div className="bg-white min-h-100vh">
          <div className="container clearfix mx-auto  h-500px">
            <form onSubmit={e => addOne(e)}>
              <input ref={inputRef} type="text" />
              <button type="submit">添加</button>
            </form>
            {todo.map((v: ITodo) => {
              return (
                <p onClick={() => remove(v.id)} key={v.id}>
                  {v.text}
                  {v.id}
                </p>
              )
            })}
          </div>
        </div>
        <div className="min-h-100vh"></div>
        <div className="bg-white min-h-100vh">
          <div className="container clearfix mx-auto">
            {[...Array(100)]
              .map((v, i) => i)
              .map(v => {
                return <p key={v}>v</p>
              })}
          </div>
        </div>
      </div>
    </div>
  )
}

const mapStateToProps = (state: any) => {
  return {
    todo: state.todo,
  }
}

const mapDispatchToProps = (dispatch: any) => ({
  add: (text: string) => dispatch(addTodo(text)),
  remove: (id: string | number) => dispatch(removeTodo(id)),
})

export default connect(mapStateToProps, mapDispatchToProps)(Home)
