import React, { useState, useEffect } from 'react'
import { View, Text, Input, Button, actionSheet } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { usePullDownRefresh } from '@tarojs/taro'
import { pageApiKey, createApiKey, deleteApiKey } from '@/api/developer/developer'
import type { ApiKey, ApiKeyParam } from '@/types/developer'
import './index.scss'

// API Key 状态映射
const STATUS_MAP: Record<number, { text: string; color: string }> = {
  0: { text: '禁用', color: '#999' },
  1: { text: '正常', color: '#52c41a' },
}

const TYPE_MAP: Record<string, string> = {
  server: '服务端',
  client: '客户端',
  webhook: 'Webhook',
}

const ApiKeysPage: React.FC = () => {
  const router = useRouter()
  const projectId = Number(router.params.projectId) || undefined

  const [loading, setLoading] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [list, setList] = useState<ApiKey[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [createForm, setCreateForm] = useState({
    name: '',
    type: 'server' as const,
    remark: '',
  })
  const [creating, setCreating] = useState(false)

  // 加载数据
  const loadData = async (pageNum: number = 1, isRefresh = false) => {
    if (loading) return
    setLoading(true)
    if (isRefresh) setRefreshing(true)

    try {
      const params: ApiKeyParam = {
        page: pageNum,
        limit: 20,
        websiteId: projectId,
      }
      const data = await pageApiKey(params)

      if (pageNum === 1) {
        setList(data?.records || [])
      } else {
        setList(prev => [...prev, ...(data?.records || [])])
      }

      const total = data?.total || 0
      const records = data?.records || []
      setHasMore(records.length > 0 && (pageNum * 20) < total)
      setPage(pageNum)
    } catch (err) {
      console.error('加载失败', err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

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

  // 下拉刷新
  usePullDownRefresh(() => {
    loadData(1, true)
  })

  // 加载更多
  const onReachBottom = () => {
    if (hasMore && !loading) {
      loadData(page + 1)
    }
  }

  // 创建 API Key
  const handleCreate = async () => {
    if (!createForm.name.trim()) {
      Taro.showToast({ title: '请输入名称', icon: 'none' })
      return
    }

    setCreating(true)
    try {
      await createApiKey({
        name: createForm.name,
        type: createForm.type,
        remark: createForm.remark,
        websiteId: projectId,
      } as Partial<ApiKey>)
      Taro.showToast({ title: '创建成功', icon: 'success' })
      setShowCreate(false)
      setCreateForm({ name: '', type: 'server', remark: '' })
      loadData(1)
    } catch (err) {
      console.error('创建失败', err)
      Taro.showToast({ title: '创建失败', icon: 'none' })
    } finally {
      setCreating(false)
    }
  }

  // 删除 API Key
  const handleDelete = (item: ApiKey) => {
    actionSheet({
      alertText: `确定删除 "${item.name}" 吗？此操作不可恢复。`,
      actions: [
        { name: '删除', color: '#ff4d4f', type: 'warn' as const },
      ],
      confirmText: '取消',
    }).then(res => {
      if (res.confirm) {
        doDelete(item.id!)
      }
    }).catch(() => {})
  }

  const doDelete = async (id: number) => {
    try {
      await deleteApiKey(id)
      Taro.showToast({ title: '已删除', icon: 'success' })
      loadData(1)
    } catch (err) {
      console.error('删除失败', err)
      Taro.showToast({ title: '删除失败', icon: 'none' })
    }
  }

  // 复制内容
  const handleCopy = (text: string, label: string) => {
    Taro.setClipboardData({
      data: text,
      success: () => {
        Taro.showToast({ title: `${label}已复制`, icon: 'success' })
      },
    })
  }

  // 格式化日期
  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  return (
    <View className="api-keys-page">
      {/* 头部 */}
      <View className="api-keys-page__header">
        <Text className="api-keys-page__title">🔑 API Key 管理</Text>
        <Button
          className="api-keys-page__create-btn"
          size="mini"
          onClick={() => setShowCreate(true)}
        >
          + 创建
        </Button>
      </View>

      {/* 提示信息 */}
      <View className="api-keys-page__tips">
        <Text>API Key 是用于调用接口的凭证，请妥善保管，切勿泄露。</Text>
      </View>

      {/* 列表 */}
      <View className="api-keys-page__list">
        {list.length === 0 && !loading ? (
          <View className="api-keys-page__empty">
            <Text>暂无 API Key</Text>
            <Text className="api-keys-page__empty-hint">点击上方「创建」按钮生成新的 Key</Text>
          </View>
        ) : (
          list.map((item) => (
            <View key={item.id} className="api-key-card">
              <View className="api-key-card__header">
                <View className="api-key-card__info">
                  <Text className="api-key-card__name">{item.name}</Text>
                  <View
                    className="api-key-card__status"
                    style={{ color: STATUS_MAP[item.status || 1]?.color }}
                  >
                    {STATUS_MAP[item.status || 1]?.text}
                  </View>
                </View>
                <View
                  className="api-key-card__type"
                >
                  {TYPE_MAP[item.type || 'server']}
                </View>
              </View>

              <View className="api-key-card__body">
                <View className="api-key-card__row">
                  <Text className="api-key-card__label">AppId:</Text>
                  <Text
                    className="api-key-card__value api-key-card__value--monospace"
                    onClick={() => handleCopy(item.appId || '', 'AppId')}
                  >
                    {item.appId || '-'}
                  </Text>
                </View>
                <View className="api-key-card__row">
                  <Text className="api-key-card__label">AppSecret:</Text>
                  <Text
                    className="api-key-card__value api-key-card__value--monospace"
                    onClick={() => handleCopy(item.appSecret || '', 'AppSecret')}
                  >
                    ••••••••••••••••
                  </Text>
                </View>
                {item.remark && (
                  <View className="api-key-card__row">
                    <Text className="api-key-card__label">备注:</Text>
                    <Text className="api-key-card__value">{item.remark}</Text>
                  </View>
                )}
              </View>

              <View className="api-key-card__footer">
                <Text className="api-key-card__time">
                  创建于 {formatDate(item.createTime)}
                </Text>
                <View className="api-key-card__actions">
                  {item.appSecret && (
                    <Text
                      className="api-key-card__action api-key-card__action--primary"
                      onClick={() => handleCopy(item.appSecret || '', 'AppSecret')}
                    >
                      复制密钥
                    </Text>
                  )}
                  <Text
                    className="api-key-card__action api-key-card__action--danger"
                    onClick={() => handleDelete(item)}
                  >
                    删除
                  </Text>
                </View>
              </View>
            </View>
          ))
        )}

        {/* 加载状态 */}
        {loading && list.length > 0 && (
          <View className="api-keys-page__loading">
            <Text>加载中...</Text>
          </View>
        )}

        {!hasMore && list.length > 0 && (
          <View className="api-keys-page__no-more">
            <Text>没有更多了</Text>
          </View>
        )}
      </View>

      {/* 创建弹窗 */}
      {showCreate && (
        <View className="api-keys-page__modal">
          <View className="api-keys-page__modal-mask" onClick={() => setShowCreate(false)} />
          <View className="api-keys-page__modal-content">
            <Text className="api-keys-page__modal-title">创建 API Key</Text>

            <View className="api-keys-page__form">
              <View className="api-keys-page__form-item">
                <Text className="api-keys-page__form-label">名称 *</Text>
                <Input
                  className="api-keys-page__form-input"
                  placeholder="请输入 Key 名称"
                  value={createForm.name}
                  onInput={(e) => setCreateForm(prev => ({ ...prev, name: e.detail.value }))}
                />
              </View>

              <View className="api-keys-page__form-item">
                <Text className="api-keys-page__form-label">类型</Text>
                <View className="api-keys-page__form-radio">
                  {(['server', 'client', 'webhook'] as const).map((type) => (
                    <View
                      key={type}
                      className={`api-keys-page__form-radio-item ${createForm.type === type ? 'active' : ''}`}
                      onClick={() => setCreateForm(prev => ({ ...prev, type }))}
                    >
                      {TYPE_MAP[type]}
                    </View>
                  ))}
                </View>
              </View>

              <View className="api-keys-page__form-item">
                <Text className="api-keys-page__form-label">备注</Text>
                <Input
                  className="api-keys-page__form-input"
                  placeholder="可选，简要描述用途"
                  value={createForm.remark}
                  onInput={(e) => setCreateForm(prev => ({ ...prev, remark: e.detail.value }))}
                />
              </View>
            </View>

            <View className="api-keys-page__modal-actions">
              <Button
                className="api-keys-page__modal-btn api-keys-page__modal-btn--cancel"
                onClick={() => setShowCreate(false)}
              >
                取消
              </Button>
              <Button
                className="api-keys-page__modal-btn api-keys-page__modal-btn--confirm"
                loading={creating}
                onClick={handleCreate}
              >
                创建
              </Button>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default ApiKeysPage
