import { useEffect, useState } from 'react'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { PageTitle } from '../components/PageTitle'
import { Switch } from '../components/Switch'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError } from '../lib/api'
import {
  getSettings,
  updateDashboardSettings,
  type DashboardSettings,
} from '../services/settingsService'
import pageStyles from '../components/PageContent.module.css'
import styles from './ProductSettingsPage.module.css'

const DEFAULT_SETTINGS: DashboardSettings = {
  comments: { autoApprove: false },
  expertReviews: { autoApprove: false },
}

export function BlogSettingsPage() {
  const t = useT()
  const { showToast } = useToast()
  const [settings, setSettings] = useState<DashboardSettings>(DEFAULT_SETTINGS)
  const [isLoading, setIsLoading] = useState(true)
  const [savingKey, setSavingKey] = useState<string | null>(null)
  const [error, setError] = useState('')

  useEffect(() => {
    const controller = new AbortController()
    void loadSettings(controller.signal)
    return () => controller.abort()
  }, [])

  async function loadSettings(signal?: AbortSignal) {
    setIsLoading(true)
    setError('')

    try {
      const data = await getSettings(signal)
      setSettings(data.settings.dashboard)
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('productSettings.errorLoad'))
      }
    } finally {
      setIsLoading(false)
    }
  }

  async function handleCommentsAutoApprove(checked: boolean) {
    setSavingKey('comments')
    setError('')

    try {
      const data = await updateDashboardSettings({
        comments: { autoApprove: checked },
      })
      setSettings(data.settings.dashboard)
      showToast(t('productSettings.saved'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('productSettings.errorSave'))
      }
    } finally {
      setSavingKey(null)
    }
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={[
          { label: 'Dashboard', href: '/' },
          { label: 'Blog', href: '/blog' },
          { label: 'Settings' },
        ]}
      />

      <div className={pageStyles.pageHeader}>
        <div>
          <PageTitle en="BLOG SETTINGS">{t('blog.settings.title')}</PageTitle>
          <p className={pageStyles.pageSubtitle}>{t('blog.settings.subtitle')}</p>
        </div>
      </div>

      {error && (
        <div className={styles.alertError} role="alert">
          {error}
        </div>
      )}

      <section className={styles.panel}>
        <h3 className={styles.sectionTitle}>{t('productSettings.moderation')}</h3>

        {isLoading ? (
          <p className={styles.status}>{t('productSettings.loading')}</p>
        ) : (
          <div className={styles.list}>
            <div className={styles.row}>
              <div className={styles.rowText}>
                <label htmlFor="blog-comments-auto-approve" className={styles.rowLabel}>
                  {t('blog.settings.commentsAuto')}
                </label>
                <p className={styles.rowDescription}>{t('blog.settings.commentsAutoDesc')}</p>
              </div>
              <Switch
                id="blog-comments-auto-approve"
                checked={settings.comments.autoApprove}
                disabled={savingKey === 'comments'}
                aria-label={t('blog.settings.commentsAutoAria')}
                onChange={(checked) => void handleCommentsAutoApprove(checked)}
              />
            </div>
          </div>
        )}
      </section>
    </main>
  )
}
