import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { ArrowLeft, Wifi, Phone, Zap, Wallet as WalletIcon, RotateCcw } from 'lucide-react'
import api from '../../axios'

const spring = { type: 'spring', stiffness: 300, damping: 28 }

const FILTERS = ['all', 'success', 'failed', 'pending', 'refunded']

export default function AdminTransactions() {
    const navigate = useNavigate()
    const [transactions, setTransactions] = useState([])
    const [loading, setLoading] = useState(true)
    const [filter, setFilter] = useState('all')
    const [refunding, setRefunding] = useState(null)

    useEffect(() => { fetchTx() }, [filter])

    const fetchTx = async () => {
        setLoading(true)
        try {
            const url = filter === 'all' ? '/admin/transactions' : `/admin/transactions?status=${filter}`
            const res = await api.get(url)
            setTransactions(res.data.data || [])
        } catch (e) { console.error(e) }
        finally { setLoading(false) }
    }

    const refund = async (tx) => {
        setRefunding(tx.id)
        try {
            await api.post(`/admin/transactions/${tx.id}/refund`)
            fetchTx()
        } catch (e) {
            console.error(e)
            alert(e.response?.data?.message || 'Refund failed')
        } finally {
            setRefunding(null)
        }
    }

    const txIcon = t => t === 'data' ? Wifi : t === 'airtime' ? Phone : t === 'electricity' ? Zap : WalletIcon
    const stColor = s => s === 'success' ? 'text-ok' : s === 'failed' ? 'text-bad' : s === 'refunded' ? 'text-txt-2' : 'text-brass'
    const stBg = s => s === 'success' ? 'bg-ok/10' : s === 'failed' ? 'bg-bad/10' : 'bg-brass/10'

    return (
        <div className="min-h-screen bg-ink pb-12 max-w-[480px] mx-auto">
            {/* Header */}
            <motion.header
                initial={{ opacity: 0, y: -12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={spring}
                className="flex items-center gap-3 px-6 pt-7 pb-4"
            >
                <button
                    onClick={() => navigate('/admin')}
                    className="w-10 h-10 rounded-xl bg-surface border border-line flex items-center justify-center text-txt-2"
                >
                    <ArrowLeft size={18} />
                </button>
                <h1 className="text-txt text-[18px] font-semibold">All Transactions</h1>
            </motion.header>

            {/* Filters */}
            <div className="flex gap-2 px-6 mb-5 overflow-x-auto no-scrollbar">
                {FILTERS.map(f => (
                    <motion.button
                        key={f}
                        whileTap={{ scale: 0.95 }}
                        onClick={() => setFilter(f)}
                        className={`px-4 py-2 rounded-full text-[13px] font-medium whitespace-nowrap border transition-all
                            ${filter === f
                                ? 'bg-brass text-ink border-brass'
                                : 'bg-surface text-txt-2 border-line'}`}
                    >
                        {f.charAt(0).toUpperCase() + f.slice(1)}
                    </motion.button>
                ))}
            </div>

            <div className="px-6">
                {loading ? (
                    <div className="space-y-3">
                        {[1,2,3,4,5].map(i => <div key={i} className="shimmer h-20 rounded-2xl" />)}
                    </div>
                ) : transactions.length === 0 ? (
                    <div className="bg-surface border border-line rounded-2xl py-12 text-center">
                        <p className="text-txt-3 text-[14px]">No transactions found</p>
                    </div>
                ) : transactions.map((tx, i) => {
                    const Icon = txIcon(tx.type)
                    const canRefund = tx.status === 'pending' || tx.status === 'failed'
                    return (
                        <motion.div
                            key={tx.id}
                            initial={{ opacity: 0, y: 12 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ ...spring, delay: i * 0.03 }}
                            className="bg-surface border border-line rounded-2xl p-4 mb-3"
                        >
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className={`w-10 h-10 rounded-xl ${stBg(tx.status)} flex items-center justify-center`}>
                                        <Icon size={17} className={stColor(tx.status)} strokeWidth={1.8} />
                                    </div>
                                    <div>
                                        <p className="text-txt text-[13px] font-medium">{tx.user?.name || 'Unknown'}</p>
                                        <p className="text-txt-3 text-[11px] mt-0.5 capitalize">
                                            {tx.details?.size
                                                ? `${tx.details.network?.toUpperCase()} ${tx.details.size}`
                                                : tx.type.replace('_', ' ')}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-right">
                                    <p className="text-txt font-mono text-[14px] font-bold">
                                        ₦{Number(tx.amount).toLocaleString()}
                                    </p>
                                    <span className={`text-[10px] font-semibold uppercase ${stColor(tx.status)}`}>
                                        {tx.status}
                                    </span>
                                </div>
                            </div>

                            <div className="flex items-center justify-between mt-3 pt-3 border-t border-line-soft">
                                <span className="text-txt-3 text-[11px] font-mono">{tx.reference}</span>
                                {canRefund && (
                                    <motion.button
                                        whileTap={{ scale: 0.95 }}
                                        onClick={() => refund(tx)}
                                        disabled={refunding === tx.id}
                                        className="flex items-center gap-1.5 text-brass text-[12px] font-medium"
                                    >
                                        <RotateCcw size={13} />
                                        {refunding === tx.id ? 'Refunding…' : 'Refund'}
                                    </motion.button>
                                )}
                            </div>
                        </motion.div>
                    )
                })}
            </div>
        </div>
    )
}