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

const CustomMySQLConfigure = ({ onvVeiwChange, ...props }) => {
  const { t } = useTranslations()
  const [isOpen, setIsOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [modifyConnection, setModifyConnection] = useState(false)
  const [connectionErrorMsg, setConnectionErrorMsg] = useState('')
  const [connectionType, setConnectionType] = useState('current') // 'current' or 'external'
  const [savedConnectionType, setSavedConnectionType] = useState('current')
  // Connection type switch confirmation modal state
  const [connectionTypeModal, setConnectionTypeModal] = useState({ open: false, targetType: null, currentType: null })
  const {
    customMySQLConnection,
    handleCustomMySQLConnection,
    handleOnboardingComplete,
    customMySQLCredential,
    setCustomMySQLCredential
  } = useContext(connectionContext)
 
  const [connectionTitle, setConnectionTitle] = useState(
    t('connecting_to_remote_db')
  )
  const [connectionDesc, setConnectionDesc] = useState(
    t('connection_establishing')
  )

  const handleSetupConnection = async () => {
    setIsOpen(true)
    setLoading(true)
    setConnectionTitle(t('setting_up_custom_mysql'))
    setConnectionDesc(t('creating_database_tables'))

    const response = await Ajax.post(
      'archm_pro_mysql_setup',
      {
        ...customMySQLCredential,
        connectionType: connectionType
      }
    )

    if (response.success) {
      handleCustomMySQLConnection(true)
      window.archm_admin.archm_settings.cmysql_connection_type = connectionType
      window.archm_admin.archm_settings.cmysql_credential ={
        cmysql_dbname: customMySQLCredential.database,
        cmysql_endpoint: customMySQLCredential.endpoint,
        cmysql_password: customMySQLCredential.password,
        cmysql_port: customMySQLCredential.port,
        cmysql_username: customMySQLCredential.username
      }
      setConnectionTitle(t('database_ready'))
      setConnectionDesc(
        t('mysql_database_created')
      )
      setLoading(false)
      setModifyConnection(false)
      setConnectionErrorMsg(
        response.data?.message || response.message || t('setup_completed')
      )
    } else {
      setLoading(false)
      handleCustomMySQLConnection(false)
      handleOnboardingComplete(false)
      setConnectionErrorMsg(
        response.data?.message || response.message || t('setup_failed')
      )
    }
  }

  const handleToggleModal = () => {
    setIsOpen(!isOpen)
    setConnectionTitle(t('connecting_to_remote_db'))
    setConnectionDesc(t('connection_establishing'))
  }

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

  // Handle connection type switch with confirmation
  const handleConnectionTypeSwitch = (targetType) => {
    // If switching to the same type, no need for confirmation
    if (connectionType === targetType) {
      return
    }
    
    // Show confirmation modal
    setConnectionTypeModal({
      open: true,
      targetType: targetType,
      currentType: connectionType
    })
  }

  const closeConnectionTypeModal = () => {
    setConnectionTypeModal({ open: false, targetType: null, currentType: null })
  }

  const confirmConnectionTypeSwitch = () => {
    // Actually switch the connection type
    setConnectionType(connectionTypeModal.targetType)
    closeConnectionTypeModal()
  }

  // Initialize connection type from settings (runs once on mount)
  useEffect(() => {
    const customMySQLCreds = window?.archm_admin?.archm_settings?.cmysql_credential
    const connectionTypeFromSettings = window?.archm_admin?.archm_settings?.cmysql_connection_type || 'current'
    const wpDbCreds = window?.archm_admin?.archm_settings?.wp_db_credentials
  
    if(customMySQLCreds) {
      setSavedConnectionType(connectionTypeFromSettings)
      setConnectionType(connectionTypeFromSettings)
    }else{
      setCustomMySQLCredential({
        endpoint: wpDbCreds?.wp_db_host || '',
        port: wpDbCreds?.wp_db_port || '3306',
        username: wpDbCreds?.wp_db_user || '',
        password: wpDbCreds?.wp_db_pass || '',
        database: ''
      })
    }
  }, []) // Only run on mount

  // Handle credential updates when connection type changes (but don't reset connectionType)
  useEffect(() => {
    const customMySQLCreds = window?.archm_admin?.archm_settings?.cmysql_credential
    const wpDbCreds = window?.archm_admin?.archm_settings?.wp_db_credentials

    // Don't run if credentials don't exist or savedConnectionType isn't initialized yet
    if(!customMySQLCreds || !savedConnectionType) return

    // If switching back to the saved connection type, restore saved credentials
    if (connectionType === savedConnectionType) {
      setCustomMySQLCredential({
        endpoint: customMySQLCreds.cmysql_endpoint || '',
        port: customMySQLCreds.cmysql_port || '3306',
        username: customMySQLCreds.cmysql_username || '',
        password: customMySQLCreds.cmysql_password || '',
        database: customMySQLCreds.cmysql_dbname || ''
      })
    } else {
      // If switching to a different connection type, update the fields accordingly
      if('current' === connectionType) {
        setCustomMySQLCredential({
          endpoint: wpDbCreds?.wp_db_host || '',
          port: wpDbCreds?.wp_db_port || '3306',
          username: wpDbCreds?.wp_db_user || '',
          password: wpDbCreds?.wp_db_pass || '',
          database: ''
        })
      } else {
        setCustomMySQLCredential({
          endpoint: '',
          port: '',
          username: '',
          password: '',
          database: ''
        })
      }
    }
  }, [connectionType, savedConnectionType]) // Run when connectionType or savedConnectionType changes

  return (
    <div className='custom-mysql-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='custom-mysql-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'>
          <svg
            xmlns='http://www.w3.org/2000/svg'
            width='59'
            height='30'
            viewBox='0 0 59 30'
            fill='none'
          >
            <path
              d='M0 27.3248H1.91381V19.7675L4.87648 26.3557C5.2261 27.153 5.70462 27.4352 6.64305 27.4352C7.58162 27.4352 8.04167 27.1531 8.39144 26.3557L11.3541 19.7675V27.3247H13.2679V19.7798C13.2679 19.0436 12.9734 18.6879 12.3663 18.504C10.9125 18.0501 9.93715 18.4426 9.49543 19.4241L6.58791 25.9262L3.77248 19.4241C3.34924 18.4426 2.35553 18.0501 0.901765 18.504C0.294478 18.6879 0 19.0438 0 19.7797V27.3248ZM14.8592 21.1735H16.7724V25.3371C16.7546 25.5633 16.845 26.0941 17.8934 26.1105C18.4283 26.119 22.0215 26.1105 22.055 26.1105V21.1533H23.9727C23.9815 21.1533 23.9708 27.9138 23.9709 27.9425C23.9814 29.6098 21.9021 29.972 20.9437 30H14.9007V28.7124C14.9114 28.7124 20.9393 28.7137 20.9545 28.7122C22.1862 28.5821 22.0407 27.9699 22.0406 27.7638V27.2619H17.9727C16.0801 27.2445 14.875 26.4184 14.8601 25.4684C14.8586 25.3803 14.901 21.2151 14.8591 21.1734L14.8592 21.1735Z'
              fill='#00618A'
            />
            <path
              d='M25.4477 27.3248H30.9498C31.5938 27.3248 32.2195 27.1899 32.7165 26.9567C33.5445 26.5765 33.9494 26.0613 33.9494 25.3864V23.9879C33.9494 23.4358 33.4893 22.9204 32.5876 22.5771C32.109 22.3929 31.5202 22.2948 30.9498 22.2948H28.6309C27.8583 22.2948 27.4902 22.0617 27.3983 21.5466C27.3798 21.4852 27.3798 21.436 27.3798 21.3747V20.5038C27.3798 20.4546 27.3798 20.4054 27.3983 20.3442C27.4902 19.9517 27.6928 19.8411 28.3735 19.7798C28.4287 19.7798 28.5023 19.7675 28.5576 19.7675H34.023V18.4918H28.6495C27.8767 18.4918 27.4717 18.5408 27.1038 18.6511C25.9628 19.007 25.466 19.5713 25.466 20.5527V21.6692C25.466 22.528 26.4414 23.2641 28.079 23.4358C28.2632 23.448 28.4471 23.4602 28.631 23.4602H30.6185C30.6922 23.4602 30.7659 23.4602 30.821 23.4726C31.4283 23.5218 31.6858 23.632 31.87 23.8529C31.9803 23.9632 32.0171 24.0738 32.0171 24.1964V25.3126C32.0171 25.4478 31.9251 25.6196 31.7412 25.7667C31.5755 25.914 31.2995 26.0122 30.9314 26.0367C30.8578 26.0367 30.8027 26.049 30.729 26.049H25.4475V27.3246L25.4477 27.3248ZM45.8883 25.1043C45.8883 26.4169 46.8635 27.1531 48.8326 27.3004C49.0165 27.3126 49.2007 27.3248 49.3846 27.3248H54.3717V26.049H49.3478C48.2253 26.049 47.8021 25.7667 47.8021 25.0921V18.4916H45.8883V25.1043ZM35.1708 25.1712V20.6224C35.1708 19.4669 35.9823 18.766 37.5864 18.5447C37.7574 18.5203 37.93 18.508 38.1028 18.5079H41.7355C41.9198 18.5079 42.086 18.5203 42.2703 18.5447C43.8746 18.766 44.6859 19.4669 44.6859 20.6224V25.171C44.6859 26.1084 44.3414 26.6104 43.5472 26.9373L45.4324 28.6389H43.2102L41.6851 27.2622L40.1497 27.3595H38.1028C37.7524 27.3595 37.3837 27.3102 36.9779 27.1996C35.761 26.8677 35.1708 26.2284 35.1708 25.171V25.1712ZM37.2363 25.0606C37.2363 25.1222 37.2548 25.1836 37.2733 25.2573C37.3839 25.7859 37.8818 26.081 38.6378 26.081H40.3765L38.7794 24.6392H41.0014L42.3945 25.8967C42.6511 25.7599 42.8201 25.5506 42.8791 25.2819C42.8974 25.2205 42.8974 25.159 42.8974 25.0976V20.7333C42.8974 20.6841 42.8974 20.6226 42.8791 20.561C42.7684 20.0692 42.2705 19.7867 41.5329 19.7867H38.6378C37.7897 19.7867 37.2365 20.1555 37.2365 20.7333V25.0606H37.2363Z'
              fill='#E48E00'
            />
          </svg>
        </div>
        <div className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-mb-6'>
          {t('mysql_database')}
        </div>
        {!customMySQLConnection ? (
          <>
            <div className='arcm-text-gray-800 arcm-text-xl arcm-font-bold arcm-mb-1'>
              {t('configure_custom_mysql')}
            </div>
            <div className='arcm-text-gray-600 arcm-text-sm arcm-font-normal arcm-mb-2'>
              {t('connect_to_current_or_remote')}
            </div>
            <div className='arcm-text-gray-600 arcm-text-xs arcm-font-normal'>
              {t('need_help')}{' '}
              <a
                href='https://wppool.dev/docs/how-to-configure-a-custom-mysql-database-for-archivemaster/'
                target='_blank'
                rel='noopener noreferrer'
                className='arcm-text-[#3858e9] arcm-font-medium hover:arcm-underline'
              >
                {t('read_mysql_guide')}
              </a>
            </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('connected')}
                </div>
                <div className='arcm-text-gray-600 arcm-text-sm arcm-font-normal'>
                  {t('successfully_connected_mysql')}
                </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('modify_connection')}
                </button>
              </div>
            </div>
          </>
        )}

        {/* Radio Buttons for Connection Type */}
        <div className='arcm-flex arcm-flex-wrap arcm-gap-5 arcm-mt-8 arcm-mb-6'>
          <Tooltip
            title={
              customMySQLConnection && !modifyConnection
                ? `Already connected with ${
                    connectionType === 'current'
                      ? 'current database connection'
                      : 'external connection'
                  }. Click the Modify Connection button to apply changes.`
                : ''
            }
            color='#fff'
          >
            <label
              className={`arcm-flex arcm-items-start ${
                customMySQLConnection && !modifyConnection
                  ? 'arcm-cursor-not-allowed'
                  : 'arcm-cursor-pointer'
              } arcm-group`}
              onClick={(e) => {
                if (!customMySQLConnection || modifyConnection) {
                  handleConnectionTypeSwitch('current')
                }
              }}
              role='radio'
              aria-checked={connectionType === 'current'}
              aria-label='Use current database connection'
            >
              <input
                type='radio'
                name='connection_type'
                value='current'
                checked={connectionType === 'current'}
                onChange={() => handleConnectionTypeSwitch('current')}
                disabled={customMySQLConnection && !modifyConnection}
                className='arcm-sr-only'
              />
              <span
                className={`arcm-flex arcm-items-start arcm-px-4 arcm-py-4 arcm-rounded-lg arcm-border-2 arcm-transition-all arcm-min-w-[320px] arcm-max-w-[400px] ${
                  connectionType === 'current'
                    ? 'arcm-border-[#3858e9] arcm-bg-[#f0f4ff]'
                    : 'arcm-border-gray-300 arcm-bg-white'
                } ${
                  customMySQLConnection && !modifyConnection
                    ? 'arcm-opacity-50 arcm-cursor-not-allowed'
                    : ''
                }`}
              >
                <span
                  className={`arcm-w-5 arcm-h-5 arcm-rounded-full arcm-border-2 arcm-flex arcm-items-center arcm-justify-center arcm-mr-3 arcm-mt-0.5 arcm-flex-shrink-0 ${
                    connectionType === 'current'
                      ? 'arcm-border-[#3858e9]'
                      : 'arcm-border-gray-300'
                  }`}
                >
                  {connectionType === 'current' && (
                    <span className='arcm-w-3 arcm-h-3 arcm-rounded-full arcm-bg-[#3858e9]'></span>
                  )}
                </span>
                <div className='arcm-flex arcm-flex-col arcm-gap-2'>
                  <span className={`arcm-text-sm arcm-font-semibold ${
                    connectionType === 'current'
                      ? 'arcm-text-gray-900'
                      : 'arcm-text-gray-700'
                  }`}>
                    {t('use_current_database_connection')}
                  </span>
                  <span className={`arcm-text-xs arcm-leading-relaxed ${
                    connectionType === 'current'
                      ? 'arcm-text-gray-600'
                      : 'arcm-text-gray-500'
                  }`}>
                    {t('archive_to_separate_database')}
                  </span>
                </div>
              </span>
            </label>
          </Tooltip>

          <Tooltip
            title={
              customMySQLConnection && !modifyConnection
                ? `Already connected with ${
                    connectionType === 'current'
                      ? 'current database connection'
                      : 'external connection'
                  }. Click the Modify Connection button to apply changes.`
                : ''
            }
            color='#fff'
          >
            <label
              className={`arcm-flex arcm-items-start ${
                customMySQLConnection && !modifyConnection
                  ? 'arcm-cursor-not-allowed'
                  : 'arcm-cursor-pointer'
              } arcm-group`}
              onClick={(e) => {
                if (!customMySQLConnection || modifyConnection) {
                  handleConnectionTypeSwitch('external')
                }
              }}
              role='radio'
              aria-checked={connectionType === 'external'}
              aria-label='Connect to external MySQL database'
            >
              <input
                type='radio'
                name='connection_type'
                value='external'
                checked={connectionType === 'external'}
                onChange={() => handleConnectionTypeSwitch('external')}
                disabled={customMySQLConnection && !modifyConnection}
                className='arcm-sr-only'
              />
              <span
                className={`arcm-flex arcm-items-start arcm-px-4 arcm-py-4 arcm-rounded-lg arcm-border-2 arcm-transition-all arcm-min-w-[320px] arcm-max-w-[400px] ${
                  connectionType === 'external'
                    ? 'arcm-border-[#3858e9] arcm-bg-[#f0f4ff]'
                    : 'arcm-border-gray-300 arcm-bg-white'
                } ${
                  customMySQLConnection && !modifyConnection
                    ? 'arcm-opacity-50 arcm-cursor-not-allowed'
                    : ''
                }`}
              >
                <span
                  className={`arcm-w-5 arcm-h-5 arcm-rounded-full arcm-border-2 arcm-flex arcm-items-center arcm-justify-center arcm-mr-3 arcm-mt-0.5 arcm-flex-shrink-0 ${
                    connectionType === 'external'
                      ? 'arcm-border-[#3858e9]'
                      : 'arcm-border-gray-300'
                  }`}
                >
                  {connectionType === 'external' && (
                    <span className='arcm-w-3 arcm-h-3 arcm-rounded-full arcm-bg-[#3858e9]'></span>
                  )}
                </span>
                <div className='arcm-flex arcm-flex-col arcm-gap-2'>
                  <span className={`arcm-text-sm arcm-font-semibold ${
                    connectionType === 'external'
                      ? 'arcm-text-gray-900'
                      : 'arcm-text-gray-700'
                  }`}>
                    {t('connect_to_external_mysql')}
                  </span>
                  <span className={`arcm-text-xs arcm-leading-relaxed ${
                    connectionType === 'external'
                      ? 'arcm-text-gray-600'
                      : 'arcm-text-gray-500'
                  }`}>
                    {t('archive_to_remote_mysql')}
                  </span>
                </div>
              </span>
            </label>
          </Tooltip>
        </div>

        <div className='arcm-flex arcm-flex-col lg:arcm-flex-row arcm-gap-8'>
          <div className='custom-mysql-configure__form arcm-max-w-[671px] arcm-mt-6 arcm-w-[50%] arcm-mr-[126px]'>
            {/* Host Field - Only shown for external connection */}
            {connectionType === 'external' && (
            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              color='#fff'
              placement='right'
            >
              <div className='input-field arcm-mb-4 arcm-relative'>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <label
                  htmlFor='mysql_host'
                  className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
                >
                  <span className='arcm-mr-1'>{t('host')}</span>
                  <Tooltip
                    className='arcm-text-sm'
                    placement='right'
                    title={t('mysql_host_tooltip')}
                    color='#fff'
                  >
                    {arcmIcons.info}
                  </Tooltip>
                </label>
                <input
                  disabled={customMySQLConnection && !modifyConnection}
                  type='text'
                  value={customMySQLCredential.endpoint}
                  onChange={e =>
                    setCustomMySQLCredential({
                      ...customMySQLCredential,
                      endpoint: e.target.value
                    })
                  }
                  id='mysql_host'
                  placeholder={t('host_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>
            </Tooltip>
            )}

            {/* Port Field - Only shown for external connection */}
            {connectionType === 'external' && (
            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              color='#fff'
              placement='right'
            >
              <div className='input-field arcm-mb-4 arcm-relative'>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <label
                  htmlFor='mysql_port'
                  className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
                >
                  <span className='arcm-mr-1'>Port</span>
                  <Tooltip
                    className='arcm-text-sm'
                    placement='right'
                    title='MySQL port (default: 3306)'
                    color='#fff'
                  >
                    {arcmIcons.info}
                  </Tooltip>
                </label>
                <input
                  disabled={customMySQLConnection && !modifyConnection}
                  type='number'
                  value={customMySQLCredential.port}
                  onChange={e =>
                    setCustomMySQLCredential({
                      ...customMySQLCredential,
                      port: e.target.value
                    })
                  }
                  id='mysql_port'
                  placeholder='3306'
                  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>
            </Tooltip>
            )}

            {/* Username Field */}
            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              color='#fff'
              placement='right'
            >
              <div className='input-field arcm-mb-4 arcm-relative'>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <label
                  htmlFor='mysql_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={customMySQLConnection && !modifyConnection}
                  type='text'
                  value={customMySQLCredential.username}
                  onChange={e =>
                    setCustomMySQLCredential({
                      ...customMySQLCredential,
                      username: e.target.value
                    })
                  }
                  id='mysql_user'
                  placeholder={t('database_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>
            </Tooltip>

            {/* Password Field */}
            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              color='#fff'
              placement='right'
            >
              <div className='input-field arcm-mb-4 arcm-relative'>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <label
                  htmlFor='mysql_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={customMySQLConnection && !modifyConnection}
                  type='password'
                  value={customMySQLCredential.password}
                  onChange={e =>
                    setCustomMySQLCredential({
                      ...customMySQLCredential,
                      password: e.target.value
                    })
                  }
                  id='mysql_password'
                  placeholder={t('database_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>
            </Tooltip>

            {/* Database Field */}
            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              color='#fff'
              placement='right'
            >
              <div className='input-field arcm-mb-4 arcm-relative'>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <label
                  htmlFor='mysql_database'
                  className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-2'
                >
                  <span className='arcm-mr-1'>{t('database_name')}</span>
                  <Tooltip
                    className='arcm-text-sm'
                    placement='top'
                    title={t('database_name_create_tooltip')}
                    color='#fff'
                  >
                    {arcmIcons.info}
                  </Tooltip>
                </label>
                <input
                  disabled={customMySQLConnection && !modifyConnection}
                  type='text'
                  value={customMySQLCredential.database}
                  onChange={e =>
                    setCustomMySQLCredential({
                      ...customMySQLCredential,
                      database: e.target.value
                    })
                  }
                  id='mysql_database'
                  placeholder='woocommerce_archive'
                  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>
            </Tooltip>

            <Tooltip
              title={
                customMySQLConnection && !modifyConnection
                  ? `Already connected with ${
                      connectionType === 'current'
                        ? 'current database connection'
                        : 'external connection'
                    }. Click the Modify Connection button to apply changes.`
                  : ''
              }
              placement='left'
              color='#fff'
            > 
              <div className={`arcm-inline-flex arcm-gap-3 arcm-relative ${
                customMySQLConnection && !modifyConnection
                  ? 'arcm-cursor-not-allowed'
                  : 'arcm-cursor-pointer'
              }`}>
                {/* Disabled Overlay */}
                {customMySQLConnection && !modifyConnection && (
                  <div className='arcm-absolute arcm-inset-0 arcm-bg-white/50 arcm-z-10 arcm-rounded-lg'></div>
                )}
                <button
                  onClick={handleSetupConnection}
                  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')}
                  </span>
                </button>
              </div>
            </Tooltip>
          </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'>
                {connectionTitle}
              </h5>
              <p className='arcm-text-center arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-6'>
                {connectionDesc}
              </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'>
              {customMySQLConnection ? (
                <>
                  <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'>
                    {connectionTitle}
                  </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('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('couldnt_connect_database')}
                  </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'>
                    {t('connection_error_message')}{' '}
                    <span className='arcm-block arcm-mt-2'>
                      {t('need_help')}{' '}
                      <a
                        href='https://wppool.dev/docs/how-to-configure-a-custom-mysql-database-for-archivemaster/'
                        target='_blank'
                        rel='noopener noreferrer'
                        className='arcm-text-[#3858e9] arcm-font-medium hover:arcm-underline'
                      >
                        {t('learn_how_to_fix')}
                      </a>
                    </span>
                  </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>

      {/* Connection Type Switch Confirmation Modal */}
      <Modal openModal={connectionTypeModal.open} toggleModal={closeConnectionTypeModal}>
        {{
          header: (
            <h5 className='arcm-text-gray-900 arcm-text-lg arcm-font-semibold arcm-leading-7'>
              {t('switch_archive_storage_title')}
            </h5>
          ),
          body: (
            <div className='arcm-mb-6 arcm-mt-3'>
              <div className='arcm-text-gray-600 arcm-text-sm arcm-leading-6 arcm-mb-6'>
                {t('switch_archive_storage_message')}
                <span className='arcm-block arcm-mt-3'>
                  {' '}
                  <a
                    href='https://wppool.dev/docs/considerations-impact-on-archived-data-when-archive-storage-is-switched/'
                    target='_blank'
                    rel='noopener noreferrer'
                    className='arcm-text-[#3858e9] arcm-font-medium hover:arcm-underline'
                  >
                    {t('read_more')}
                  </a>
                </span>
              </div>
              <div className='arcm-flex arcm-gap-3'>
                <button
                  onClick={confirmConnectionTypeSwitch}
                  className='arcm-text-white arcm-text-sm arcm-font-medium arcm-px-8 arcm-py-3 arcm-bg-[#4F46E5] arcm-rounded-lg arcm-transition-all hover:arcm-bg-[#4338CA] arcm-flex-1'
                >
                  {t('confirm')}
                </button>
                <button
                  onClick={closeConnectionTypeModal}
                  className='arcm-text-gray-700 arcm-text-sm arcm-font-medium arcm-px-8 arcm-py-3 arcm-bg-gray-100 arcm-rounded-lg arcm-transition-all hover:arcm-bg-gray-200 arcm-flex-1'
                >
                  {t('cancel')}
                </button>
              </div>
            </div>
          )
        }}
      </Modal>
    </div>
  )
}

export default CustomMySQLConfigure
