import React, { useState, useEffect, FC } from 'react'
import { Button, Notice, Card, CardBody } from '@wordpress/components'
import { useI18n } from '@wordpress/react-i18n'
import apiFetch from '@wordpress/api-fetch'

interface RemoteLogResponse {
  remoteLoggingEnabled: boolean
}

interface ToggleRemoteLogProps {
  onToggleComplete?: (newValue: boolean) => void
}

const ToggleRemoteLog: FC<ToggleRemoteLogProps> = ({ onToggleComplete }) => {
  const [remoteLoggingEnabled, setRemoteLoggingEnabled] =
    useState<boolean>(false)
  const [isSaving, setIsSaving] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)

  const { __ } = useI18n()

  const handleToggleChange = async (newValue: boolean) => {
    setIsSaving(true)
    setError(null)
    try {
      await apiFetch({
        path: '/posten-bring-checkout/remote-log-toggle',
        method: 'POST',
        data: { remoteLoggingEnabled: newValue },
      })
      setRemoteLoggingEnabled(newValue)
      if (onToggleComplete) {
        onToggleComplete(newValue)
      }
    } catch (e: any) {
      setError(
        __(
          'An error occurred while updating the remote log setting. Please try again.',
          'posten-bring-checkout'
        )
      )
    } finally {
      setIsSaving(false)
    }
  }

  useEffect(() => {
    const fetchInitialValue = async () => {
      try {
        const response: RemoteLogResponse = await apiFetch({
          path: '/posten-bring-checkout/remote-log-toggle',
        })
        setRemoteLoggingEnabled(response.remoteLoggingEnabled ?? true) // Default to "on" if undefined
      } catch (e) {
        setError(
          __(
            'Could not fetch the current remote log setting.',
            'posten-bring-checkout'
          )
        )
      }
    }
    fetchInitialValue()
  })

  const turnOffText = __('Turn Off', 'posten-bring-checkout')
  const turnOnText = __('Turn On', 'posten-bring-checkout')
  const enabledText = __('Enabled', 'posten-bring-checkout')
  const disabledText = __('Disabled', 'posten-bring-checkout')
  return (
    <Card className="setting-card">
      <div className="setting-container">
        <div>
          <h4 style={{ margin: 0 }}>
            {__('Send us error logs', 'posten-bring-checkout')}{' '}
            <span
              className={`setting-toggle ${
                remoteLoggingEnabled ? 'active' : ''
              }`}
            >
              {remoteLoggingEnabled ? enabledText : disabledText}
            </span>
          </h4>
        </div>
        <Button
          variant="secondary"
          isBusy={isSaving}
          onClick={() => handleToggleChange(!remoteLoggingEnabled)}
        >
          {remoteLoggingEnabled ? turnOffText : turnOnText}
        </Button>
      </div>
      <CardBody>
        <p>
          {__(
            'Enable or disable sending logs to Posten Bring for troubleshooting.',
            'posten-bring-checkout'
          )}
        </p>
        <p>
          {__(
            'We recommend keeping this option enabled to help Posten Bring identify and resolve issues with your webshop integration. Logs are sent only when errors occur, and no personal information is ever transmitted.',
            'posten-bring-checkout'
          )}
        </p>
        {error && (
          <Notice status="error" isDismissible={false}>
            {error}
          </Notice>
        )}
      </CardBody>
    </Card>
  )
}

export default ToggleRemoteLog
