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 PortfolioSettingsPage() {
  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: 'Portfolios', href: '/portfolios' },
          { label: 'Settings' },
        ]}
      />

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