'use client'

import { useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { CheckCircle, Loader2 } from 'lucide-react'
import Link from 'next/link'

export default function CreditTopupSuccess() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const sessionId = searchParams.get('session_id')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [amount, setAmount] = useState<number | null>(null)
  const [countdown, setCountdown] = useState(3)

  useEffect(() => {
    if (sessionId) {
      // 验证支付会话
      fetch(`/api/credits/verify-payment?session_id=${sessionId}`)
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            setAmount(data.amount)
          } else {
            setError(data.error || 'Payment verification failed')
          }
        })
        .catch(() => {
          setError('Failed to verify payment')
        })
        .finally(() => {
          setLoading(false)
        })
    } else {
      setError('No session ID provided')
      setLoading(false)
    }
  }, [sessionId])

  // 倒计时和自动跳转
  useEffect(() => {
    if (!loading && !error && amount !== null) {
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer)
            router.push('/credits')
            return 0
          }
          return prev - 1
        })
      }, 1000)

      return () => clearInterval(timer)
    }
  }, [loading, error, amount, router])

  if (loading) {
    return (
      <div className="container mx-auto py-8 px-4">
        <Card className="max-w-md mx-auto">
          <CardContent className="pt-6">
            <div className="flex items-center justify-center">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">Verifying payment...</span>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  if (error) {
    return (
      <div className="container mx-auto py-8 px-4">
        <Card className="max-w-md mx-auto">
          <CardHeader>
            <CardTitle className="text-red-600">Payment Error</CardTitle>
            <CardDescription>{error}</CardDescription>
          </CardHeader>
          <CardContent>
            <Link href="/credits" className="w-full">
              <Button className="w-full">Back to Credits</Button>
            </Link>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <Card className="max-w-md mx-auto">
        <CardHeader className="text-center">
          <div className="flex justify-center mb-4">
            <CheckCircle className="h-16 w-16 text-green-500" />
          </div>
          <CardTitle className="text-green-600">Payment Successful!</CardTitle>
          <CardDescription>
            {amount && `$${amount} has been added to your account`}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <p className="text-center text-muted-foreground">
            Your credit top-up has been processed successfully. The credits have been added to your account.
          </p>
          {countdown > 0 && (
            <div className="text-center">
              <p className="text-sm text-muted-foreground">
                Redirecting to credits page in <span className="font-semibold text-blue-600">{countdown}</span> seconds...
              </p>
            </div>
          )}
          <div className="flex flex-col gap-3">
            <Link href="/credits" className="block">
              <Button className="w-full">View Credits</Button>
            </Link>
            <Link href="/studio" className="block">
              <Button variant="outline" className="w-full">Continue to Studio</Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}