import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { safeNavigateTo } from '@/utils/navigate';
import { useAuthStore } from '../../../stores/auth';
import { useUIStore } from '../../../stores/ui';
import { invalidateHeadersCache, clearRequestCache } from '@/services/request';
import { useElderClass } from '../../../hooks/useElderClass';
import PageShell from '@/components/ui/PageShell';
import DoctorTabBar from '@/components/ui/DoctorTabBar';
import './index.scss';

export default function Settings() {
  const modeClass = useElderClass();
  const logout = useAuthStore((s) => s.logout);
  const isMedicalStaff = useAuthStore((s) => s.isMedicalStaff);
  const mode = useUIStore((s) => s.mode);
  const toggleMode = useUIStore((s) => s.toggle);

  const handleClearCache = async () => {
    const { confirm } = await Taro.showModal({
      title: '清除缓存',
      content: '确定要清除本地缓存数据吗？不会影响账号信息。',
    });
    if (!confirm) return;

    const preservedKeys = ['access_token', 'refresh_token', 'user_data', 'user_roles', 'tenant_id', 'wechat_openid', 'current_patient', 'current_patient_id'];
    const preserved: Record<string, unknown> = {};
    await Promise.all(
      preservedKeys.map(async (key) => {
        try {
          const val = await Taro.getStorage({ key });
          if (val.data) preserved[key] = val.data;
        } catch { /* key not found */ }
      }),
    );

    await Taro.clearStorage();

    await Promise.all(
      Object.entries(preserved).map(([key, val]) =>
        Taro.setStorage({ key, data: val }),
      ),
    );

    clearRequestCache();
    invalidateHeadersCache();
    Taro.showToast({ title: '缓存已清除', icon: 'success' });
  };

  const handleAbout = () => {
    Taro.showModal({
      title: '关于我们',
      content: 'HMS 健康管理平台 v1.0.0\n为您的健康保驾护航',
      showCancel: false,
    });
  };

  const handlePrivacy = () => {
    safeNavigateTo('/pages/legal/privacy-policy');
  };

  const handleLogout = () => {
    Taro.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
    }).then((res) => {
      if (res.confirm) {
        logout();
      }
    });
  };

  return (
    <PageShell className={modeClass}>
      <Text className='page-title'>设置</Text>

      <View className='settings-group'>
        <View className='settings-item' onClick={toggleMode}>
          <View className='settings-icon'>
            <Text className='settings-icon-text'>老</Text>
          </View>
          <Text className='settings-label'>长辈模式</Text>
          <Text className={`settings-toggle ${mode === 'elder' ? 'settings-toggle--active' : ''}`}>
            {mode === 'elder' ? '已开启' : '未开启'}
          </Text>
          <Text className='settings-arrow'>{'>'}</Text>
        </View>
        <View className='settings-item' onClick={handleClearCache}>
          <View className='settings-icon'>
            <Text className='settings-icon-text'>缓</Text>
          </View>
          <Text className='settings-label'>清除缓存</Text>
          <Text className='settings-arrow'>{'>'}</Text>
        </View>
        <View className='settings-item' onClick={handleAbout}>
          <View className='settings-icon'>
            <Text className='settings-icon-text'>关</Text>
          </View>
          <Text className='settings-label'>关于我们</Text>
          <Text className='settings-arrow'>{'>'}</Text>
        </View>
        <View className='settings-item' onClick={handlePrivacy}>
          <View className='settings-icon'>
            <Text className='settings-icon-text'>隐</Text>
          </View>
          <Text className='settings-label'>隐私政策</Text>
          <Text className='settings-arrow'>{'>'}</Text>
        </View>
      </View>

      <View className='settings-group'>
        <View className='settings-item logout-item' onClick={handleLogout}>
          <Text className='settings-label logout-label'>退出登录</Text>
        </View>
      </View>
      {isMedicalStaff() && <DoctorTabBar active="settings" />}
    </PageShell>
  );
}
