/**
 * SSO 单点登录配置页面
 */
import { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Switch, Tag, Loading, Dialog, Input } from '@nutui/nutui-react-taro'
import {
  getSSOConfig,
  createSSOConfig,
  updateSSOConfig,
  toggleSSO,
  testSSOConnection,
  pageSSOLogs,
} from '@/api/sso'
import type { SSOConfig, SSOProvider, SSOLog } from '@/types/sso'
import './sso.scss'

// 提供商映射
const PROVIDER_MAP: Record<SSOProvider, { text: string; icon: string }> = {
  oidc: { text: 'OIDC', icon: '🔐' },
  saml: { text: 'SAML', icon: '🔑' },
  cas: { text: 'CAS', icon: '🎫' },
  ldap: { text: 'LDAP', icon: '👥' },
  oauth2: { text: 'OAuth2', icon: '🔓' }
}

const STATUS_CONFIG = {
  disconnected: { text: '未连接', color: '#999' },
  connected: { text: '已连接', color: '#34c759' },
  error: { text: '连接错误', color: '#ff3b30' }
}

const SSOConfigPage: React.FC = () => {
  const [loading, setLoading] = useState(true)
  const [config, setConfig] = useState<SSOConfig | null>(null)
  const [logs, setLogs] = useState<SSOLog[]>([])
  const [showModal, setShowModal] = useState(false)

  useEffect(() => {
    loadData()
  }, [])

  const loadData = async () => {
    setLoading(true)
    try {
      const [configData, logData] = await Promise.all([
        getSSOConfig(),
        pageSSOLogs({ page: 1, pageSize: 10 })
      ])
      setConfig(configData)
      setLogs(logData.list)
    } catch (e) {
      console.error('加载失败', e)
    } finally {
      setLoading(false)
    }
  }

  const handleToggle = async (enabled: boolean) => {
    try {
      await toggleSSO(enabled)
      Taro.showToast({ title: enabled ? '已启用' : '已禁用', icon: 'success' })
      loadData()
    } catch (e) {
      Taro.showToast({ title: '操作失败', icon: 'none' })
    }
  }

  const handleTest = async () => {
    Taro.showLoading({ title: '测试中...' })
    try {
      const result = await testSSOConnection()
      Taro.hideLoading()
      if (result.success) {
        Taro.showToast({ title: '连接成功', icon: 'success' })
      } else {
        Dialog.alert({
          title: '连接失败',
          content: result.error || '请检查配置是否正确'
        })
      }
    } catch (e) {
      Taro.hideLoading()
      Taro.showToast({ title: '测试失败', icon: 'none' })
    }
  }

  if (loading) {
    return <Loading className="loading">加载中...</Loading>
  }

  return (
    <View className="sso-page">
      <ScrollView className="sso-content" scrollY>
        {/* SSO 状态卡片 */}
        <View className="status-card">
          <View className="status-header">
            <Text className="status-title">SSO 单点登录</Text>
            <Switch checked={config?.enabled} onChange={(val) => handleToggle(val)} />
          </View>
          <View className="status-info">
            <View className="status-item">
              <Text className="item-label">状态</Text>
              <Tag color={STATUS_CONFIG[config?.connectionStatus || 'disconnected']?.color}>
                {STATUS_CONFIG[config?.connectionStatus || 'disconnected']?.text}
              </Tag>
            </View>
            <View className="status-item">
              <Text className="item-label">提供商</Text>
              <Text className="item-value">
                {PROVIDER_MAP[config?.provider || 'oidc']?.icon} {PROVIDER_MAP[config?.provider || 'oidc']?.text}
              </Text>
            </View>
          </View>
        </View>

        {/* 配置信息 */}
        {config && (
          <View className="config-card">
            <Text className="card-title">配置信息</Text>
            <View className="config-item">
              <Text className="config-label">Issuer</Text>
              <Text className="config-value">{config.issuer || '-'}</Text>
            </View>
            <View className="config-item">
              <Text className="config-label">Client ID</Text>
              <Text className="config-value">{config.clientId || '-'}</Text>
            </View>
            <View className="config-item">
              <Text className="config-label">Entity ID</Text>
              <Text className="config-value">{config.entityId || '-'}</Text>
            </View>
            <View className="config-item">
              <Text className="config-label">ACS URL</Text>
              <Text className="config-value">{config.acsUrl || '-'}</Text>
            </View>
            <View className="config-actions">
              <Button size="small" onClick={handleTest}>
                测试连接
              </Button>
              <Button size="small" type="primary" onClick={() => setShowModal(true)}>
                编辑配置
              </Button>
            </View>
          </View>
        )}

        {/* 连接日志 */}
        <View className="logs-card">
          <Text className="card-title">最近日志</Text>
          {logs.length === 0 ? (
            <Text className="empty-text">暂无日志记录</Text>
          ) : (
            logs.map(log => (
              <View key={log.id} className="log-item">
                <View className="log-header">
                  <Tag type={log.action === 'login' ? 'success' : 'default'}>
                    {log.action === 'login' ? '登录' : log.action === 'logout' ? '登出' : '错误'}
                  </Tag>
                  <Text className="log-time">{log.createTime.slice(0, 16)}</Text>
                </View>
                <Text className="log-message">{log.message}</Text>
              </View>
            ))
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default SSOConfigPage
