'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 { Badge } from '@/components/ui/badge'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
  History,
  RefreshCw,
  ArrowUpCircle,
  ArrowDownCircle,
  ChevronLeft,
  ChevronRight,
  Filter,
} from 'lucide-react'
import { formatCurrency } from '@/lib/balance-service'

interface Transaction {
  _id: string
  transactionId: string
  type: 'debit' | 'credit'
  amount: number
  service: string
  serviceId?: string
  description?: string
  status: 'pending' | 'completed' | 'failed'
  previousBalance: number
  newBalance: number
  createdAt: string
  updatedAt: string
}

interface TransactionHistoryProps {
  className?: string
  showFilters?: boolean
  maxHeight?: string
}

export function TransactionHistory({
  className = '',
  showFilters = true,
  maxHeight = '400px',
}: TransactionHistoryProps) {
  const { user } = useAuth()
  const [transactions, setTransactions] = useState<Transaction[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [typeFilter, setTypeFilter] = useState<'all' | 'debit' | 'credit'>('all')
  const [serviceFilter, setServiceFilter] = useState('all')

  const fetchTransactions = async (pageNum: number = 1, reset: boolean = false) => {
    if (!user) return

    setLoading(true)
    setError(null)

    try {
      const params = new URLSearchParams({
        page: pageNum.toString(),
        limit: '10',
        type: typeFilter,
      })

      if (serviceFilter && serviceFilter !== 'all') {
        params.append('service', serviceFilter)
      }

      const response = await fetch(`/api/transactions?${params}`, {
        credentials: 'include',
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error?.message || 'Failed to fetch transactions')
      }

      if (data.success) {
        if (reset) {
          setTransactions(data.data.transactions)
        } else {
          setTransactions((prev) => [...prev, ...data.data.transactions])
        }
        setTotalPages(data.data.pagination.totalPages)
        setPage(pageNum)
      } else {
        throw new Error(data.error?.message || 'Failed to fetch transactions')
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch transactions'
      setError(errorMessage)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTransactions(1, true)
  }, [user, typeFilter, serviceFilter])

  const handleRefresh = () => {
    setPage(1)
    fetchTransactions(1, true)
  }

  const handleLoadMore = () => {
    if (page < totalPages) {
      fetchTransactions(page + 1, false)
    }
  }

  const getTransactionIcon = (type: string) => {
    return type === 'credit' ? (
      <ArrowUpCircle className="h-4 w-4 text-green-600" />
    ) : (
      <ArrowDownCircle className="h-4 w-4 text-red-600" />
    )
  }

  const getStatusBadge = (status: string) => {
    const variants = {
      completed: 'default',
      pending: 'secondary',
      failed: 'destructive',
    } as const

    return (
      <Badge variant={variants[status as keyof typeof variants] || 'secondary'}>{status}</Badge>
    )
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-IN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  if (!user) {
    return null
  }

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

      {showFilters && (
        <CardContent className="pb-4">
          <div className="flex gap-2">
            <Select
              value={typeFilter}
              onValueChange={(value: 'all' | 'debit' | 'credit') => setTypeFilter(value)}
            >
              <SelectTrigger className="w-32">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="debit">Debits</SelectItem>
                <SelectItem value="credit">Credits</SelectItem>
              </SelectContent>
            </Select>

            <Select value={serviceFilter} onValueChange={setServiceFilter}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="All Services" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Services</SelectItem>
                <SelectItem value="VPS">VPS Server</SelectItem>
                <SelectItem value="Kubernetes">Kubernetes</SelectItem>
                <SelectItem value="Balance">Balance Top-up</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      )}

      <CardContent className="pt-0">
        {error && (
          <Alert variant="destructive" className="mb-4">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <div className="space-y-3 overflow-y-auto" style={{ maxHeight }}>
          {transactions.length === 0 && !loading ? (
            <div className="text-center py-8 text-muted-foreground">
              <History className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>No transactions found</p>
              <p className="text-sm">Your transaction history will appear here</p>
            </div>
          ) : (
            transactions.map((transaction) => (
              <div
                key={transaction._id}
                className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 transition-colors"
              >
                <div className="flex items-center space-x-3">
                  {getTransactionIcon(transaction.type)}
                  <div>
                    <div className="font-medium text-sm">
                      {transaction.description || transaction.service}
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {formatDate(transaction.createdAt)}
                    </div>
                    {transaction.serviceId && (
                      <div className="text-xs text-muted-foreground">
                        ID: {transaction.serviceId}
                      </div>
                    )}
                  </div>
                </div>

                <div className="text-right">
                  <div
                    className={`font-medium ${
                      transaction.type === 'credit' ? 'text-green-600' : 'text-red-600'
                    }`}
                  >
                    {transaction.type === 'credit' ? '+' : '-'}
                    {formatCurrency(transaction.amount)}
                  </div>
                  {/* <div className="text-xs text-muted-foreground">Balance: {formatCurrency(transaction.newBalance)}</div> */}
                  <div className="mt-1">{getStatusBadge(transaction.status)}</div>
                </div>
              </div>
            ))
          )}

          {loading && (
            <div className="text-center py-4">
              <RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2" />
              <p className="text-sm text-muted-foreground">Loading transactions...</p>
            </div>
          )}

          {page < totalPages && !loading && (
            <div className="text-center pt-4">
              <Button variant="outline" onClick={handleLoadMore} disabled={loading}>
                Load More
              </Button>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}
