import React, { useContext } from 'react'
import Link from 'next/link'
import Contact from './contact'
import BookProvider, { BookContext } from '../../context/book'
import DateSelect from './dateSelect'
import Reason from './reason'
import Button from '../button'
import Required from '../required'

function BookForm() {
  const { onSubmit, onChangeEvent, state, forgetData } = useContext(BookContext)
  const { postData, postDataError, dataStoredLoaded } = state

  return (
    <>
      <form
        className="w-full"
        onSubmit={(event) => {
          event.preventDefault()
          onSubmit()
        }}
      >
        <div className="text-right">
          Mit <Required /> markierte Felder sind Pflichtfelder.
        </div>
        <DateSelect />
        <Reason />
        {dataStoredLoaded && (
          <p className="mb-6 info-message">
            Buchungsdaten wurden aus Deinem Browser geladen und vorausgefüllt.
            <a
              className="ml-3 font-medium text-blue-400 underline cursor-pointer hover:text-blue-600"
              onClick={forgetData}
            >
              Daten wieder vergessen
            </a>
          </p>
        )}
        <Contact />
        <div className="mb-3">
          <label className="form-check-label inline-block text-gray-800 cursor-pointer" htmlFor="termsAgreed">
            <input className="form-check-input h-4 w-4 border border-gray-300 rounded-sm bg-white checked:bg-blue-600 checked:border-blue-600 focus:outline-none transition duration-200 mt-1 align-top bg-no-repeat bg-center bg-contain float-left mr-2 cursor-pointer" type="checkbox" value="" id="termsAgreed" name="termsAgreed" required onChange={onChangeEvent} />
            Ich stimme den <Link href="./terms" target="_blank" className="underline hover:text-blue-700">Mietbedingungen</Link> zu <Required />
          </label>
        </div>
        <div className="flex items-end">
          <Button type="submit" loading={!!postData} disabled={postData}>
            {postData ? 'Speichern...' : 'Absenden'}
          </Button>
          {postDataError && (
            <div className="error-message flex-grow">{postDataError}</div>
          )}
        </div>
      </form>
    </>
  )
}

export default function Book() {
  return (
    <BookProvider>
      <BookForm />
    </BookProvider>
  )
}