import React, { useState, useContext, useEffect } from 'react'
import { Tooltip } from 'antd'
import { makeApiRequest } from '../common'
import arcmIcons from '../Icons'
import Modal from '../components/core/Modal'
import connectionContext from '../context/connectionContext'
import { useTranslations } from '../hooks/useTranslation'

const AwsConfigure = ({ onvVeiwChange, ...props }) => {
  const { t } = useTranslations();
  const [isOpen, setIsOpen] = useState(false)
  const [loading, setLoading] = useState(true)
  const [modifyConnection, setModifyConnection] = useState(false)
  const [ConnectionErrorMsg, setConnectionErrorMsg] = useState('')
  const {
    awsConnection,
    handleAwsconnection,
    handleOnboardingComplete,
    rdsCredential,
    setRdsCredential
  } = useContext(connectionContext)
  const [rdsConnectionnTitle, setRdsConnectionTitle] = useState(t('rds_connecting_to_remote_db'))
  const [rdsConnectionDesc, setRdsConnectionDesc] = useState(t('rds_connection_establishing'))

  const handleRdsConnection = async () => {
    setIsOpen(true)
    setLoading(true)
    const rdsConnection = await makeApiRequest(
      'rds-connection',
      'POST',
      rdsCredential
    )
    if (rdsConnection.success) {
      handleAwsconnection(true)
      if (!('rds_credential' in archm_admin.archm_settings)) {
        archm_admin.archm_settings.rds_credential = rdsCredential
      } else {
        Object.assign(archm_admin.archm_settings.rds_credential, rdsCredential)
      }
      setRdsConnectionTitle(t('database_connected'))
      setRdsConnectionDesc(t('creating_wordpress_schema'))
      const installWordpress = await makeApiRequest(
        'install-wordpress',
        'POST',
        rdsCredential
      )
      if (installWordpress.success) {
        setLoading(false)
        setConnectionErrorMsg(installWordpress.message)
      }
    } else {
      setLoading(false)
      handleAwsconnection(false)
      handleOnboardingComplete(false)
      setConnectionErrorMsg(rdsConnection.message)
    }
  }

  const handleToggleModal = () => {
    setIsOpen(!isOpen)
    setRdsConnectionTitle(t('rds_connecting_to_remote_db'))
    setRdsConnectionDesc(t('rds_connection_establishing'))
  }

  const setModifyConnectionInputFocus = () => {
    setModifyConnection(true)
    setTimeout(() => {
      const db_name = document.querySelector('#db_name')
      db_name.focus()
    }, 0)
  }

  return (
    <div className='aws-configure'>
      <button
        onClick={() => onvVeiwChange('archive_settings')}
        className='arcm-flex arcm-items-center arcm-justify-center arcm-text-[#3858e9] arcm-text-sm arcm-font-semibold'
      >
        <div className='icon arcm-mr-2'>{arcmIcons.arrowLeft}</div>
        {t('back_to_settings')}
      </button>

      <div className='aws-configure__edit arcm-mt-4 arcm-px-6 arcm-pt-12 arcm-pb-14 arcm-bg-white arcm-rounded-2xl'>
        <div className='icon arcm-mb-4'>{arcmIcons.aws}</div>
        <div className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-mb-6'>
          {t('aws_rds.title')}
        </div>
        {!awsConnection ? (
          <>
            <div className='arcm-text-gray-800 arcm-text-xl arcm-font-bold arcm-mb-1'>
              {t('rds_configure_connection')}
            </div>
            <div className='arcm-text-gray-600 arcm-text-sm arcm-font-normal'>
              {t('connect_to_aws_rds')}
            </div>
            <div className='arcm-text-[#3858E9] arcm-flex arcm-font-[14px] arcm-mt-1'>
              <b>
                <a
                  className='arcm-underline arcm-mr-1 arcm-decoration-1'
                  target='_blank'
                  href='https://console.aws.amazon.com/rds/home'
                >
                  {t('click_here')}
                </a>
              </b>
              {t('to_rds_portal')}
              {arcmIcons.arrowRight}
            </div>
          </>
        ) : (
          <>
            <div className='arcm-wrap arcm-flex arcm-justify-between arcm-items-center arcm-gap-3 arcm-max-w-[671px]'>
              <div className='arcm-wrap__text'>
                <div className='arcm-text-gray-800 arcm-text-xl arcm-font-bold arcm-mb-1'>
                  <span className='arcm-inline-flex arcm-w-[17px] arcm-h-[17px] arcm-bg-[#27d935] arcm-rounded-full arcm-mr-2'></span>
                  {t('aws_rds.connected')}
                </div>
                <div className='arcm-text-gray-600 arcm-text-sm arcm-font-normal'>
                  {t('rds_connection_success')}
                </div>
              </div>
              <div className='arcm-wrap__btn-box'>
                <button
                  onClick={() => setModifyConnectionInputFocus()}
                  className='arcm-text-[#3858e9] arcm-text-sm arcm-font-semibold arcm-px-4 arcm-py-3 arcm-bg-white arcm-rounded-lg arcm-border arcm-border-[#3858e9] arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all arcm-group hover:arcm-text-white hover:arcm-bg-[#3858e9]'
                >
                  {arcmIcons.edit} {t('rds_modify_connection')}
                </button>
              </div>
            </div>
          </>
        )}

        <div className='arcm-flex arcm-flex-col lg:arcm-flex-row arcm-gap-8'>
          <div className='aws-configure__form arcm-max-w-[671px] arcm-mt-6 arcm-w-[50%] arcm-mr-[126px]'>
            {/* Database Form Fields */}
            <div className='input-field arcm-mb-4'>
              <label
                htmlFor='db_name'
                className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
              >
                <span className='arcm-mr-1'>
                  {t('database')}
                  {!awsConnection && (
                    <span className='arcm-text-slate-400 arcm-text-[13px]'>
                      {t('database_name_rules')}
                    </span>
                  )}
                </span>
                <Tooltip
                  className='arcm-text-sm'
                  placement='right'
                  title={t('database_name_tooltip')}
                  color='#fff'
                >
                  {arcmIcons.info}
                </Tooltip>
              </label>
              <input
                disabled={awsConnection && !modifyConnection}
                type='text'
                value={rdsCredential.rds_dbname}
                onChange={e =>
                  setRdsCredential({
                    ...rdsCredential,
                    rds_dbname: e.target.value
                  })
                }
                id='db_name'
                placeholder={t('database_placeholder')}
                className='!arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full focus:!arcm-border-[#3858e9]'
              />
            </div>

            {/* Username Field */}
            <div className='input-field arcm-mb-4'>
              <label
                htmlFor='db_user'
                className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
              >
                <span className='arcm-mr-1'>{t('username')}</span>
                <Tooltip
                  className='arcm-text-sm'
                  placement='right'
                  title={t('username_tooltip')}
                  color='#fff'
                >
                  {arcmIcons.info}
                </Tooltip>
              </label>
              <input
                disabled={awsConnection && !modifyConnection}
                type='text'
                value={rdsCredential.rds_username}
                onChange={e =>
                  setRdsCredential({
                    ...rdsCredential,
                    rds_username: e.target.value
                  })
                }
                id='db_user'
                placeholder={t('username_placeholder')}
                className='!arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full focus:!arcm-border-[#3858e9]'
              />
            </div>

            {/* Password Field */}
            <div className='input-field arcm-mb-4'>
              <label
                htmlFor='db_password'
                className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
              >
                <span className='arcm-mr-1'>{t('password')}</span>
                <Tooltip
                  className='arcm-text-sm'
                  placement='right'
                  title={t('password_tooltip')}
                  color='#fff'
                >
                  {arcmIcons.info}
                </Tooltip>
              </label>
              <input
                disabled={awsConnection && !modifyConnection}
                type='password'
                value={rdsCredential.rds_password}
                onChange={e =>
                  setRdsCredential({
                    ...rdsCredential,
                    rds_password: e.target.value
                  })
                }
                id='db_password'
                placeholder={t('password_placeholder')}
                className='!arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full focus:!arcm-border-[#3858e9]'
              />
            </div>

            {/* Port Field */}
            <div className='input-field arcm-mb-4'>
              <label
                htmlFor='db_port'
                className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
              >
                <span className='arcm-mr-1'>{t('port')}</span>
                <Tooltip
                  className='arcm-text-sm'
                  placement='right'
                  title={t('port_tooltip')}
                  color='#fff'
                >
                  {arcmIcons.info}
                </Tooltip>
              </label>
              <input
                disabled={awsConnection && !modifyConnection}
                type='number'
                value={rdsCredential.rds_port}
                onChange={e =>
                  setRdsCredential({
                    ...rdsCredential,
                    rds_port: e.target.value
                  })
                }
                id='db_port'
                placeholder={t('port_placeholder')}
                className='!arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full focus:!arcm-border-[#3858e9]'
              />
            </div>

            {/* Endpoint Field */}
            <div className='input-field arcm-mb-4'>
              <label
                htmlFor='db_endpoint'
                className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
              >
                <span className='arcm-mr-1'>{t('endpoint')}</span>
                <Tooltip
                  className='arcm-text-sm'
                  placement='right'
                  title={t('endpoint_tooltip')}
                  color='#fff'
                >
                  {arcmIcons.info}
                </Tooltip>
              </label>
              <input
                disabled={awsConnection && !modifyConnection}
                type='text'
                value={rdsCredential.rds_endpoint}
                onChange={e =>
                  setRdsCredential({
                    ...rdsCredential,
                    rds_endpoint: e.target.value
                  })
                }
                id='db_endpoint'
                placeholder={t('endpoint_placeholder')}
                className='!arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full focus:!arcm-border-[#3858e9]'
              />
            </div>

            <button
              onClick={handleRdsConnection}
              className='arcm-text-white arcm-text-xs sm:arcm-text-sm arcm-font-semibold arcm-px-4 arcm-py-3 arcm-bg-[#3858e9] arcm-rounded-lg arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all hover:arcm-bg-blue-700'
            >
              <span>{t('connect_to_rds')}</span>
            </button>
          </div>

          {/* Video Guide Section */}
          <div className='arcm-relative arcm-h-[100%] arcm-w-[50%] arcm-m-auto'>
            <span className='arcm-text-[#111827] arcm-font-[14px] arcm-flex arcm-items-center arcm-text-sm'>
              {arcmIcons.play}
              {t('step_by_step_guide')}
            </span>
            <div className='arcm-h-[365px] arcm-w-full arcm-aspect-video arcm-mb-4'>
              <iframe
                className='arcm-h-full arcm-w-full arcm-rounded-[22px]'
                src='https://www.youtube.com/embed/ts7OT9OYbmE?playlist=gLTNZAXYxPY&controls=1&showinfo=0&rel=0'
                allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen'
                allowFullScreen
              ></iframe>
            </div>
            <p className='arcm-text-sm arcm-text-left arcm-w-[300px]'>
              {t('prefer_reading')}{' '}
              <a
                target='_blank'
                className='arcm-text-[#3858E9] arcm-underline'
                href='https://wppool.dev/docs-category/archive-master-docs/'
              >
                {t('documentation_link')}
              </a>{' '}
              {t('for_written_guide')}
            </p>
          </div>
        </div>
      </div>

      {/* Connection Modal */}
      <Modal
        openModal={isOpen}
        toggleModal={handleToggleModal}
        outerClick={false}
      >
        {{
          body: loading ? (
            <div className='arcm-text-center arcm-mb-6'>
              <div className='icon arcm-inline-flex'>
                {arcmIcons.SpinningAnimation}
              </div>
              <h5 className='arcm-text-gray-900 arcm-text-base arcm-font-semibold arcm-mb-1.5'>
                {rdsConnectionnTitle}
              </h5>
              <p className='arcm-text-center arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-6'>
                {rdsConnectionDesc}
              </p>
              <button
                onClick={handleToggleModal}
                className='arcm-text-gray-900 arcm-text-sm arcm-font-semibold arcm-min-w-[120px] arcm-px-4 arcm-py-2.5 arcm-rounded-lg arcm-bg-slate-100 arcm-transition-all hover:arcm-bg-[#F44336] hover:arcm-text-white'
              >
                {t('cancel')}
              </button>
            </div>
          ) : (
            <div className='arcm-text-center arcm-my-6'>
              {awsConnection ? (
                <>
                  <div className='icon arcm-inline-flex arcm-mb-6'>
                    {arcmIcons.success}
                  </div>
                  <h5 className='arcm-text-gray-900 arcm-text-base arcm-font-semibold arcm-mb-1.5'>
                    {t('connection_success_message')}
                  </h5>
                  <p className='arcm-max-w-[384px] arcm-ml-auto arcm-mr-auto arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-6'>
                    {ConnectionErrorMsg}
                  </p>
                  <button
                    onClick={handleToggleModal}
                    className='arcm-text-white arcm-text-sm arcm-font-semibold arcm-px-4 arcm-py-3 arcm-min-w-[120px] arcm-bg-[#3858e9] arcm-rounded-lg arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all hover:arcm-bg-blue-700'
                  >
                    <span>{t('rds_done')}</span>
                  </button>
                </>
              ) : (
                <>
                  <div className='icon arcm-inline-flex arcm-mb-6'>
                    {arcmIcons.error}
                  </div>
                  <h5 className='arcm-text-gray-900 arcm-text-base arcm-font-semibold arcm-mb-1.5'>
                    {t('rds_connection_failed')}
                  </h5>
                  <p className='arcm-max-w-[384px] arcm-ml-auto arcm-mr-auto arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-6'>
                    {ConnectionErrorMsg}
                  </p>
                  <button
                    onClick={handleToggleModal}
                    className='arcm-text-white arcm-text-sm arcm-font-semibold arcm-px-4 arcm-py-3 arcm-min-w-[120px] arcm-bg-[#3858e9] arcm-rounded-lg arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all hover:arcm-bg-blue-700'
                  >
                    <span>{t('ok')}</span>
                  </button>
                </>
              )}
            </div>
          )
        }}
      </Modal>
    </div>
  )
}

export default AwsConfigure