'use client'

import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { useBetterAuth } from '@/hooks/useBetterAuth'
import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { 
  CreditCard, 
  TrendingUp, 
  TrendingDown, 
  Calendar,
  Filter,
  ArrowUpDown,
  ChevronLeft,
  ChevronRight,
  Plus,
  Minus,
  Zap,
  DollarSign,
  X
} from 'lucide-react'

interface CreditTransaction {
  id: string
  amount: number
  balance: number
  type: string
  category?: string
  note?: string
  referenceId?: string
  referenceType?: string
  createdAt: string
}

interface CreditStats {
  currentBalance: number
  totalEarned: number
  totalSpent: number
  thisMonthEarned: number
  thisMonthSpent: number
}

interface CreditTransactionsResult {
  transactions: CreditTransaction[]
  total: number
  currentBalance: number
}

export default function CreditsPage() {
  const { user, loading } = useBetterAuth()
  const t = useTranslations('credits')
  
  const [transactions, setTransactions] = useState<CreditTransaction[]>([])
  const [stats, setStats] = useState<CreditStats | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [total, setTotal] = useState(0)
  
  // Filters and pagination
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(20)
  const [typeFilter, setTypeFilter] = useState<string>('')
  const [categoryFilter, setCategoryFilter] = useState<string>('')
  const [sortBy, setSortBy] = useState<'createdAt' | 'amount' | 'balance'>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  
  // Top-up modal state
  const [showTopUpModal, setShowTopUpModal] = useState(false)
  const [topUpAmount, setTopUpAmount] = useState('')
  const [isTopUpLoading, setIsTopUpLoading] = useState(false)
  
  const totalPages = Math.ceil(total / pageSize)

  const loadCreditData = useCallback(async () => {
    if (!user) return

    setIsLoading(true)
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString(),
        sortBy,
        sortOrder
      })
      
      if (typeFilter) params.append('type', typeFilter)
      if (categoryFilter) params.append('category', categoryFilter)

      const [transactionsResponse, statsResponse] = await Promise.all([
        fetch(`/api/credits/transactions?${params}`),
        fetch('/api/credits/stats')
      ])

      if (transactionsResponse.ok) {
        const data: CreditTransactionsResult = await transactionsResponse.json()
        setTransactions(data.transactions)
        setTotal(data.total)
      }

      if (statsResponse.ok) {
        const statsData: CreditStats = await statsResponse.json()
        setStats(statsData)
      }
    } catch (error) {
      console.error('Error loading credit data:', error)
    } finally {
      setIsLoading(false)
    }
  }, [user, currentPage, pageSize, typeFilter, categoryFilter, sortBy, sortOrder])

  useEffect(() => {
    if (user) {
      loadCreditData()
    }
  }, [user, loadCreditData])

  const getTransactionIcon = (type: string, amount: number) => {
    if (amount > 0) {
      switch (type) {
        case 'system_gift':
          return <Zap className="w-4 h-4 text-blue-500" />
        case 'subscription_monthly':
          return <Calendar className="w-4 h-4 text-green-500" />
        case 'user_purchase':
          return <Plus className="w-4 h-4 text-green-500" />
        default:
          return <Plus className="w-4 h-4 text-green-500" />
      }
    } else {
      return <Minus className="w-4 h-4 text-red-500" />
    }
  }

  const getTransactionColor = (amount: number) => {
    return amount > 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
  }

  const getTransactionBadgeColor = (type: string) => {
    switch (type) {
      case 'system_gift':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
      case 'subscription_monthly':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
      case 'user_purchase':
        return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200'
      case 'consumption':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
      case 'subscription_payment':
        return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'
      case 'subscription_refund':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200'
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
    }
  }

  const formatTransactionType = (type: string) => {
    switch (type) {
      case 'system_gift':
        return t('systemGift')
      case 'subscription_monthly':
        return t('monthlyAllowance')
      case 'user_purchase':
        return t('purchase')
      case 'consumption':
        return t('usage')
      case 'subscription_payment':
        return t('subscriptionPayment')
      case 'subscription_refund':
        return t('subscriptionRefund')
      default:
        return type
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString()
  }

  const handleTopUp = async () => {
    const amount = parseFloat(topUpAmount)
    
    if (!amount || amount <= 0) {
      alert('Please enter a valid amount greater than 0')
      return
    }

    if (amount > 1000) {
      alert('Maximum top-up amount is $1000')
      return
    }

    setIsTopUpLoading(true)
    try {
      // 统一使用 Stripe 支付
      const response = await fetch('/api/credits/stripe-topup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ amount }),
      })

      const data = await response.json()

      if (response.ok && data.url) {
        // 重定向到 Stripe Checkout
        window.location.href = data.url
      } else {
        console.error("failed to create payment session: ", data.error)
        alert(data.error || 'Failed to create payment session')
      }
    } catch (error) {
      console.error('Top-up error:', error)
      alert('Failed to process top-up. Please try again.')
    } finally {
      setIsTopUpLoading(false)
    }
  }

  const predefinedAmounts = [5, 10, 25, 50, 100]

  if (loading || !user) {
    return (
      <div className="min-h-screen">
        <Header />
        <div className="max-w-7xl mx-auto px-4 py-8">
          <div className="flex items-center justify-center min-h-[400px]">
            <LoadingSpinner />
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen">
      <Header />
      
      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-foreground mb-2">{t('title')}</h1>
          <p className="text-muted-foreground">{t('subtitle')}</p>
        </div>

        {/* Balance and Top-up Section */}
        {stats && (
          <div className="space-y-6 mb-8">
            {/* Main Balance Card */}
            <Card className="overflow-hidden">
              <div className="bg-gradient-to-br from-green-50 via-emerald-50 to-teal-50 dark:from-green-950/30 dark:via-emerald-950/30 dark:to-teal-950/30 p-6 sm:p-8">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                  {/* Balance Display */}
                  <div className="flex items-center space-x-4">
                    <div className="p-3 rounded-full bg-green-500 shadow-lg">
                      <CreditCard className="w-6 h-6 text-white" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-green-700 dark:text-green-300 mb-1">
                        {t('currentBalance')}
                      </p>
                      <p className="text-3xl sm:text-4xl font-bold text-green-800 dark:text-green-200">
                        ${stats.currentBalance.toFixed(2)}
                      </p>
                    </div>
                  </div>
                  
                  {/* Top-up Button */}
                  <div className="flex flex-col items-stretch sm:items-end gap-2 w-full sm:w-auto">
                    <Button
                      onClick={() => setShowTopUpModal(true)}
                      size="lg"
                      className="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-8 py-3 rounded-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
                    >
                      <Plus className="w-5 h-5 mr-2" />
                      {t('topUp')}
                    </Button>
                    <p className="text-xs text-green-600 dark:text-green-400 text-center sm:text-right">
                      {t('instantTopUp')}
                    </p>
                  </div>
                </div>
              </div>
            </Card>

            {/* Stats Overview */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              <Card className="p-4 sm:p-5 hover:shadow-md transition-shadow duration-200">
                <div className="flex items-center space-x-3">
                  <div className="p-2 rounded-full bg-blue-500/10 dark:bg-blue-500/20">
                    <TrendingUp className="w-4 h-4 text-blue-500" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-xs font-medium text-muted-foreground truncate">{t('totalEarned')}</p>
                    <p className="text-lg font-bold text-foreground">${stats.totalEarned.toFixed(2)}</p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 sm:p-5 hover:shadow-md transition-shadow duration-200">
                <div className="flex items-center space-x-3">
                  <div className="p-2 rounded-full bg-red-500/10 dark:bg-red-500/20">
                    <TrendingDown className="w-4 h-4 text-red-500" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-xs font-medium text-muted-foreground truncate">{t('totalSpent')}</p>
                    <p className="text-lg font-bold text-foreground">${stats.totalSpent.toFixed(2)}</p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 sm:p-5 hover:shadow-md transition-shadow duration-200">
                <div className="flex items-center space-x-3">
                  <div className="p-2 rounded-full bg-emerald-500/10 dark:bg-emerald-500/20">
                    <Calendar className="w-4 h-4 text-emerald-500" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-xs font-medium text-muted-foreground truncate">{t('thisMonthEarned')}</p>
                    <p className="text-lg font-bold text-foreground">${stats.thisMonthEarned.toFixed(2)}</p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 sm:p-5 hover:shadow-md transition-shadow duration-200">
                <div className="flex items-center space-x-3">
                  <div className="p-2 rounded-full bg-orange-500/10 dark:bg-orange-500/20">
                    <Calendar className="w-4 h-4 text-orange-500" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-xs font-medium text-muted-foreground truncate">{t('thisMonthSpent')}</p>
                    <p className="text-lg font-bold text-foreground">${stats.thisMonthSpent.toFixed(2)}</p>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        )}

        {/* Filters */}
        <Card className="p-4 mb-6">
          <div className="flex flex-wrap gap-4 items-center">
            <div className="flex items-center space-x-2">
              <Filter className="w-4 h-4 text-muted-foreground" />
              <span className="text-sm font-medium text-foreground">{t('filters')}:</span>
            </div>
            
            <select
              value={typeFilter}
              onChange={(e) => {
                setTypeFilter(e.target.value)
                setCurrentPage(1)
              }}
              className="px-3 py-1 border border-border rounded-md bg-background text-foreground text-sm"
            >
              <option value="">{t('allTypes')}</option>
              <option value="system_gift">{t('systemGift')}</option>
              <option value="subscription_monthly">{t('monthlyAllowance')}</option>
              <option value="user_purchase">{t('purchase')}</option>
              <option value="consumption">{t('usage')}</option>
              <option value="subscription_payment">{t('subscriptionPayment')}</option>
              <option value="subscription_refund">{t('subscriptionRefund')}</option>
            </select>

            <select
              value={categoryFilter}
              onChange={(e) => {
                setCategoryFilter(e.target.value)
                setCurrentPage(1)
              }}
              className="px-3 py-1 border border-border rounded-md bg-background text-foreground text-sm"
            >
              <option value="">{t('allCategories')}</option>
              <option value="simulation">{t('simulation')}</option>
              <option value="api_call">{t('apiCall')}</option>
              <option value="export">{t('export')}</option>
            </select>

            <div className="flex items-center space-x-2">
              <ArrowUpDown className="w-4 h-4 text-muted-foreground" />
              <select
                value={`${sortBy}-${sortOrder}`}
                onChange={(e) => {
                  const [field, order] = e.target.value.split('-')
                  setSortBy(field as 'createdAt' | 'amount' | 'balance')
                  setSortOrder(order as 'asc' | 'desc')
                  setCurrentPage(1)
                }}
                className="px-3 py-1 border border-border rounded-md bg-background text-foreground text-sm"
              >
                <option value="createdAt-desc">{t('newestFirst')}</option>
                <option value="createdAt-asc">{t('oldestFirst')}</option>
                <option value="amount-desc">{t('highestAmount')}</option>
                <option value="amount-asc">{t('lowestAmount')}</option>
                <option value="balance-desc">{t('highestBalance')}</option>
                <option value="balance-asc">{t('lowestBalance')}</option>
              </select>
            </div>
          </div>
        </Card>

        {/* Transactions List */}
        <Card>
          <div className="p-6">
            <h2 className="text-xl font-semibold text-foreground mb-4">{t('transactionHistory')}</h2>
            
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <LoadingSpinner />
              </div>
            ) : transactions.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <CreditCard className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>{t('noTransactions')}</p>
              </div>
            ) : (
              <div className="space-y-3">
                {transactions.map((transaction) => (
                  <div
                    key={transaction.id}
                    className="flex items-center justify-between p-4 rounded-lg border border-border hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-center space-x-4">
                      <div className="p-2 rounded-full bg-muted">
                        {getTransactionIcon(transaction.type, transaction.amount)}
                      </div>
                      
                      <div>
                        <div className="flex items-center space-x-2 mb-1">
                          <Badge className={`text-xs ${getTransactionBadgeColor(transaction.type)}`}>
                            {formatTransactionType(transaction.type)}
                          </Badge>
                          {transaction.category && (
                            <Badge variant="outline" className="text-xs">
                              {transaction.category}
                            </Badge>
                          )}
                        </div>
                        
                        <p className="text-sm text-foreground font-medium">
                          {transaction.note || t('noDescription')}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {formatDate(transaction.createdAt)}
                        </p>
                      </div>
                    </div>

                    <div className="text-right">
                      <p className={`text-lg font-bold ${getTransactionColor(transaction.amount)}`}>
                        {transaction.amount > 0 ? '+' : ''}${Math.abs(transaction.amount).toFixed(2)}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {t('balance')}: ${transaction.balance.toFixed(2)}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center justify-between mt-6 pt-4 border-t border-border">
                <div className="text-sm text-muted-foreground">
                  {t('showing')} {((currentPage - 1) * pageSize) + 1} - {Math.min(currentPage * pageSize, total)} {t('of')} {total} {t('transactions')}
                </div>
                
                <div className="flex items-center space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                    disabled={currentPage === 1}
                  >
                    <ChevronLeft className="w-4 h-4" />
                  </Button>
                  
                  <div className="flex items-center space-x-1">
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      let pageNum
                      if (totalPages <= 5) {
                        pageNum = i + 1
                      } else if (currentPage <= 3) {
                        pageNum = i + 1
                      } else if (currentPage >= totalPages - 2) {
                        pageNum = totalPages - 4 + i
                      } else {
                        pageNum = currentPage - 2 + i
                      }
                      
                      return (
                        <Button
                          key={pageNum}
                          variant={currentPage === pageNum ? "default" : "outline"}
                          size="sm"
                          onClick={() => setCurrentPage(pageNum)}
                        >
                          {pageNum}
                        </Button>
                      )
                    })}
                  </div>
                  
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                    disabled={currentPage === totalPages}
                  >
                    <ChevronRight className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            )}
          </div>
        </Card>

        {/* Top-up Modal */}
        {showTopUpModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-background rounded-lg shadow-xl max-w-md w-full">
              <div className="flex items-center justify-between p-6 border-b border-border">
                <h2 className="text-xl font-semibold text-foreground">{t('topUp')}</h2>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowTopUpModal(false)}
                >
                  <X className="w-4 h-4" />
                </Button>
              </div>
              
              <div className="p-6 space-y-4">
                <div>
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    {t('enterAmount')}
                  </label>
                  <div className="relative">
                    <DollarSign className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
                    <input
                      type="number"
                      value={topUpAmount}
                      onChange={(e) => setTopUpAmount(e.target.value)}
                      placeholder="0.00"
                      min="0.01"
                      max="1000"
                      step="0.01"
                      className="w-full pl-10 pr-4 py-2 border border-border rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                </div>

                <div>
                  <p className="text-sm font-medium text-foreground mb-2">{t('quickAmounts')}</p>
                  <div className="grid grid-cols-5 gap-2">
                    {predefinedAmounts.map((amount) => (
                      <Button
                        key={amount}
                        variant="outline"
                        size="sm"
                        onClick={() => setTopUpAmount(amount.toString())}
                        className="text-xs"
                      >
                        ${amount}
                      </Button>
                    ))}
                  </div>
                </div>

                <div className="bg-blue-50 dark:bg-blue-950/20 p-3 rounded-md">
                  <p className="text-xs text-blue-700 dark:text-blue-300">
                    {t('topUpNote')}
                  </p>
                </div>
              </div>

              <div className="flex gap-3 p-6 border-t border-border">
                <Button
                  variant="outline"
                  onClick={() => setShowTopUpModal(false)}
                  disabled={isTopUpLoading}
                  className="flex-1"
                >
                  {t('cancel')}
                </Button>
                <Button
                  onClick={handleTopUp}
                  disabled={isTopUpLoading || !topUpAmount || parseFloat(topUpAmount) <= 0}
                  className="flex-1 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700"
                >
                  {isTopUpLoading ? (
                    <>
                      <LoadingSpinner className="w-4 h-4 mr-2" />
                      {t('processing')}
                    </>
                  ) : (
                    <>
                      <Plus className="w-4 h-4 mr-2" />
                      {t('topUpNow')}
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}