import { message } from 'antd'
import { Content } from 'antd/lib/layout/layout'
import React, { FormEvent } from 'react'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
import { createClient } from '../api'
import settings from '../settings'

export const Dashboard = () => {
  const history = useHistory()
  const [error, setError] = useState<string | null>(null)
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')

  const handleReset = () => {
    //
    setName('')
    setEmail('')
    setPhone('')
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()

    if (phone.length < 10) {
      // helpful message
      message.error('Check all fields!')
      setError('Phone number needs to be a length of at least 10')
      return
    }

    if (settings.env === 'jank') {
      history.push(`/sessions/${phone}`)
      return
    }

    await createClient({ name, email, phone: parseInt(phone) })
    history.push(`/sessions/${phone}`)
  }

  return (
    <Content>
      <h1>Dashboard</h1>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">
          Name:
          <input
            minLength={3}
            value={name}
            onChange={(e) => setName(e.target.value)}
            name="name"
          />
        </label>
        <label htmlFor="email">
          Email:
          <input
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            type="email"
            name="email"
          />
        </label>
        <label htmlFor="phone">
          Phone:
          <input
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            type="tel"
            name="phone"
          />
        </label>
        <button type="submit">Start Session</button>
        <button type="button" onClick={handleReset}>
          Reset
        </button>
        {error && <p className="error">{error}</p>}
      </form>
    </Content>
  )
}
