'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { useAuthUser } from '@/hooks/useAuthUser'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { Crown, Star, CreditCard, AlertTriangle } from 'lucide-react'

import { SubscriptionStatus } from '@/components/subscription/SubscriptionStatus'
import { QuickUpgradeButton } from '@/components/subscription/SubscribeButton'

interface SubscriptionData {
  plan: string
  status?: string
  subscriptions: Array<{
    id: string
    status: string
    currentPeriodEnd: number
    cancelAtPeriodEnd: boolean
  }>
}

export default function SubscriptionPage() {
  const { user, userData, loading } = useAuthUser()
  const router = useRouter()
  const t = useTranslations('subscription')

  const [subscriptionData, setSubscriptionData] = useState<SubscriptionData | null>(null)
  const [subscriptionLoading, setSubscriptionLoading] = useState(true)
  const [actionLoading, setActionLoading] = useState(false)

  useEffect(() => {
    if (!loading && !user) {
      router.push('/signin')
      return
    }

    const fetchSubscriptionData = async () => {
      if (!userData) return

      try {
        // 检查是否是从支付成功页面返回
        const urlParams = new URLSearchParams(window.location.search)
        const isSuccess = urlParams.get('success') === 'true'

        if (isSuccess) {
          // 先同步订阅状态
          try {
            const syncResponse = await fetch('/api/subscription/sync', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' }
            })
            if (syncResponse.ok) {
              // 清除 URL 参数
              window.history.replaceState({}, '', '/subscription')
            }
          } catch (syncError) {
            console.error('Failed to sync subscription:', syncError)
          }
        }

        const response = await fetch('/api/subscription/manage')
        if (response.ok) {
          const data = await response.json()
          setSubscriptionData(data)
        }
      } catch (error) {
        console.error('Failed to fetch subscription data:', error)
      } finally {
        setSubscriptionLoading(false)
      }
    }

    if (userData) {
      fetchSubscriptionData()
    }
  }, [user, userData, loading, router])



  const handleCancelSubscription = async (subscriptionId: string) => {
    if (!confirm(t('confirmCancel'))) return

    setActionLoading(true)
    try {
      const response = await fetch('/api/subscription/manage', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'cancel',
          subscriptionId
        }),
      })

      if (response.ok) {
        // 刷新订阅数据
        window.location.reload()
      } else {
        throw new Error('Failed to cancel subscription')
      }
    } catch (error) {
      console.error('Cancel failed:', error)
      alert('Failed to cancel subscription. Please try again.')
    } finally {
      setActionLoading(false)
    }
  }



  const handleSyncSubscription = async () => {
    setActionLoading(true)
    try {
      const response = await fetch('/api/subscription/sync', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (response.ok) {
        const result = await response.json()
        console.log('Sync result:', result)
        // 刷新页面以显示最新状态
        window.location.reload()
      } else {
        throw new Error('Failed to sync subscription')
      }
    } catch (error) {
      console.error('Sync failed:', error)
      alert('Failed to sync subscription. Please try again.')
    } finally {
      setActionLoading(false)
    }
  }

  const handleManageSubscription = async () => {
    setActionLoading(true)
    try {
      const response = await fetch('/api/subscription/portal', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (response.ok) {
        const result = await response.json()
        // 重定向到Stripe客户门户
        window.location.href = result.url
      } else {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to create portal session')
      }
    } catch (error) {
      console.error('Portal creation failed:', error)
      const message = error.message.includes('development mode') 
        ? 'Stripe billing portal is only available in production environment.'
        : 'Failed to access billing portal. Please try again.'
      alert(message)
    } finally {
      setActionLoading(false)
    }
  }

  if (loading || subscriptionLoading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="max-w-4xl mx-auto px-4 py-8">
          <div className="flex items-center justify-center min-h-96">
            <div className="flex flex-col items-center gap-3">
              <LoadingSpinner />
              <p className="text-sm text-muted-foreground">{t('loading')}</p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  const currentPlan = subscriptionData?.plan || 'free'

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="max-w-4xl mx-auto px-4 py-8">
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-foreground mb-2">
                {t('title')}
              </h1>
              <p className="text-muted-foreground">
                {t('subtitle')}
              </p>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleSyncSubscription}
              disabled={actionLoading}
              className="flex items-center gap-2 text-muted-foreground hover:text-foreground"
            >
              {actionLoading ? (
                <LoadingSpinner className="w-4 h-4" />
              ) : (
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
              )}
              Refresh
            </Button>
          </div>
        </div>

        <div className="grid gap-6">
          {/* Current Plan */}
          <SubscriptionStatus />

          {/* Quick Actions */}
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="font-semibold text-foreground mb-4">{t('quickActions')}</h3>
            <div className="space-y-4">
              {/* Primary Actions */}
              <div className="flex flex-col sm:flex-row gap-3">
                {currentPlan === 'free' ? (
                  <QuickUpgradeButton className="flex items-center">
                    <Crown className="w-4 h-4 mr-2" />
                    {t('upgradePlan')}
                  </QuickUpgradeButton>
                ) : (
                  <>
                    <Button
                      variant="outline"
                      onClick={handleManageSubscription}
                      disabled={actionLoading}
                      className="flex items-center"
                    >
                      {actionLoading ? <LoadingSpinner className="w-4 h-4 mr-2" /> : <CreditCard className="w-4 h-4 mr-2" />}
                      {t('manageBilling')}
                    </Button>
                    {subscriptionData?.subscriptions && subscriptionData.subscriptions.length > 0 && (
                      <Button
                        variant="destructive"
                        onClick={() => handleCancelSubscription(subscriptionData.subscriptions[0].id)}
                        disabled={actionLoading}
                        className="flex items-center"
                      >
                        {actionLoading ? <LoadingSpinner className="w-4 h-4 mr-2" /> : <AlertTriangle className="w-4 h-4 mr-2" />}
                        {t('cancelSubscription')}
                      </Button>
                    )}
                  </>
                )}
              </div>

              {/* Secondary Actions */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Button
                  variant="ghost"
                  onClick={() => router.push('/pricing')}
                  className="flex items-center justify-start p-4 h-auto"
                >
                  <div className="flex flex-col items-start text-left">
                    <div className="flex items-center mb-1">
                      <Crown className="w-4 h-4 mr-2" />
                      <span className="font-medium">{t('planDetails')}</span>
                    </div>
                    <span className="text-sm text-muted-foreground">{t('planDetailsDescription')}</span>
                  </div>
                </Button>
                
                <Button
                  variant="ghost"
                  onClick={() => router.push('/credits')}
                  className="flex items-center justify-start p-4 h-auto"
                >
                  <div className="flex flex-col items-start text-left">
                    <div className="flex items-center mb-1">
                      <CreditCard className="w-4 h-4 mr-2" />
                      <span className="font-medium">{t('feeDetails')}</span>
                    </div>
                    <span className="text-sm text-muted-foreground">{t('feeDetailsDescription')}</span>
                  </div>
                </Button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
