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

const ToggleDarkMode: FC = () => {
  const shopAddressConfigured =
    // @ts-expect-error 2339
    window.shopDetails?.darkMode || false

  const [isSaving, setIsSaving] = useState<boolean>(false)
  const [error, setError] = useState<string>()
  const [darkModeActive, setDarkModeActive] = useState<boolean>(
    shopAddressConfigured
  )

  const { __ } = useI18n()

  const handleToggleChange = async (newValue: boolean) => {
    setIsSaving(true)
    setError(undefined)
    try {
      await apiFetch({
        path: '/posten-bring-checkout/dark-mode',
        method: 'POST',
        data: { darkMode: newValue },
      })
      setDarkModeActive(newValue)
    } catch (e) {
      setError(
        __(
          'An error occurred while updating the dark mode setting. Please try again.',
          'posten-bring-checkout'
        )
      )
    } finally {
      setIsSaving(false)
    }
  }

  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="mbm setting-card">
      <div className="setting-container">
        <div>
          <h4 style={{ margin: 0 }}>
            {__('Dark mode', 'posten-bring-checkout')}{' '}
            <span
              className={`setting-toggle ${darkModeActive ? 'active' : ''}`}
            >
              {darkModeActive ? enabledText : disabledText}
            </span>
          </h4>
        </div>
        <Button
          variant="secondary"
          isBusy={isSaving}
          onClick={() => handleToggleChange(!darkModeActive)}
        >
          {darkModeActive ? turnOffText : turnOnText}
        </Button>
      </div>
      <CardBody>
        <p>
          {__(
            'If your theme has a dark color palette, you can enable dark styling of the Posten Bring Checkout components.',
            'posten-bring-checkout'
          )}
        </p>
        <details>
          <summary>{__('View screenshot', 'posten-bring-checkout')}</summary>
          <img className="dark-sample" src={dark} alt="" />
        </details>
        {error && (
          <Notice status="error" isDismissible={false}>
            {error}
          </Notice>
        )}
      </CardBody>
    </Card>
  )
}

export default ToggleDarkMode
