import { useState, useEffect, useMemo } from 'react'
import { useAccountApiKeys, useCreateAccountApiKey, useUpdateAccountApiKey, useDeleteAccountApiKey } from '@/service/account'
import '../App.css'

const maskToken = (token) => `${token.slice(0, 10)}${'*'.repeat(16)}`

const toDateText = (timestamp) => {
  if (!timestamp) return '永久有效'
  return new Date(timestamp * 1000).toLocaleDateString('zh-CN')
}

const getRemainDays = (timestamp) => {
  if (!timestamp) return null
  const remainMs = timestamp * 1000 - Date.now()
  return Math.max(0, Math.ceil(remainMs / 86400000))
}

const isExpired = (apiKey) => apiKey.expires_at && apiKey.expires_at * 1000 <= Date.now()

function ApiKeyModal({ onClose }) {
  const [apiKeys, setApiKeys] = useState([])
  const [loading, setLoading] = useState(false)
  const [expiresInDays, setExpiresInDays] = useState('')
  const [copied, setCopied] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [operateId, setOperateId] = useState(null)

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

  const fetchKeys = async () => {
    setLoading(true)
    try {
      const response = await useAccountApiKeys()
      setApiKeys(response?.data || response || [])
    } catch (e) {
      setError(e.message || '获取API Key失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async () => {
    const days = expiresInDays.trim() ? Number(expiresInDays) : null
    if (days !== null && (!Number.isInteger(days) || days <= 0)) {
      setError('请输入有效的过期天数')
      return
    }
    setSubmitting(true)
    setError('')
    setSuccess('')
    try {
      await useCreateAccountApiKey({ body: { expires_in_days: days } })
      setSuccess('API Key 创建成功')
      setExpiresInDays('')
      fetchKeys()
    } catch (e) {
      setError(e.message || '创建API Key失败')
    } finally {
      setSubmitting(false)
    }
  }

  const handleCopy = (token) => {
    navigator.clipboard.writeText(token)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleToggleStatus = async (apiKey) => {
    const nextStatus = apiKey.status === 'active' ? 'inactive' : 'active'
    setOperateId(apiKey.id)
    try {
      await useUpdateAccountApiKey(apiKey.id, { body: { status: nextStatus } })
      fetchKeys()
    } catch (e) {
      setError(e.message || '更新状态失败')
    } finally {
      setOperateId(null)
    }
  }

  const handleDelete = async (apiKey) => {
    if (!window.confirm(`确定要删除 API Key 吗？`)) return
    setOperateId(apiKey.id)
    try {
      await useDeleteAccountApiKey(apiKey.id)
      setSuccess('API Key 已删除')
      fetchKeys()
    } catch (e) {
      setError(e.message || '删除失败')
    } finally {
      setOperateId(null)
    }
  }

  const isMutating = submitting || operateId !== null

  const copiedTip = useMemo(() => {
    return copied ? '已复制' : '复制'
  }, [copied])

  return (
    <div className="profile-modal-overlay" onClick={onClose}>
      <div className="profile-modal" onClick={e => e.stopPropagation()}>
        <div className="profile-modal-header">
          <h2>API Key 管理</h2>
          <button className="profile-close-btn" onClick={onClose}>✕</button>
        </div>

        <div className="profile-tab-content">
          {error && <div className="alert alert-error">{error}</div>}
          {success && <div className="alert alert-success">{success}</div>}

          <div className="apikey-create-section">
            <div className="apikey-create-title">创建新的 API Key</div>
            <div className="apikey-create-form">
              <input
                type="number"
                min={1}
                value={expiresInDays}
                onChange={e => setExpiresInDays(e.target.value)}
                placeholder="过期天数（留空表示永久有效）"
                className="apikey-expires-input"
              />
              <button 
                className="btn btn-primary" 
                onClick={handleCreate}
                disabled={isMutating}
              >
                {submitting ? '创建中...' : '添加'}
              </button>
            </div>
          </div>

          <div className="apikey-list">
            <div className="apikey-list-header">
              <div className="apikey-col apikey-col-key">Key</div>
              <div className="apikey-col apikey-col-status">状态</div>
              <div className="apikey-col apikey-col-expires">过期时间</div>
              <div className="apikey-col apikey-col-actions">操作</div>
            </div>
            {loading ? (
              <div className="apikey-loading">加载中...</div>
            ) : apiKeys.length === 0 ? (
              <div className="apikey-empty">暂无 API Key</div>
            ) : (
              apiKeys.map(apiKey => {
                const expired = apiKey.status === 'active' && isExpired(apiKey)
                const displayStatus = expired
                  ? '已过期'
                  : apiKey.status === 'active' ? '启用' : '禁用'
                const remainDays = getRemainDays(apiKey.expires_at)
                return (
                  <div key={apiKey.id} className="apikey-list-item">
                    <div className="apikey-col apikey-col-key">
                      <span className="apikey-token-text">{maskToken(apiKey.token)}</span>
                      <button 
                        className="apikey-copy-btn"
                        onClick={() => handleCopy(apiKey.token)}
                        title={copiedTip}
                      >
                        {copied ? '✓' : '📋'}
                      </button>
                    </div>
                    <div className="apikey-col apikey-col-status">
                      <span className={`apikey-status ${apiKey.status === 'active' && !expired ? 'active' : 'inactive'}`}>
                        {displayStatus}
                      </span>
                    </div>
                    <div className="apikey-col apikey-col-expires">
                      <div className="apikey-expires-text">{toDateText(apiKey.expires_at)}</div>
                      {remainDays !== null && apiKey.expires_at && (
                        <div className="apikey-remain-text">（{remainDays} 天）</div>
                      )}
                    </div>
                    <div className="apikey-col apikey-col-actions">
                      <button 
                        className={`apikey-action-btn ${apiKey.status === 'active' ? 'disable' : 'enable'}`}
                        onClick={() => handleToggleStatus(apiKey)}
                        disabled={isMutating}
                      >
                        {apiKey.status === 'active' ? '禁用' : '启用'}
                      </button>
                      <button 
                        className="apikey-action-btn delete"
                        onClick={() => handleDelete(apiKey)}
                        disabled={isMutating}
                      >
                        删除
                      </button>
                    </div>
                  </div>
                )
              })
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default ApiKeyModal