import React, { useState, useCallback } from 'react'
import { Button, Modal, SelectControl } from '@wordpress/components'
import {
  FeedbackSuccess,
  FeedbackWarning,
} from './FeedbackBanner'
import { __ } from '@wordpress/i18n'
import apiFetch from '@wordpress/api-fetch'

export declare interface FeedbackFormProps
  extends React.HTMLProps<HTMLDivElement> {}

const FeedbackForm: React.FC<FeedbackFormProps> = ({ className }) => {
  const [active, setActive] = useState<boolean>(false)
  const [status, setStatus] = useState<string>('')
  const [category, setCategory] = useState<string>('Problem')
  const [message, setMessage] = useState<string>('')
  const [email, setEmail] = useState<string>('')
  const [submittable, setSubmittable] = useState<boolean>(false)

  const handleChange = useCallback(() => {
    if (active) {
      // Closing modal - reset form fields
      setMessage('')
      setEmail('')
      setSubmittable(false)
      setStatus('')
    } else {
      validateForm(email, message)
    }
    setActive(!active)
  }, [active, email, message])

  const validateForm = useCallback((emailValue: string, messageValue: string) => {
    const hasValidEmail = emailValue.trim().length > 0
    const hasValidMessage = messageValue.trim().length > 0
    setSubmittable(hasValidEmail && hasValidMessage)
  }, [])

  const handleFeedback = () => {
    const feedbackData = {
      category,
      message: message.trim(),
      email: email.trim(),
    }

    apiFetch({
      path: `/posten-bring-checkout/feedback`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(feedbackData),
    })
      .then(() => {
        setStatus('success')
        setMessage('')
        setEmail('')
        setSubmittable(false)
      })
      .catch(() => {
        setStatus('error')
      })
  }

  const handleMessageChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value
    setMessage(value)
    validateForm(email, value)
  }

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setEmail(value)
    validateForm(value, message)
  }

  const renderPlaceholder = (): string => {
    switch (category) {
      case 'Problem':
        return __('How can we improve?', 'posten-bring-checkout')
      case 'Feature request':
        return __('What should we add?', 'posten-bring-checkout')
      case 'Praise':
        return __('What did we do correctly?', 'posten-bring-checkout')
      default:
        return __('How can we improve?', 'posten-bring-checkout')
    }
  }

  return (
    <div className={className}>
      <div className="feedback-form__button-container">
        <Button
          onClick={handleChange}
          variant="secondary"
          icon="admin-comments"
        >
          {__('Send feedback', 'posten-bring-checkout')}
        </Button>
      </div>
      {active && (
        <Modal
          onRequestClose={handleChange}
          title={__('Posten Bring Checkout Feedback', 'posten-bring-checkout')}
        >
          <div id="feedback-form-container">
            <SelectControl
              label={__('Select a category', 'posten-bring-checkout')}
              value={category}
              options={[
                {
                  label: __('Problem', 'posten-bring-checkout'),
                  value: 'Problem',
                },
                {
                  label: __('Feature request!', 'posten-bring-checkout'),
                  value: 'Feature request',
                },
                {
                  label: __('Praise', 'posten-bring-checkout'),
                  value: 'Praise',
                },
              ]}
              onChange={(newCategory: string) => setCategory(newCategory)}
            />
            <input
              type="email"
              className="feedback-form__email"
              placeholder="Email"
              value={email}
              onChange={handleEmailChange}
            />
            <textarea
              className="feedback-form__message"
              placeholder={renderPlaceholder()}
              rows={6}
              value={message}
              onChange={handleMessageChange}
            />
            <div className="feedback-form__bottom-text mtm">
              <Button
                disabled={!submittable}
                onClick={handleFeedback}
                variant={'primary'}
              >
                {__('Submit', 'posten-bring-checkout')}
              </Button>

              <div className="feedback-form__link">
                {__('Want to contact ', 'posten-bring-checkout')}
                <a
                  href={__(
                    'https://www.bring.com/resources/mybring#mybring',
                    'posten-bring-checkout'
                  )}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  Mybring?
                </a>
              </div>
            </div>
            <div className="feedback-form__status">
              {status === 'success' && <FeedbackSuccess />}
              {status === 'error' && <FeedbackWarning />}
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

export default FeedbackForm
