'use client'

import { useState, useEffect } from 'react'
import { useAuthUser } from '@/hooks/useAuthUser'
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/ui/loading-spinner'

interface SubscribeButtonProps {
  priceId: string
  planName: string
  className?: string
  children: React.ReactNode
  disabled?: boolean
  variant?: 'default' | 'outline' | 'ghost' | 'destructive'
}

export function SubscribeButton({
  priceId,
  className,
  children,
  disabled = false,
  variant = 'default'
}: SubscribeButtonProps) {
  const { user, loading: authLoading } = useAuthUser()
  const [loading, setLoading] = useState(false)

  const handleSubscribe = async () => {
    // 如果还在加载认证状态，不执行任何操作
    if (authLoading) {
      return
    }

    if (!user) {
      window.location.href = '/signin'
      return
    }



    setLoading(true)

    try {
      // 创建订阅会话
      const response = await fetch('/api/subscription/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ priceId }),
      })

      if (!response.ok) {
        throw new Error('Failed to create subscription')
      }

      const { url } = await response.json()

      // 重定向到 Stripe Checkout
      if (url) {
        window.location.href = url
      }
    } catch (error) {
      console.error('Subscription error:', error)
      alert('Failed to start subscription process. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Button
      variant={variant}
      className={className}
      onClick={handleSubscribe}
      disabled={disabled || loading || authLoading}
    >
      {loading ? (
        <>
          <LoadingSpinner className="w-4 h-4 mr-2" />
          Processing...
        </>
      ) : authLoading ? (
        <>
          <LoadingSpinner className="w-4 h-4 mr-2" />
          Loading...
        </>
      ) : (
        children
      )}
    </Button>
  )
}

// 简化版本，用于快速升级
interface QuickUpgradeButtonProps {
  className?: string
  children?: React.ReactNode
}

export function QuickUpgradeButton({ className, children }: QuickUpgradeButtonProps) {
  const [proPriceId, setProPriceId] = useState<string>('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string>('')

  useEffect(() => {
    const fetchProPriceId = async () => {
      try {
        const response = await fetch('/api/subscription/pro-price-id')
        if (response.ok) {
          const data = await response.json()
          if (data.priceId) {
            setProPriceId(data.priceId)
          } else {
            setError('Pro plan not available')
          }
        } else {
          setError('Failed to load Pro plan')
        }
      } catch {
        setError('Failed to load Pro plan')
      } finally {
        setLoading(false)
      }
    }

    fetchProPriceId()
  }, [])

  if (loading) {
    return (
      <Button variant="default" className={className} disabled>
        <LoadingSpinner className="w-4 h-4 mr-2" />
        Loading...
      </Button>
    )
  }

  if (error || !proPriceId) {
    return (
      <Button variant="outline" className={className} disabled>
        Pro plan unavailable
      </Button>
    )
  }

  return (
    <SubscribeButton
      priceId={proPriceId}
      planName="Pro"
      className={className}
      variant="default"
    >
      {children || 'Upgrade to Pro'}
    </SubscribeButton>
  )
}
