import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { ArrowLeft, Shield, LogOut, ChevronRight, Wallet as WalletIcon, Sun, Moon, Pencil, Check, X, Lock } from 'lucide-react'
import api from '../axios'
import useStore from '../store/useStore'
import Avatar, { AVATAR_IDS } from '../components/Avatars'
import PinPad from '../components/PinPad'

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

export default function Profile() {
    const navigate = useNavigate()
    const { theme, toggleTheme } = useStore()
    const [user, setUser] = useState(JSON.parse(localStorage.getItem('user') || '{}'))
    const [balance, setBalance] = useState(0)
    const [editing, setEditing] = useState(false)
    const [showAvatars, setShowAvatars] = useState(false)
    const [form, setForm] = useState({ name: '', email: '', phone: '' })
    const [saving, setSaving] = useState(false)
    const [errors, setErrors] = useState({})
    const [hasPin, setHasPin] = useState(false)
    const [showPin, setShowPin] = useState(false)

    useEffect(() => {
        api.get('/wallet').then(r => setBalance(Number(r.data.balance))).catch(() => {})
        api.get('/me').then(r => {
            setUser(r.data)
            localStorage.setItem('user', JSON.stringify(r.data))
            setForm({ name: r.data.name || '', email: r.data.email || '', phone: r.data.phone || '' })
        }).catch(() => {})

        api.get('/pin/status').then(r => setHasPin(r.data.has_pin)).catch(() => {})
    }, [])

    const saveProfile = async (extra = {}) => {
        setSaving(true)
        setErrors({})
        try {
            const payload = { ...form, ...extra }
            const res = await api.post('/profile/update', payload)
            setUser(res.data.user)
            localStorage.setItem('user', JSON.stringify(res.data.user))
            setEditing(false)
        } catch (err) {
            if (err.response?.status === 422) {
                const raw = err.response.data.errors
                const flat = {}
                Object.keys(raw).forEach(k => flat[k] = raw[k][0])
                setErrors(flat)
            }
        } finally {
            setSaving(false)
        }
    }

    const pickAvatar = async (id) => {
        setShowAvatars(false)
        await saveProfile({ avatar: id })
    }

    const logout = async () => {
        try { await api.post('/logout') } catch {}
        localStorage.clear()
        navigate('/login')
    }

    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 justify-between px-6 pt-7 pb-4"
            >
                <div className="flex items-center gap-3">
                    <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">Profile</h1>
                </div>
                <button
                    onClick={toggleTheme}
                    className="w-10 h-10 rounded-xl bg-surface border border-line card-shadow flex items-center justify-center text-txt-2"
                >
                    {theme === 'light' ? <Moon size={17} /> : <Sun size={17} />}
                </button>
            </motion.header>

            <div className="px-6">
                {/* Avatar + name card */}
                <motion.div
                    initial={{ opacity: 0, y: 16 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={transition}
                    className="bg-surface border border-line rounded-3xl p-6 mb-5 flex flex-col items-center text-center card-shadow"
                >
                    <button onClick={() => setShowAvatars(true)} className="relative">
                        <div className="w-20 h-20 rounded-full overflow-hidden border-2" style={{ borderColor: 'var(--accent)' }}>
                            <Avatar id={user?.avatar || 'fox'} size={80} />
                        </div>
                        <div className="absolute -bottom-1 -right-1 w-7 h-7 rounded-full flex items-center justify-center text-white" style={{ background: 'var(--accent)' }}>
                            <Pencil size={13} />
                        </div>
                    </button>
                    <p className="text-txt text-[18px] font-semibold mt-4">{user?.name}</p>
                    <p className="text-txt-3 text-[13px] mt-0.5">{user?.email}</p>
                </motion.div>

                {/* Wallet shortcut */}
                <motion.button
                    whileTap={{ scale: 0.98 }}
                    onClick={() => navigate('/wallet')}
                    className="w-full bg-surface border border-line rounded-2xl p-4 mb-5 flex items-center justify-between card-shadow"
                >
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: 'var(--accent-soft)' }}>
                            <WalletIcon size={18} className="text-accent" strokeWidth={1.8} />
                        </div>
                        <div className="text-left">
                            <p className="text-txt-3 text-[11px]">Wallet balance</p>
                            <p className="text-txt font-mono text-[16px] font-bold">₦{balance.toLocaleString()}</p>
                        </div>
                    </div>
                    <ChevronRight size={18} className="text-txt-3" />
                </motion.button>

                {/* Account details — editable */}
                <div className="flex items-center justify-between mb-3">
                    <p className="text-txt-3 text-[11px] uppercase tracking-[0.14em]">Account details</p>
                    {!editing ? (
                        <button onClick={() => setEditing(true)} className="text-accent text-[12px] font-semibold flex items-center gap-1">
                            <Pencil size={13} /> Edit
                        </button>
                    ) : (
                        <button onClick={() => { setEditing(false); setErrors({}) }} className="text-txt-3 text-[12px] font-semibold flex items-center gap-1">
                            <X size={13} /> Cancel
                        </button>
                    )}
                </div>

                <div className="bg-surface border border-line rounded-2xl p-4 mb-5 card-shadow space-y-4">
                    {[
                        { key: 'name', label: 'Full name', type: 'text' },
                        { key: 'email', label: 'Email', type: 'email' },
                        { key: 'phone', label: 'Phone', type: 'tel' },
                    ].map(({ key, label, type }) => (
                        <div key={key}>
                            <p className="text-txt-3 text-[11px] mb-1.5">{label}</p>
                            {editing ? (
                                <>
                                    <input
                                        type={type}
                                        value={form[key]}
                                        onChange={e => setForm({ ...form, [key]: e.target.value })}
                                        className={`glow-focus w-full bg-raised text-txt text-[14px] rounded-xl px-3 py-2.5 border outline-none transition-all
                                            ${errors[key] ? 'border-bad' : 'border-line'}`}
                                    />
                                    {errors[key] && <p className="text-bad text-[11px] mt-1">{errors[key]}</p>}
                                </>
                            ) : (
                                <p className="text-txt text-[14px] font-medium">{user?.[key] || '—'}</p>
                            )}
                        </div>
                    ))}

                    {editing && (
                        <motion.button
                            whileTap={{ scale: 0.98 }}
                            onClick={() => saveProfile()}
                            disabled={saving}
                            className="w-full text-white font-semibold text-[14px] rounded-xl py-3 flex items-center justify-center gap-2 transition-all disabled:opacity-50"
                            style={{ background: 'var(--accent)' }}
                        >
                            {saving ? 'Saving…' : <><Check size={16} /> Save changes</>}
                        </motion.button>
                    )}
                </div>
<motion.button
                    whileTap={{ scale: 0.98 }}
                    onClick={() => setShowPin(true)}
                    className="w-full bg-surface border border-line rounded-2xl p-4 mb-5 flex items-center justify-between card-shadow"
                >
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: 'var(--accent-soft)' }}>
                            <Lock size={18} className="text-accent" strokeWidth={1.8} />
                        </div>
                        <div className="text-left">
                            <p className="text-txt text-[14px] font-medium">Transaction PIN</p>
                            <p className="text-txt-3 text-[11px] mt-0.5">{hasPin ? 'Tap to change your PIN' : 'Set a PIN to secure purchases'}</p>
                        </div>
                    </div>
                    <ChevronRight size={18} className="text-txt-3" />
                </motion.button>
                {user?.role === 'admin' && (
                    <motion.button
                        whileTap={{ scale: 0.98 }}
                        onClick={() => navigate('/admin')}
                        className="w-full bg-surface border border-line rounded-2xl p-4 mb-5 flex items-center justify-between card-shadow"
                    >
                        <div className="flex items-center gap-3">
                            <Shield size={18} className="text-accent" strokeWidth={1.8} />
                            <span className="text-txt text-[14px] font-medium">Admin Panel</span>
                        </div>
                        <ChevronRight size={18} className="text-txt-3" />
                    </motion.button>
                )}

                <motion.button
                    whileTap={{ scale: 0.98 }}
                    onClick={logout}
                    className="w-full bg-bad/10 border border-bad/20 rounded-2xl p-4 flex items-center justify-center gap-2 text-bad font-medium text-[15px]"
                >
                    <LogOut size={18} /> Sign out
                </motion.button>
            </div>

            {/* Avatar picker modal */}
            <AnimatePresence>
                {showAvatars && (
                    <motion.div
                        initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                        onClick={() => setShowAvatars(false)}
                        className="fixed inset-0 bg-black/50 flex items-end sm:items-center justify-center z-50 p-4"
                    >
                        <motion.div
                            initial={{ y: 40, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 40, opacity: 0 }}
                            transition={transition}
                            onClick={e => e.stopPropagation()}
                            className="bg-surface border border-line rounded-3xl p-6 w-full max-w-[400px] card-shadow-lg"
                        >
                            <div className="flex items-center justify-between mb-5">
                                <h3 className="text-txt text-[16px] font-semibold">Choose your avatar</h3>
                                <button onClick={() => setShowAvatars(false)} className="text-txt-3"><X size={20} /></button>
                            </div>
                            <div className="grid grid-cols-4 gap-3">
                                {AVATAR_IDS.map(id => (
                                    <motion.button
                                        key={id}
                                        whileTap={{ scale: 0.9 }}
                                        onClick={() => pickAvatar(id)}
                                        className={`rounded-2xl p-1 border-2 transition-all ${user?.avatar === id ? 'border-accent' : 'border-transparent'}`}
                                    >
                                        <Avatar id={id} size={64} />
                                    </motion.button>
                                ))}
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            <PinPad
                open={showPin}
                mode="set"
                onClose={() => setShowPin(false)}
                onSuccess={() => { setShowPin(false); setHasPin(true) }}
            />
        </div>
    )
}