'use client'

/**
 * Settings Page - 系統設定
 * =========================
 * 純前端設定：語言、外觀、通知、API 端點
 * 設定值持久化至 localStorage
 *
 * @updated 2026-04-01 ogt - 從佔位符升級為完整頁面
 * @updated 2026-04-02 Claude Code - i18n 合規修復 (零硬編碼)
 */

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'
import { usePathname } from 'next/navigation'
import { cn } from '@/lib/utils'
import {
  Settings, Globe, Bell, Monitor,
  CheckCircle2, ChevronRight,
} from 'lucide-react'

// =============================================================================
// Types
// =============================================================================

interface SettingSection {
  id: string
  icon: typeof Settings
  titleKey: string
  descKey: string
}

// =============================================================================
// Setting Row
// =============================================================================

function SettingRow({
  label, description, children,
}: { label: string; description?: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between py-4 border-b border-nothing-gray-100 last:border-0">
      <div>
        <p className="text-sm font-medium text-nothing-black">{label}</p>
        {description && <p className="text-xs font-body text-nothing-gray-400 mt-0.5">{description}</p>}
      </div>
      <div className="flex-shrink-0 ml-6">{children}</div>
    </div>
  )
}

function Toggle({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }) {
  return (
    <button
      onClick={() => onChange(!value)}
      className={cn(
        'relative w-10 h-5 rounded-full transition-colors',
        value ? 'bg-claw-blue' : 'bg-nothing-gray-300'
      )}
    >
      <span className={cn(
        'absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform',
        value ? 'translate-x-5' : 'translate-x-0.5'
      )} />
    </button>
  )
}

// =============================================================================
// Page
// =============================================================================

export default function SettingsPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('settings')
  const tNav = useTranslations('nav')
  const pathname = usePathname()
  const [activeSection, setActiveSection] = useState('appearance')
  const [saved, setSaved] = useState(false)

  const SECTIONS: SettingSection[] = [
    { id: 'appearance', icon: Monitor,  titleKey: 'appearance', descKey: 'appearanceDesc' },
    { id: 'language',   icon: Globe,    titleKey: 'language',   descKey: 'languageDesc' },
    { id: 'notify',     icon: Bell,     titleKey: 'notify',     descKey: 'notifyDesc' },
    { id: 'system',     icon: Settings, titleKey: 'system',     descKey: 'systemDesc' },
  ]

  // Settings state — loaded from / persisted to localStorage
  const [notifyBrowser, setNotifyBrowser] = useState(false)
  const [notifyP0Only, setNotifyP0Only]   = useState(false)
  const [compactMode, setCompactMode]     = useState(false)

  useEffect(() => {
    setNotifyBrowser(localStorage.getItem('setting_notify_browser') === 'true')
    setNotifyP0Only(localStorage.getItem('setting_notify_p0only') === 'true')
    setCompactMode(localStorage.getItem('setting_compact_mode') === 'true')
  }, [])

  const saveSettings = () => {
    localStorage.setItem('setting_notify_browser', String(notifyBrowser))
    localStorage.setItem('setting_notify_p0only', String(notifyP0Only))
    localStorage.setItem('setting_compact_mode', String(compactMode))
    setSaved(true)
    setTimeout(() => setSaved(false), 2000)
  }

  const switchLocale = (locale: string) => {
    const newPath = pathname.replace(`/${params.locale}`, `/${locale}`)
    window.location.href = newPath
  }

  return (
    <AppLayout locale={params.locale}>
      <div className="flex items-center gap-2 mb-6">
        <Settings className="w-6 h-6 text-nothing-black" />
        <h2 className="font-heading text-2xl font-bold text-nothing-black">{t('title')}</h2>
      </div>

      <div className="flex gap-6">
        {/* Sidebar nav */}
        <div className="w-48 flex-shrink-0">
          <nav className="space-y-1">
            {SECTIONS.map(section => (
              <button
                key={section.id}
                onClick={() => setActiveSection(section.id)}
                className={cn(
                  'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all',
                  activeSection === section.id
                    ? 'bg-nothing-black text-white'
                    : 'text-nothing-gray-600 hover:bg-nothing-gray-100'
                )}
              >
                <section.icon className="w-4 h-4 flex-shrink-0" />
                <span className="text-sm font-body">{t(section.titleKey)}</span>
                {activeSection !== section.id && <ChevronRight className="w-3 h-3 ml-auto text-nothing-gray-400" />}
              </button>
            ))}
          </nav>
        </div>

        {/* Content */}
        <div className="flex-1 bg-white rounded-xl border border-nothing-gray-200 p-6">

          {/* Appearance */}
          {activeSection === 'appearance' && (
            <div>
              <h3 className="font-body text-sm font-bold text-nothing-black mb-4 uppercase tracking-wider">{t('appearanceSettings')}</h3>
              <SettingRow label={t('compactMode')} description={t('compactModeDesc')}>
                <Toggle value={compactMode} onChange={setCompactMode} />
              </SettingRow>
              <SettingRow label={t('designSystem')} description={t('designSystemValue')}>
                <span className="text-xs font-body text-nothing-gray-400 bg-nothing-gray-100 px-2 py-1 rounded">v7.0</span>
              </SettingRow>
              <SettingRow label={t('themeColor')} description={t('themeColorValue')}>
                <div className="flex gap-1.5">
                  <div className="w-5 h-5 rounded-full bg-[#4A90D9] border-2 border-white shadow" />
                  <div className="w-5 h-5 rounded-full bg-[#d97757] border-2 border-white shadow" />
                </div>
              </SettingRow>
            </div>
          )}

          {/* Language */}
          {activeSection === 'language' && (
            <div>
              <h3 className="font-body text-sm font-bold text-nothing-black mb-4 uppercase tracking-wider">{t('languageSettings')}</h3>
              {[
                { code: 'zh-TW', labelKey: 'zhTW', subKey: 'zhTWSub' },
                { code: 'en',    labelKey: 'en',   subKey: 'enSub' },
              ].map(lang => (
                <div
                  key={lang.code}
                  onClick={() => switchLocale(lang.code)}
                  className={cn(
                    'flex items-center justify-between p-4 rounded-lg border cursor-pointer transition-all mb-2',
                    params.locale === lang.code
                      ? 'border-claw-blue bg-claw-blue/5'
                      : 'border-nothing-gray-200 hover:border-nothing-gray-300'
                  )}
                >
                  <div>
                    <p className="text-sm font-medium text-nothing-black">{t(lang.labelKey)}</p>
                    <p className="text-xs font-body text-nothing-gray-400">{t(lang.subKey)}</p>
                  </div>
                  {params.locale === lang.code && <CheckCircle2 className="w-5 h-5 text-claw-blue" />}
                </div>
              ))}
            </div>
          )}

          {/* Notifications */}
          {activeSection === 'notify' && (
            <div>
              <h3 className="font-body text-sm font-bold text-nothing-black mb-4 uppercase tracking-wider">{t('notifySettings')}</h3>
              <SettingRow label={t('browserNotify')} description={t('browserNotifyDesc')}>
                <Toggle value={notifyBrowser} onChange={setNotifyBrowser} />
              </SettingRow>
              <SettingRow label={t('p0Only')} description={t('p0OnlyDesc')}>
                <Toggle value={notifyP0Only} onChange={setNotifyP0Only} />
              </SettingRow>
              <SettingRow label={t('telegramNotify')} description={t('telegramNotifyDesc')}>
                <span className="text-xs font-body text-nothing-gray-400 bg-nothing-gray-100 px-2 py-1 rounded">{t('backendConfig')}</span>
              </SettingRow>
            </div>
          )}

          {/* System */}
          {activeSection === 'system' && (
            <div>
              <h3 className="font-body text-sm font-bold text-nothing-black mb-4 uppercase tracking-wider">{t('systemSettings')}</h3>
              {[
                { labelKey: 'frontendVersion', value: 'v1.0.0' },
                { labelKey: 'apiEndpoint',     value: process.env.NEXT_PUBLIC_API_URL ?? t('notConfigured') },
                { labelKey: 'designSystem',    value: 'Nothing.tech v7.0' },
                { labelKey: 'phase',           value: 'Phase 23 (2026-04-01)' },
              ].map(item => (
                <SettingRow key={item.labelKey} label={t(item.labelKey)}>
                  <span className="text-sm font-body text-nothing-gray-600">{item.value}</span>
                </SettingRow>
              ))}
            </div>
          )}

          {/* Save button (appearance / notify only) */}
          {(activeSection === 'appearance' || activeSection === 'notify') && (
            <div className="mt-6 flex items-center gap-3">
              <button
                onClick={saveSettings}
                className="px-5 py-2.5 rounded-lg bg-nothing-black text-white font-body text-sm font-semibold hover:bg-nothing-black/90 transition-colors"
              >
                {t('save')}
              </button>
              {saved && (
                <span className="flex items-center gap-1.5 text-sm font-body text-status-healthy">
                  <CheckCircle2 className="w-4 h-4" />
                  {t('saved')}
                </span>
              )}
            </div>
          )}
        </div>
      </div>
    </AppLayout>
  )
}
