import { useEffect, useState } from 'react'
import { Breadcrumbs } from '../components/Breadcrumbs'
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 ProductSettingsPage() {
  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)
    }
  }

  async function handleExpertReviewsAutoApprove(checked: boolean) {
    setSavingKey('expertReviews')
    setError('')

    try {
      const data = await updateDashboardSettings({
        expertReviews: { 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: 'Products', href: '/products' },
          { label: 'Settings' },
        ]}
      />

      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('productSettings.title')}</h2>
          <p className={pageStyles.pageSubtitle}>{t('productSettings.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="comments-auto-approve" className={styles.rowLabel}>
                  {t('productSettings.commentsAuto')}
                </label>
                <p className={styles.rowDescription}>{t('productSettings.commentsAutoDesc')}</p>
              </div>
              <Switch
                id="comments-auto-approve"
                checked={settings.comments.autoApprove}
                disabled={savingKey === 'comments'}
                aria-label={t('productSettings.commentsAuto')}
                onChange={(checked) => void handleCommentsAutoApprove(checked)}
              />
            </div>

            <div className={styles.row}>
              <div className={styles.rowText}>
                <label htmlFor="expert-reviews-auto-approve" className={styles.rowLabel}>
                  {t('productSettings.reviewsAuto')}
                </label>
                <p className={styles.rowDescription}>{t('productSettings.reviewsAutoDesc')}</p>
              </div>
              <Switch
                id="expert-reviews-auto-approve"
                checked={settings.expertReviews.autoApprove}
                disabled={savingKey === 'expertReviews'}
                aria-label={t('productSettings.reviewsAuto')}
                onChange={(checked) => void handleExpertReviewsAutoApprove(checked)}
              />
            </div>
          </div>
        )}
      </section>
    </main>
  )
}
