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

import { Input, InputProps } from '../input'
import { T } from '../t'
import { formatDate, parseIsoDate, validateDateFormat } from '../utils'

type Props = InputProps & {
  initialDate?: Date
  onChange: (date?: Date) => void
  onValidate: (date?: Date) => string
  setValidateStatus: (inValid: boolean) => void
}

export const DateInput = ({ initialDate, onChange, onValidate, setValidateStatus, ...rest }: Props) => {
  const formattedInitialDate = initialDate ? formatDate(initialDate, 'YYYY-MM-DD', { timeZone: 'UTC' }) : ''
  const [dateInput, setDateInput] = useState<string>(formattedInitialDate)
  const [dateInputValidated, setDateInputValidated] = useState<boolean>(true)
  const [errorMessage, setErrorMessage] = useState<string>('')

  const isValidDate = (dateString: string) => {
    if (!validateDateFormat(dateString)) return false
    if (!parseIsoDate(dateString)) return false
    return true
  }

  const handleOnBlur = () => {
    setDateInputValidated(!dateInput)
    const parsedDate = parseIsoDate(dateInput)
    if (parsedDate) {
      setDateInput(formatDate(parsedDate, 'YYYY-MM-DD', { timeZone: 'UTC' }))
      const validateMessage = onValidate(parsedDate)
      !validateMessage && onChange(parsedDate)
      setDateInputValidated(!validateMessage)
      setErrorMessage(validateMessage)
    }
  }

  useEffect(() => {
    setDateInput(formattedInitialDate)
    const validation = onValidate(initialDate)
    setDateInputValidated(!validation)
    setValidateStatus(!validation)
    setErrorMessage(validation)
  }, [initialDate])

  useEffect(() => {
    if (dateInput) {
      const isValidDateString = isValidDate(dateInput)
      setValidateStatus(isValidDateString)
      if (!validateDateFormat(dateInput)) setErrorMessage('Supported format is YYYY-MM-DD')
      else if (!parseIsoDate(dateInput)) setErrorMessage('Invalid date')
      else {
        const parsedDate = parseIsoDate(dateInput)
        const validateMessage = onValidate(parsedDate)
        !validateMessage && onChange(parsedDate)
        setDateInputValidated(!validateMessage)
        setErrorMessage(validateMessage)
      }
    }
  }, [dateInput])

  return (
    <Input
      borderColor={dateInputValidated ? 'sandstone.main' : 'energyRed.main'}
      className="dateInput"
      data-testid="test-date-input"
      errorText={!dateInputValidated && <T size="md">{errorMessage}</T>}
      onBlur={handleOnBlur}
      onChange={e => setDateInput(e.target.value)}
      placeholder="YYYY-MM-DD"
      size="md"
      state={!dateInputValidated && !errorMessage ? 'error' : 'default'}
      value={dateInput}
      {...rest}
    />
  )
}
