import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { ArrowLeft, CreditCard, Building2, Check, Copy } from 'lucide-react'
import api from '../axios'
import { SkeletonWallet } from '../components/Skeleton'

const ease = [0.22, 1, 0.36, 1]
const transition = { duration: 0.4, ease }

const QUICK = [500, 1000, 2000, 5000]

export default function Wallet() {
    const navigate = useNavigate()
    const [balance, setBalance] = useState(0)
    const [loading, setLoading] = useState(true)
    const [method, setMethod] = useState('paystack')
    const [amount, setAmount] = useState('')
    const [submitting, setSubmitting] = useState(false)
    const [copied, setCopied] = useState(false)

    const bank = { name: 'Opay', account: '8012345678', holder: 'Fargo Topup' }

    useEffect(() => { fetchBalance() }, [])

    const fetchBalance = async () => {
        try {
            const res = await api.get('/wallet')
            setBalance(Number(res.data.balance))
        } catch (e) { console.error(e) }
        finally { setLoading(false) }
    }

    const handlePaystack = async () => {
        if (!amount || amount < 100 || submitting) return
        setSubmitting(true)
        try {
            const res = await api.post('/wallet/fund/paystack', { amount: Number(amount) })
            const { reference, amount: koboAmount, email, public_key } = res.data
            const handler = window.PaystackPop.setup({
                key: public_key,
                email,
                amount: koboAmount,
                ref: reference,
                callback: function () {
                    setTimeout(() => { fetchBalance(); setAmount('') }, 2000)
                },
                onClose: function () { setSubmitting(false) },
            })
            handler.openIframe()
        } catch (e) {
            console.error(e)
        } finally {
            setSubmitting(false)
        }
    }

    const copyAccount = () => {
        navigator.clipboard.writeText(bank.account)
        setCopied(true)
        setTimeout(() => setCopied(false), 1500)
    }

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

            <div className="px-6">
                {loading ? <SkeletonWallet /> : (
                    <motion.div
                        initial={{ opacity: 0, y: 16 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={transition}
                        className="rounded-3xl p-6 mb-6 relative overflow-hidden border"
                        style={{ background: 'var(--accent-soft)', borderColor: 'var(--txt)' }}
                    >
                        <p className="text-accent text-[11px] uppercase tracking-[0.14em] font-semibold">Current balance</p>
                        <p className="text-txt font-mono text-[30px] font-bold mt-2">
                            ₦{balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                        </p>
                    </motion.div>
                )}

                {/* Method toggle */}
                <div className="grid grid-cols-2 gap-3 mb-6">
                    {[
                        { key: 'paystack', label: 'Card / Instant', Icon: CreditCard },
                        { key: 'manual', label: 'Bank Transfer', Icon: Building2 },
                    ].map(({ key, label, Icon }) => (
                        <button
                            key={key}
                            onClick={() => setMethod(key)}
                            className={`rounded-2xl py-4 px-3 border flex flex-col items-center gap-2 transition-all card-shadow
                                ${method === key ? 'bg-accent-soft border-accent' : 'bg-surface border-line'}`}
                        >
                            <Icon size={20} className={method === key ? 'text-accent' : 'text-txt-3'} strokeWidth={1.8} />
                            <span className={`text-[12px] font-medium ${method === key ? 'text-accent' : 'text-txt-2'}`}>
                                {label}
                            </span>
                        </button>
                    ))}
                </div>

                <AnimatePresence mode="wait">
                    {method === 'paystack' ? (
                        <motion.div
                            key="paystack"
                            initial={{ opacity: 0, x: 20 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -20 }}
                            transition={transition}
                        >
                            <label className="block text-txt-2 text-[13px] font-medium mb-2">Amount</label>
                            <div className="relative mb-4">
                                <span className="absolute left-4 top-1/2 -translate-y-1/2 text-txt-2 text-[18px] font-mono">₦</span>
                                <input
                                    type="number"
                                    value={amount}
                                    onChange={e => setAmount(e.target.value)}
                                    placeholder="0"
                                    className="glow-focus w-full bg-raised text-txt text-[18px] font-mono rounded-xl pl-10 pr-4 py-3.5 border border-line outline-none transition-all"
                                />
                            </div>

                            <div className="grid grid-cols-4 gap-2 mb-6">
                                {QUICK.map(q => (
                                    <button
                                        key={q}
                                        onClick={() => setAmount(String(q))}
                                        className="bg-surface border border-line rounded-xl py-2.5 text-txt-2 text-[13px] font-medium card-shadow"
                                    >
                                        {q.toLocaleString()}
                                    </button>
                                ))}
                            </div>

                            <motion.button
                                whileTap={{ scale: 0.98 }}
                                onClick={handlePaystack}
                                disabled={!amount || amount < 100 || submitting}
                                className="w-full text-white font-semibold text-[15px] rounded-xl py-3.5 transition-all disabled:opacity-40"
                                style={{ background: 'var(--accent)' }}
                            >
                                {submitting ? 'Processing…' : `Pay ₦${Number(amount || 0).toLocaleString()}`}
                            </motion.button>
                            <p className="text-txt-3 text-[12px] text-center mt-3">Minimum ₦100 · Instant credit</p>
                        </motion.div>
                    ) : (
                        <motion.div
                            key="manual"
                            initial={{ opacity: 0, x: 20 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -20 }}
                            transition={transition}
                        >
                            <div className="bg-surface border border-line rounded-2xl p-5 mb-4 card-shadow">
                                <p className="text-txt-3 text-[12px] mb-4">Transfer to this account, then your wallet is credited after confirmation.</p>
                                <div className="space-y-3">
                                    <div className="flex justify-between items-center">
                                        <span className="text-txt-3 text-[13px]">Bank</span>
                                        <span className="text-txt text-[14px] font-medium">{bank.name}</span>
                                    </div>
                                    <div className="flex justify-between items-center">
                                        <span className="text-txt-3 text-[13px]">Account name</span>
                                        <span className="text-txt text-[14px] font-medium">{bank.holder}</span>
                                    </div>
                                    <div className="flex justify-between items-center">
                                        <span className="text-txt-3 text-[13px]">Account number</span>
                                        <button onClick={copyAccount} className="flex items-center gap-2 text-accent">
                                            <span className="font-mono text-[15px] font-bold">{bank.account}</span>
                                            {copied ? <Check size={15} /> : <Copy size={15} />}
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <p className="text-txt-3 text-[12px] text-center">
                                After transfer, send your receipt to support to get credited fast.
                            </p>
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        </div>
    )
}