import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { backend, type BackendAiAccessLevel, type BackendAiPermission } from '@/api/backend'
import { EmptyState, Page } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'
import { tapLight, tapMedium } from '@/utils/feedback'

function levelLabel(level: BackendAiAccessLevel, maxLevel: BackendAiAccessLevel) {
  if (level === 'denied') return '不允许'
  if (level === 'operate') return '授权操作'
  return maxLevel === 'operate' ? '只读' : '允许读取'
}

function optionsFor(item: BackendAiPermission): BackendAiAccessLevel[] {
  if (item.maxAccessLevel === 'operate') return ['denied', 'operate']
  return ['denied', 'read']
}

function groupTitle(groupKey: string) {
  if (groupKey === 'operate') return '授权操作'
  return '只读权限'
}

function groupSub(groupKey: string) {
  if (groupKey === 'operate') return '只在你明确要求时生效，关键业务仍会打开页面由你确认。'
  return '只读取脱敏摘要，用于回答你的服务状态，不返回完整资料。'
}

export default function AiSettingsPage() {
  const [items, setItems] = useState<BackendAiPermission[]>([])
  const [dangerousScopes, setDangerousScopes] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [savingScope, setSavingScope] = useState('')

  async function load() {
    const user = ensureLoggedIn('/pages/account/ai-settings/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    try {
      const result = await backend.accountAiPermissions(token)
      setItems(result.items || [])
      setDangerousScopes(result.dangerousScopes || [])
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : 'AI 授权加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useDidShow(() => {
    void load()
  })

  const groups = useMemo(() => {
    return ['read', 'operate'].map((groupKey) => ({
      groupKey,
      items: items.filter((item) => item.groupKey === groupKey).sort((a, b) => a.sortOrder - b.sortOrder),
    })).filter((group) => group.items.length > 0)
  }, [items])

  async function setAccess(item: BackendAiPermission, accessLevel: BackendAiAccessLevel) {
    if (item.accessLevel === accessLevel || savingScope) return
    const token = getToken()
    if (!token) return
    tapLight()
    const previous = items
    setSavingScope(item.scopeCode)
    setItems((current) => current.map((entry) => entry.scopeCode === item.scopeCode ? { ...entry, accessLevel } : entry))
    try {
      const result = await backend.updateAccountAiPermissions(token, [{ scopeCode: item.scopeCode, accessLevel }])
      setItems(result.items || [])
      setDangerousScopes(result.dangerousScopes || [])
      tapMedium()
    } catch (error) {
      setItems(previous)
      Taro.showToast({ title: error instanceof Error ? error.message : '保存失败', icon: 'none' })
    } finally {
      setSavingScope('')
    }
  }

  return (
    <Page title="AI 助手授权" subtle="控制 AI 能读取什么、能辅助什么，以及永远不能做什么">
      {loading ? <EmptyState compact title="正在同步授权设置" /> : null}

      {!loading && groups.map((group) => (
        <View key={group.groupKey} className="ai-settings-section">
          <View className="ai-settings-head">
            <Text className="settings-title">{groupTitle(group.groupKey)}</Text>
            <Text className="ai-settings-sub">{groupSub(group.groupKey)}</Text>
          </View>
          <View className="ai-permission-list">
            {group.items.map((item) => (
              <View key={item.scopeCode} className="ai-permission-row">
                <View className="ai-permission-copy">
                  <Text className="account-menu-title">{item.label}</Text>
                  <Text className="account-menu-sub">{item.description}</Text>
                </View>
                <View className="ai-segment">
                  {optionsFor(item).map((level) => (
                    <View
                      key={level}
                      className={item.accessLevel === level ? 'ai-segment-option active' : 'ai-segment-option'}
                      onClick={() => setAccess(item, level)}
                    >
                      <Text>{savingScope === item.scopeCode && item.accessLevel === level ? '保存中' : levelLabel(level, item.maxAccessLevel)}</Text>
                    </View>
                  ))}
                </View>
              </View>
            ))}
          </View>
        </View>
      ))}

      {!loading && (
        <View className="ai-settings-section danger">
          <View className="ai-settings-head">
            <Text className="settings-title">始终禁止</Text>
            <Text className="ai-settings-sub">这些能力不提供授权开关，AI 只能解释或引导你手动打开页面。</Text>
          </View>
          <View className="ai-danger-list">
            {dangerousScopes.map((item) => (
              <View key={item} className="ai-danger-row">
                <Text>{item}</Text>
              </View>
            ))}
          </View>
        </View>
      )}
    </Page>
  )
}
