import React, { FC, useEffect, useRef } from 'react'
import { useI18n } from '@wordpress/react-i18n'
import bringLogo from '../../assets/img/Bring_logo.svg'
import { Button, SelectControl, TextareaControl } from '@wordpress/components'
import apiFetch from '@wordpress/api-fetch'
import { useEnableWpCompatOverlaySlot } from '@wordpress/ui'

const Deactivate: FC = () => {
  const [reason, setReason] = React.useState<string>('')
  const [additionalFeedback, setAdditionalFeedback] = React.useState<string>('')
  const { __ } = useI18n()
  const [saving, setSaving] = React.useState<boolean>(false)
  const ref = useRef<HTMLSelectElement | null>(null)
  useEnableWpCompatOverlaySlot()

  useEffect(() => {
    const focus = () => {
      ref.current?.focus()
    }

    window.addEventListener('posten-bring-checkout:deactivate:open', focus)
  }, [])

  const reset = () => {
    setSaving(false)
    setReason('')
    setAdditionalFeedback('')
  }

  const closeModal = () => {
    reset()
    window.dispatchEvent(
      new CustomEvent('posten-bring-checkout:deactivate:continue')
    )
  }

  const handleDeactivationFeedback = () => {
    if (reason === '' && additionalFeedback === '') {
      closeModal()
    } else {
      setSaving(true)
      apiFetch({
        path: `/posten-bring-checkout/deactivate`,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          reason,
          feedback: additionalFeedback,
        }),
      })
        .then(() => {
          closeModal()
        })
        .catch(() => {
          closeModal()
        })
    }
  }

  return (
    <div id="deactivate-container">
      <img className="bring-logo mrm" src={bringLogo} alt={''} />
      <h1>{__('Sorry to see you leave!', 'posten-bring-checkout')}</h1>
      <div>
        <p className="mbl">
          {__(
            'Would you like to share why? Any feedback is much appreciated',
            'posten-bring-checkout'
          )}
        </p>
        <div className="feedback-form">
          <SelectControl
            label={__('Select a reason (optional)', 'posten-bring-checkout')}
            value={reason}
            ref={ref}
            options={[
              {
                label: __('Please select', 'posten-bring-checkout'),
                value: '',
                disabled: true,
              },
              {
                label: __('Not using the plugin now', 'posten-bring-checkout'),
                value: 'Not using the plugin now',
              },
              {
                label: __('Hard to set up or use', 'posten-bring-checkout'),
                value: 'Hard to set up or use',
              },
              {
                label: __(
                  'Not satisfied with support',
                  'posten-bring-checkout'
                ),
                value: 'Not satisfied with support',
              },
              {
                label: __(
                  'Limited or missing features',
                  'posten-bring-checkout'
                ),
                value: 'Limited or missing features',
              },
              {
                label: __(
                  'Not working or compatible with theme or store',
                  'posten-bring-checkout'
                ),
                value: 'Not working or compatible with theme or store',
              },
            ]}
            onChange={(selectedReason: string) => setReason(selectedReason)}
          />
          {reason !== '' && (
            <TextareaControl
              label={__(
                'Any additional comments for us?',
                'posten-bring-checkout'
              )}
              className="mtm"
              value={additionalFeedback}
              onChange={value => setAdditionalFeedback(value)}
            />
          )}
          {reason === '' ? (
            <Button
              variant="primary"
              onClick={handleDeactivationFeedback}
              className="mtl"
              isBusy={saving}
            >
              {__('Continue deactivation', 'posten-bring-checkout')}
            </Button>
          ) : (
            <Button
              variant="primary"
              onClick={handleDeactivationFeedback}
              className="mtl"
              isBusy={saving}
            >
              {__('Submit and continue deactivation', 'posten-bring-checkout')}
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}

export default Deactivate
