import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { ArrowLeft, Check, X, Loader2, Copy, Zap } from 'lucide-react'
import api from '../axios'
import PinPad from '../components/PinPad'

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

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

export default function Electricity() {
    const navigate = useNavigate()
    const [step, setStep] = useState(1)
    const [discos, setDiscos] = useState([])
    const [disco, setDisco] = useState(null)
    const [meterType, setMeterType] = useState('1')
    const [meterNumber, setMeterNumber] = useState('')
    const [phone, setPhone] = useState('')
    const [amount, setAmount] = useState('')
    const [customerName, setCustomerName] = useState('')
    const [verifying, setVerifying] = useState(false)
    const [verifyError, setVerifyError] = useState('')
    const [processing, setProcessing] = useState(false)
    const [result, setResult] = useState(null)
    const [resultMsg, setResultMsg] = useState('')
    const [token, setToken] = useState(null)
    const [copied, setCopied] = useState(false)
    const [balance, setBalance] = useState(0)
    const [showPin, setShowPin] = useState(false)
    const [pinMode, setPinMode] = useState('verify')

    useEffect(() => {
        api.get('/wallet').then(r => setBalance(Number(r.data.balance))).catch(() => {})
        api.get('/electricity/discos').then(r => setDiscos(r.data)).catch(() => {})
    }, [])

    const selectDisco = (d) => { setDisco(d); setStep(2) }

    const verifyMeter = async () => {
        if (meterNumber.length < 6) return
        setVerifying(true)
        setVerifyError('')
        try {
            const res = await api.post('/electricity/verify-meter', {
                disco: disco.id, meter_number: meterNumber, meter_type: meterType,
            })
            if (res.data.verified) {
                setCustomerName(res.data.customer_name)
                setStep(3)
            }
        } catch (e) {
            setVerifyError(e.response?.data?.message || 'Could not verify meter. Check the number.')
        } finally {
            setVerifying(false)
        }
    }

    const confirm = () => { if (amount >= 500 && phone.length >= 11) setStep(4) }

    const startPay = async () => {
        try {
            const res = await api.get('/pin/status')
            setPinMode(res.data.has_pin ? 'verify' : 'set')
            setShowPin(true)
        } catch (e) {
            setPinMode('verify')
            setShowPin(true)
        }
    }

    const buy = async () => {
        setShowPin(false)
        setProcessing(true)
        try {
            const res = await api.post('/electricity/pay', {
                disco: disco.id, meter_number: meterNumber, meter_type: meterType,
                amount: Number(amount), phone,
            })
            setResult(res.data.status === 'success' ? 'success' : 'failed')
            setResultMsg(res.data.message)
            setToken(res.data.token)
            if (res.data.status === 'success') setBalance(b => b - Number(amount))
        } catch (e) {
            setResult('failed')
            setResultMsg(e.response?.data?.message || 'Transaction failed. Try again.')
        } finally {
            setProcessing(false)
            setStep(5)
        }
    }

    const copyToken = () => {
        if (token) {
            navigator.clipboard.writeText(token)
            setCopied(true)
            setTimeout(() => setCopied(false), 1500)
        }
    }

    const reset = () => {
        setStep(1); setDisco(null); setMeterNumber(''); setPhone(''); setAmount('')
        setCustomerName(''); setResult(null); setResultMsg(''); setToken(null)
    }

    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={() => step > 1 && step < 5 ? setStep(step - 1) : 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">Electricity</h1>
                <span className="ml-auto text-txt-3 text-[13px] font-mono">₦{balance.toLocaleString()}</span>
            </motion.header>

            <div className="px-6">
                <AnimatePresence mode="wait">
                    {step === 1 && (
                        <motion.div key="s1" initial={{ opacity: 0, x: 24 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -24 }} transition={transition}>
                            <p className="text-txt-3 text-[11px] uppercase tracking-[0.14em] mb-4">Select provider</p>
                            <div className="space-y-2.5">
                                {discos.map(d => (
                                    <motion.button
                                        key={d.id}
                                        whileTap={{ scale: 0.98 }}
                                        onClick={() => selectDisco(d)}
                                        className="w-full bg-surface border border-line rounded-2xl p-4 flex items-center gap-3 card-shadow"
                                    >
                                        <div className="w-10 h-10 rounded-xl bg-accent-soft flex items-center justify-center">
                                            <Zap size={18} className="text-accent" strokeWidth={1.8} />
                                        </div>
                                        <span className="text-txt text-[14px] font-medium">{d.name}</span>
                                    </motion.button>
                                ))}
                            </div>
                        </motion.div>
                    )}

                    {step === 2 && (
                        <motion.div key="s2" initial={{ opacity: 0, x: 24 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -24 }} transition={transition}>
                            <p className="text-txt-3 text-[11px] uppercase tracking-[0.14em] mb-4">{disco?.name}</p>

                            <div className="grid grid-cols-2 gap-3 mb-4">
                                {[{ v: '1', l: 'Prepaid' }, { v: '2', l: 'Postpaid' }].map(mt => (
                                    <button
                                        key={mt.v}
                                        onClick={() => setMeterType(mt.v)}
                                        className={`rounded-xl py-3 border text-[14px] font-medium transition-all
                                            ${meterType === mt.v ? 'bg-accent-soft border-accent text-accent' : 'bg-surface border-line text-txt-2'}`}
                                    >
                                        {mt.l}
                                    </button>
                                ))}
                            </div>

                            <label className="block text-txt-2 text-[13px] font-medium mb-2">Meter number</label>
                            <input
                                type="tel"
                                value={meterNumber}
                                onChange={e => { setMeterNumber(e.target.value.replace(/\D/g, '')); setVerifyError('') }}
                                placeholder="Enter meter number"
                                autoFocus
                                className={`glow-focus w-full bg-raised text-txt text-[16px] font-mono rounded-xl px-4 py-3.5 border outline-none transition-all
                                    ${verifyError ? 'border-bad' : 'border-line'}`}
                            />
                            {verifyError && <p className="text-bad text-[12px] mt-2">{verifyError}</p>}

                            <motion.button
                                whileTap={{ scale: 0.98 }}
                                onClick={verifyMeter}
                                disabled={meterNumber.length < 6 || verifying}
                                className="w-full text-white font-semibold text-[15px] rounded-xl py-3.5 mt-5 flex items-center justify-center gap-2 transition-all disabled:opacity-40"
                                style={{ background: 'var(--accent)' }}
                            >
                                {verifying ? <><Loader2 size={18} className="animate-spin" /> Verifying…</> : 'Verify meter'}
                            </motion.button>
                        </motion.div>
                    )}

                    {step === 3 && (
                        <motion.div key="s3" initial={{ opacity: 0, x: 24 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -24 }} transition={transition}>
                            <div className="bg-ok/10 border border-ok/20 rounded-2xl p-4 mb-5 flex items-center gap-3">
                                <Check size={18} className="text-ok" />
                                <div>
                                    <p className="text-txt-3 text-[11px]">Meter verified</p>
                                    <p className="text-txt text-[14px] font-medium">{customerName}</p>
                                </div>
                            </div>

                            <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="Amount (min 500)"
                                    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-4">
                                {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-[12px] font-medium card-shadow"
                                    >
                                        {q.toLocaleString()}
                                    </button>
                                ))}
                            </div>

                            <label className="block text-txt-2 text-[13px] font-medium mb-2">Phone (for receipt)</label>
                            <input
                                type="tel"
                                value={phone}
                                onChange={e => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
                                placeholder="08012345678"
                                className="glow-focus w-full bg-raised text-txt text-[16px] font-mono rounded-xl px-4 py-3.5 border border-line outline-none transition-all mb-5"
                            />

                            <motion.button
                                whileTap={{ scale: 0.98 }}
                                onClick={confirm}
                                disabled={amount < 500 || phone.length < 11}
                                className="w-full text-white font-semibold text-[15px] rounded-xl py-3.5 transition-all disabled:opacity-40"
                                style={{ background: 'var(--accent)' }}
                            >
                                Continue
                            </motion.button>
                        </motion.div>
                    )}

                    {step === 4 && (
                        <motion.div key="s4" initial={{ opacity: 0, x: 24 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -24 }} transition={transition}>
                            <p className="text-txt-3 text-[11px] uppercase tracking-[0.14em] mb-4">Confirm purchase</p>
                            <div className="bg-surface border border-line rounded-2xl p-5 space-y-4 card-shadow">
                                {[
                                    ['Provider', disco?.name],
                                    ['Customer', customerName],
                                    ['Meter', meterNumber],
                                    ['Type', meterType === '1' ? 'Prepaid' : 'Postpaid'],
                                    ['Amount', `₦${Number(amount).toLocaleString()}`],
                                ].map(([k, v]) => (
                                    <div key={k} className="flex justify-between items-center">
                                        <span className="text-txt-3 text-[13px]">{k}</span>
                                        <span className="text-txt text-[14px] font-medium text-right max-w-[60%]">{v}</span>
                                    </div>
                                ))}
                                <div className="border-t border-line-soft pt-4 flex justify-between items-center">
                                    <span className="text-txt-3 text-[13px]">Balance after</span>
                                    <span className="text-txt font-mono font-medium">₦{(balance - Number(amount)).toLocaleString()}</span>
                                </div>
                            </div>

                            {balance < Number(amount) ? (
                                <motion.button
                                    whileTap={{ scale: 0.98 }}
                                    onClick={() => navigate('/wallet')}
                                    className="w-full bg-bad text-white font-semibold text-[15px] rounded-xl py-3.5 mt-5"
                                >
                                    Insufficient balance — Fund wallet
                                </motion.button>
                            ) : (
                                <motion.button
                                    whileTap={{ scale: 0.98 }}
                                    onClick={startPay}
                                    disabled={processing}
                                    className="w-full text-white font-semibold text-[15px] rounded-xl py-3.5 mt-5 flex items-center justify-center gap-2 transition-all disabled:opacity-50"
                                    style={{ background: 'var(--accent)' }}
                                >
                                    {processing ? <><Loader2 size={18} className="animate-spin" /> Processing…</> : `Pay ₦${Number(amount).toLocaleString()}`}
                                </motion.button>
                            )}
                        </motion.div>
                    )}

                    {step === 5 && (
                        <motion.div key="s5" initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} transition={transition} className="text-center py-8">
                            <motion.div
                                initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ ...transition, delay: 0.1 }}
                                className={`w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-6 ${result === 'success' ? 'bg-ok/15' : 'bg-bad/15'}`}
                            >
                                {result === 'success' ? <Check size={40} className="text-ok" /> : <X size={40} className="text-bad" />}
                            </motion.div>
                            <h2 className="text-txt text-[20px] font-semibold mb-2">
                                {result === 'success' ? 'Purchase successful!' : 'Transaction failed'}
                            </h2>
                            <p className="text-txt-3 text-[14px] mb-6 px-6">{resultMsg}</p>

                            {result === 'success' && token && (
                                <div className="bg-surface border border-line rounded-2xl p-5 mb-6 mx-2 card-shadow">
                                    <p className="text-txt-3 text-[11px] uppercase tracking-[0.14em] mb-2">Your token</p>
                                    <div className="flex items-center justify-center gap-3">
                                        <span className="text-txt font-mono text-[20px] font-bold tracking-wide break-all">{token}</span>
                                        <button onClick={copyToken} className="text-accent flex-shrink-0">
                                            {copied ? <Check size={18} /> : <Copy size={18} />}
                                        </button>
                                    </div>
                                </div>
                            )}

                            <div className="space-y-3 px-2">
                                <motion.button
                                    whileTap={{ scale: 0.98 }}
                                    onClick={reset}
                                    className="w-full text-white font-semibold text-[15px] rounded-xl py-3.5 transition-all"
                                    style={{ background: 'var(--accent)' }}
                                >
                                    Buy again
                                </motion.button>
                                <button
                                    onClick={() => navigate('/dashboard')}
                                    className="w-full bg-surface border border-line text-txt-2 font-medium text-[15px] rounded-xl py-3.5 card-shadow"
                                >
                                    Back to dashboard
                                </button>
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        </div>
    )
}