import React from 'react'
import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'

definePageConfig({
  navigationBarTitleText: '设置',
})

const SettingPage: React.FC = () => {
  const { isLoggedIn, logoutUser } = useUser()

  const handleClearCache = () => {
    Taro.showModal({
      title: '提示',
      content: '确定要清除缓存吗？',
      success: (res) => {
        if (res.confirm) {
          Taro.clearStorageSync()
          Taro.showToast({ title: '缓存已清除', icon: 'success' })
        }
      },
    })
  }

  const handleLogout = () => {
    if (!isLoggedIn) return
    Taro.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          logoutUser()
          Taro.reLaunch({ url: '/pages/index/index' })
        }
      },
    })
  }

  const menuItems = [
    { label: '清除缓存', action: handleClearCache },
    { label: '关于我们', action: () => Taro.showToast({ title: 'v1.0.0', icon: 'none' }) },
    { label: '用户协议', action: () => Taro.navigateTo({ url: '/passport/agreement' }) },
    { label: '隐私政策', action: () => Taro.navigateTo({ url: '/passport/agreement' }) },
  ]

  return (
    <View className='min-h-screen bg-gray-50 p-3'>
      <View className='bg-white rounded-xl overflow-hidden'>
        {menuItems.map((item, idx) => (
          <View
            key={item.label}
            className={`flex items-center justify-between px-4 py-3 ${
              idx < menuItems.length - 1 ? 'border-b border-gray-50' : ''
            }`}
            onClick={item.action}
          >
            <Text className='text-sm text-gray-700'>{item.label}</Text>
            <Text className='text-gray-300 text-sm'>{'>'}</Text>
          </View>
        ))}
      </View>
      {isLoggedIn && (
        <View className='mt-6 mx-4'>
          <View
            className='py-2 rounded-full text-center bg-white'
            onClick={handleLogout}
          >
            <Text className='text-red-500 text-sm font-medium'>退出登录</Text>
          </View>
        </View>
      )}
    </View>
  )
}

export default SettingPage
