import { Text, View } from '@tarojs/components'
import Icon, { type IconName } from '@/components/ui/Icon'
import Switch from '@/components/ui/Switch'
import type { UserProfile } from '@/types/domain'
import './index.scss'

interface PreferenceListProps {
  preferences: UserProfile['preferences']
  onChange: (key: keyof UserProfile['preferences'], value: boolean) => void
  onAction?: (key: 'help' | 'about') => void
  onLogout?: () => void
}

const rows: Array<{
  key: keyof UserProfile['preferences'] | 'help' | 'about'
  icon: IconName
  label: string
  value?: string
}> = [
  { key: 'nearbyVisible', icon: 'heart', label: '附近可见' },
  { key: 'notifications', icon: 'bell', label: '消息通知' },
  { key: 'help', icon: 'info', label: '帮助与反馈', value: '›' },
  { key: 'about', icon: 'settings', label: '设置', value: '›' }
]

function isPreferenceKey(key: (typeof rows)[number]['key']): key is keyof UserProfile['preferences'] {
  return key === 'notifications' || key === 'nearbyVisible'
}

export function PreferenceList({ preferences, onChange, onAction, onLogout }: PreferenceListProps) {
  const prefs = preferences || { notifications: true, nearbyVisible: true }
  return (
    <View className='preference-list'>
      <Text className='preference-list__title'>偏好设置</Text>
      <View className='preference-list__panel'>
        {rows.map(row => {
          const actionable = !isPreferenceKey(row.key)
          return (
            <View
              key={row.key}
              className='preference-list__row'
              onClick={actionable ? () => onAction?.(row.key as 'help' | 'about') : undefined}
            >
              <View className={`preference-list__icon preference-list__icon--${row.key}`}>
                <Icon name={row.icon} size={16} />
              </View>
              <Text className='preference-list__label'>{row.label}</Text>
              {isPreferenceKey(row.key) ? (
                <Switch
                  checked={prefs[row.key]}
                  onChange={value => onChange(row.key as keyof UserProfile['preferences'], value)}
                />
              ) : (
                <Text className='preference-list__value'>{row.value}</Text>
              )}
            </View>
          )
        })}
      </View>
      {onLogout ? (
        <View className='preference-list__logout' onClick={onLogout}>
          退出登录
        </View>
      ) : null}
    </View>
  )
}

export default PreferenceList
