'use client'

import React, { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Wallet, Plus, RefreshCw, CreditCard } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'

interface BalanceCardProps {
  showAddBalance?: boolean
  className?: string
}

export function BalanceCard({ showAddBalance = true, className = '' }: BalanceCardProps) {
  const { user, getBalance, addBalance, refreshBalance } = useAuth()
  const { toast } = useToast()
  const [balance, setBalance] = useState<number>(user?.balance || 0)
  const [loading, setLoading] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [showAddForm, setShowAddForm] = useState(false)
  const [amount, setAmount] = useState('')
  const [currency, setCurrency] = useState<'INR' | 'USD'>('INR')
  const [error, setError] = useState<string | null>(null)

  // Update balance when user changes
  useEffect(() => {
    if (user?.balance !== undefined) {
      setBalance(user.balance)
    }
  }, [user?.balance])

  const handleRefreshBalance = async () => {
    if (!user) return

    setRefreshing(true)
    setError(null)

    try {
      const newBalance = await getBalance()
      setBalance(newBalance)
      await refreshBalance() // Update user context
      toast({
        title: 'Balance Updated',
        description: 'Your balance has been refreshed successfully.',
      })
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balance'
      setError(errorMessage)
      toast({
        title: 'Error',
        description: errorMessage,
        variant: 'destructive',
      })
    } finally {
      setRefreshing(false)
    }
  }

  const handleAddBalance = async (e: React.FormEvent) => {
    e.preventDefault()

    const numAmount = parseFloat(amount)
    if (!numAmount || numAmount <= 0) {
      setError('Please enter a valid amount')
      return
    }

    const minAmount = currency === 'INR' ? 100 : 2
    const maxAmount = currency === 'INR' ? 100000 : 1500

    if (numAmount < minAmount || numAmount > maxAmount) {
      setError(
        `Amount must be between ${currency === 'INR' ? '₹' : '$'}${minAmount} and ${currency === 'INR' ? '₹' : '$'}${maxAmount}`
      )
      return
    }

    setLoading(true)
    setError(null)

    try {
      const result = await addBalance(numAmount, currency)

      if (result.success && result.paymentUrl && result.formData) {
        // Create and submit payment form
        const form = document.createElement('form')
        form.method = 'POST'
        form.action = result.paymentUrl
        form.style.display = 'none'

        // Add form data
        Object.entries(result.formData).forEach(([key, value]) => {
          const input = document.createElement('input')
          input.type = 'hidden'
          input.name = key
          input.value = String(value)
          form.appendChild(input)
        })

        document.body.appendChild(form)
        form.submit()

        toast({
          title: 'Redirecting to Payment',
          description: 'You will be redirected to the payment gateway.',
        })
      } else {
        setError(result.error || 'Failed to initiate payment')
        toast({
          title: 'Payment Error',
          description: result.error || 'Failed to initiate payment',
          variant: 'destructive',
        })
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to add balance'
      setError(errorMessage)
      toast({
        title: 'Error',
        description: errorMessage,
        variant: 'destructive',
      })
    } finally {
      setLoading(false)
    }
  }

  const formatBalance = (amount: number) => {
    return new Intl.NumberFormat('en-IN', {
      style: 'currency',
      currency: 'INR',
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    }).format(amount)
  }

  if (!user) {
    return null
  }

  return (
    <Card className={`w-full max-w-md ${className}`}>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div className="flex items-center space-x-2">
          <Wallet className="h-5 w-5 text-muted-foreground" />
          <CardTitle className="text-lg font-medium">Balance</CardTitle>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={handleRefreshBalance}
          disabled={refreshing}
          className="h-8 w-8 p-0"
        >
          <RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
        </Button>
      </CardHeader>

      <CardContent className="space-y-4">
        <div className="text-center">
          <div className="text-3xl font-bold text-primary">{formatBalance(balance)}</div>
          <CardDescription>Available Balance</CardDescription>
        </div>

        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {showAddBalance && (
          <div className="space-y-3">
            {!showAddForm ? (
              <Button onClick={() => setShowAddForm(true)} className="w-full" variant="outline">
                <Plus className="h-4 w-4 mr-2" />
                Add Balance
              </Button>
            ) : (
              <form onSubmit={handleAddBalance} className="space-y-3">
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <Label htmlFor="amount">Amount</Label>
                    <Input
                      id="amount"
                      type="number"
                      placeholder="Enter amount"
                      value={amount}
                      onChange={(e) => setAmount(e.target.value)}
                      min={currency === 'INR' ? 100 : 2}
                      max={currency === 'INR' ? 100000 : 1500}
                      step={currency === 'INR' ? 1 : 0.01}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="currency">Currency</Label>
                    <Select
                      value={currency}
                      onValueChange={(value: 'INR' | 'USD') => setCurrency(value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="INR">INR (₹)</SelectItem>
                        <SelectItem value="USD">USD ($)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="text-xs text-muted-foreground">
                  Min: {currency === 'INR' ? '₹100' : '$2'} | Max:{' '}
                  {currency === 'INR' ? '₹1,00,000' : '$1,500'}
                </div>

                <div className="flex gap-2">
                  <Button type="submit" disabled={loading} className="flex-1">
                    {loading ? (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                        Processing...
                      </>
                    ) : (
                      <>
                        <CreditCard className="h-4 w-4 mr-2" />
                        Pay Now
                      </>
                    )}
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setShowAddForm(false)
                      setAmount('')
                      setError(null)
                    }}
                  >
                    Cancel
                  </Button>
                </div>
              </form>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
