import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { t } from '@/i18n';
import { updateSettings } from '../../services/user';
import { authStore } from '../../store/auth';
// Taro mini-program component

/**
 * P2. 设置页面
 *
 * 通知开关、语言/货币选择、关于、退出登录
 */

const languages = [
  { value: 'zh-CN', label: '简体中文' },
  { value: 'en-US', label: 'English' },
  { value: 'ja-JP', label: '日本語' },
];

const currencies = [
  { code: 'CNY', symbol: '¥', label: 'CNY (¥)' },
  { code: 'USD', symbol: '$', label: 'USD ($)' },
  { code: 'EUR', symbol: '€', label: 'EUR (€)' },
  { code: 'GBP', symbol: '£', label: 'GBP (£)' },
  { code: 'JPY', symbol: '¥', label: 'JPY (¥)' },
  { code: 'HKD', symbol: 'HK$', label: 'HKD (HK$)' },
];

const SettingsPage: React.FC = () => {
  const [notifyTrade, setNotifyTrade] = useState(true);
  const [notifyExpiry, setNotifyExpiry] = useState(true);
  const [notifyMarketing, setNotifyMarketing] = useState(false);
  const [showLangPicker, setShowLangPicker] = useState(false);
  const [showCurrencyPicker, setShowCurrencyPicker] = useState(false);
  const [selectedLang, setSelectedLang] = useState('zh-CN');
  const [selectedCurrency, setSelectedCurrency] = useState('USD');

  const currentLangLabel = languages.find((l) => l.value === selectedLang)?.label || '简体中文';
  const currentCurrencyLabel = currencies.find((c) => c.code === selectedCurrency)?.label || 'USD ($)';

  const handleClearCache = () => {
    Taro.showToast({ title: t('settings_cache_cleared'), icon: 'success' });
  };

  const handleToggleNotification = (key: 'trade' | 'expiry' | 'marketing', value: boolean) => {
    const setters = { trade: setNotifyTrade, expiry: setNotifyExpiry, marketing: setNotifyMarketing };
    setters[key](value);
    updateSettings({
      notificationPrefs: {
        trade: key === 'trade' ? value : notifyTrade,
        expiry: key === 'expiry' ? value : notifyExpiry,
        marketing: key === 'marketing' ? value : notifyMarketing,
      },
    }).catch(() => {
      // Revert on failure
      setters[key](!value);
    });
  };

  const handleLanguageChange = (langValue: string) => {
    setSelectedLang(langValue);
    setShowLangPicker(false);
    updateSettings({ language: langValue }).catch(() => {});
  };

  const handleCurrencyChange = (currencyCode: string) => {
    setSelectedCurrency(currencyCode);
    setShowCurrencyPicker(false);
    updateSettings({ currency: currencyCode }).catch(() => {});
  };

  const handleLogout = () => {
    Taro.showModal({
      title: t('settings_logout'),
      content: t('settings_logout') + '?',
      confirmText: t('confirm'),
      cancelText: t('cancel'),
      success: (res) => {
        if (res.confirm) {
          authStore.logout();
        }
      },
    });
  };

  const toggleItems = [
    { label: t('settings_trade_notify'), value: notifyTrade, key: 'trade' as const },
    { label: t('settings_expiry_remind'), value: notifyExpiry, key: 'expiry' as const },
    { label: t('settings_marketing_push'), value: notifyMarketing, key: 'marketing' as const },
  ];

  return (
    <view className="settings-page">
      {/* Section: Notifications */}
      <view className="settings-section">
        <text className="settings-section-title">{t('settings_notifications')}</text>
        {toggleItems.map((item, i) => (
          <view key={i} className="settings-row">
            <text className="settings-row-label">{item.label}</text>
            <view
              className={`toggle-track ${item.value ? 'toggle-track-on' : ''}`}
              onClick={() => handleToggleNotification(item.key, !item.value)}
            >
              <view className={`toggle-thumb ${item.value ? 'toggle-thumb-on' : ''}`} />
            </view>
          </view>
        ))}
      </view>

      {/* Section: General */}
      <view className="settings-section">
        <text className="settings-section-title">{t('settings_general')}</text>

        <view className="settings-row" onClick={() => setShowLangPicker(true)}>
          <text className="settings-row-label">{t('profile_language')}</text>
          <view className="settings-row-right">
            <text className="settings-row-value">{currentLangLabel}</text>
            <text className="settings-row-arrow">›</text>
          </view>
        </view>

        <view className="settings-row" onClick={() => setShowCurrencyPicker(true)}>
          <text className="settings-row-label">{t('profile_currency')}</text>
          <view className="settings-row-right">
            <text className="settings-row-value">{currentCurrencyLabel}</text>
            <text className="settings-row-arrow">›</text>
          </view>
        </view>

        <view className="settings-row" onClick={handleClearCache}>
          <text className="settings-row-label">{t('settings_clear_cache')}</text>
          <text className="settings-row-arrow">›</text>
        </view>
      </view>

      {/* Section: About */}
      <view className="settings-section">
        <text className="settings-section-title">{t('settings_about')}</text>

        <view className="settings-row">
          <text className="settings-row-label">{t('settings_version')}</text>
          <text className="settings-row-value">v1.0.0</text>
        </view>

        <view className="settings-row">
          <text className="settings-row-label">{t('login_user_agreement')}</text>
          <text className="settings-row-arrow">›</text>
        </view>

        <view className="settings-row">
          <text className="settings-row-label">{t('login_privacy_policy')}</text>
          <text className="settings-row-arrow">›</text>
        </view>

        <view className="settings-row">
          <text className="settings-row-label">{t('settings_help_center')}</text>
          <text className="settings-row-arrow">›</text>
        </view>
      </view>

      {/* Logout Button */}
      <view className="settings-logout-btn" onClick={handleLogout}>
        <text className="settings-logout-text">{t('settings_logout')}</text>
      </view>

      {/* Language Picker Modal */}
      {showLangPicker && (
        <view className="picker-overlay" onClick={() => setShowLangPicker(false)}>
          <view className="picker-modal" onClick={(e) => e.stopPropagation()}>
            <view className="picker-header">
              <text className="picker-title">{t('settings_select_language')}</text>
              <text className="picker-close" onClick={() => setShowLangPicker(false)}>✕</text>
            </view>
            {languages.map((lang) => (
              <view
                key={lang.value}
                className="picker-option"
                onClick={() => handleLanguageChange(lang.value)}
              >
                <text className="picker-option-label">{lang.label}</text>
                {selectedLang === lang.value && <text className="picker-check">✓</text>}
              </view>
            ))}
          </view>
        </view>
      )}

      {/* Currency Picker Modal */}
      {showCurrencyPicker && (
        <view className="picker-overlay" onClick={() => setShowCurrencyPicker(false)}>
          <view className="picker-modal" onClick={(e) => e.stopPropagation()}>
            <view className="picker-header">
              <text className="picker-title">{t('settings_select_currency')}</text>
              <text className="picker-close" onClick={() => setShowCurrencyPicker(false)}>✕</text>
            </view>
            <text className="picker-note">{t('settings_currency_note')}</text>
            {currencies.map((cur) => (
              <view
                key={cur.code}
                className="picker-option"
                onClick={() => handleCurrencyChange(cur.code)}
              >
                <text className="picker-option-label">{cur.label}</text>
                {selectedCurrency === cur.code && <text className="picker-check">✓</text>}
              </view>
            ))}
          </view>
        </view>
      )}
    </view>
  );
};

export default SettingsPage;

/*
CSS:

.settings-page { background: #F8F9FC; min-height: 100vh; padding-bottom: 60rpx; }

.settings-section {
  background: white; margin-top: 16rpx;
}
.settings-section-title {
  display: block; font-size: 24rpx; color: #A0A8BE;
  padding: 24rpx 32rpx 8rpx; font-weight: 500; text-transform: uppercase;
}

.settings-row {
  display: flex; align-items: center; justify-content: space-between;
  padding: 28rpx 32rpx; border-bottom: 1rpx solid #F1F3F8;
}
.settings-row-label { font-size: 28rpx; color: #141723; }
.settings-row-right { display: flex; align-items: center; }
.settings-row-value { font-size: 26rpx; color: #A0A8BE; margin-right: 8rpx; }
.settings-row-arrow { font-size: 32rpx; color: #CDD2DE; }

.toggle-track {
  width: 88rpx; height: 48rpx; border-radius: 999rpx;
  background: #E4E7F0; position: relative; transition: background 0.2s;
}
.toggle-track-on { background: #6C5CE7; }
.toggle-thumb {
  width: 40rpx; height: 40rpx; border-radius: 50%;
  background: white; position: absolute; top: 4rpx; left: 4rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.15); transition: left 0.2s;
}
.toggle-thumb-on { left: 44rpx; }

.settings-logout-btn {
  margin: 48rpx 32rpx 0; padding: 24rpx 0;
  border: 2rpx solid #E74C3C; border-radius: 16rpx;
  display: flex; align-items: center; justify-content: center;
}
.settings-logout-text { font-size: 30rpx; color: #E74C3C; font-weight: 500; }

.picker-overlay {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5); z-index: 999;
  display: flex; align-items: flex-end; justify-content: center;
}
.picker-modal {
  width: 100%; background: white; border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx 32rpx calc(32rpx + env(safe-area-inset-bottom));
}
.picker-header {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 16rpx;
}
.picker-title { font-size: 32rpx; font-weight: 600; color: #141723; }
.picker-close { font-size: 32rpx; color: #A0A8BE; padding: 8rpx; }
.picker-note { font-size: 22rpx; color: #A0A8BE; margin-bottom: 16rpx; }

.picker-option {
  display: flex; align-items: center; justify-content: space-between;
  padding: 28rpx 16rpx; border-bottom: 1rpx solid #F1F3F8;
}
.picker-option-label { font-size: 28rpx; color: #141723; }
.picker-check { font-size: 32rpx; color: #6C5CE7; font-weight: 700; }
*/
