'use client'
import { useState } from 'react'
import { Button, useDocumentInfo } from '@payloadcms/ui'
import { useRouter } from 'next/navigation'

/**
 * 编辑页面内的订单计数刷新组件
 * 只针对当前编辑的预购商品刷新订单数据
 */
export function RefreshOrderCountField() {
  const { id } = useDocumentInfo()
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState('')
  const router = useRouter()

  const handleRefresh = async () => {
    if (!id) {
      setMessage('⚠️ 无法获取商品 ID')
      return
    }

    setLoading(true)
    setMessage('')

    try {
      const response = await fetch('/api/preorders/refresh-order-counts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          productIds: [id],
        }),
      })

      const data = await response.json()

      if (data.success) {
        setMessage(`✅ ${data.message || '订单计数刷新成功！'}`)
        // 刷新页面数据
        setTimeout(() => {
          router.refresh()
          // 重新加载页面以更新显示
          window.location.reload()
        }, 1000)
      } else {
        setMessage(`❌ 刷新失败: ${data.error || '未知错误'}`)
      }
    } catch (error) {
      setMessage('❌ 刷新出错: ' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div
      style={{
        padding: '1rem',
        border: '1px solid var(--theme-elevation-150)',
        borderRadius: '4px',
        backgroundColor: 'var(--theme-elevation-50)',
        marginBottom: '1rem',
      }}
    >
      <div style={{ marginBottom: '0.75rem' }}>
        <h4 style={{ margin: '0 0 0.5rem 0', fontSize: '0.875rem', fontWeight: 600 }}>
          📊 订单计数同步
        </h4>
        <p style={{ margin: 0, fontSize: '0.8125rem', color: 'var(--theme-elevation-600)' }}>
          从 Medusa 订单系统同步真实订单计数数据
        </p>
      </div>

      <Button
        onClick={handleRefresh}
        disabled={loading}
        buttonStyle="primary"
        size="small"
      >
        {loading ? '同步中...' : '🔄 刷新订单计数'}
      </Button>

      {message && (
        <div
          style={{
            padding: '0.75rem',
            marginTop: '0.75rem',
            borderRadius: '4px',
            backgroundColor: message.startsWith('✅')
              ? 'var(--theme-success-50)'
              : message.startsWith('⚠️')
                ? 'var(--theme-warning-50)'
                : 'var(--theme-error-50)',
            color: message.startsWith('✅')
              ? 'var(--theme-success-900)'
              : message.startsWith('⚠️')
                ? 'var(--theme-warning-900)'
                : 'var(--theme-error-900)',
            fontSize: '0.8125rem',
          }}
        >
          {message}
        </div>
      )}

      <div
        style={{
          marginTop: '0.75rem',
          padding: '0.75rem',
          backgroundColor: 'var(--theme-elevation-100)',
          borderRadius: '4px',
          fontSize: '0.8125rem',
          color: 'var(--theme-elevation-600)',
        }}
      >
        <p style={{ margin: '0.25rem 0', fontWeight: 600 }}>💡 说明：</p>
        <p style={{ margin: '0.25rem 0' }}>
          • <strong>真实订单计数</strong>：从 Medusa 自动同步，只读
        </p>
        <p style={{ margin: '0.25rem 0' }}>
          • <strong>Fake计数</strong>：上方可手动编辑
        </p>
        <p style={{ margin: '0.25rem 0' }}>
          • <strong>显示进度</strong> = 真实订单 + Fake计数
        </p>
      </div>
    </div>
  )
}
