import React, { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Delete, Loader2, Check } from 'lucide-react'
import api from '../axios'

const ease = [0.22, 1, 0.36, 1]

export default function PinPad({ open, mode = 'verify', onSuccess, onClose }) {
    const [pin, setPin] = useState('')
    const [confirmPin, setConfirmPin] = useState('')
    const [stage, setStage] = useState('enter')
    const [error, setError] = useState('')
    const [loading, setLoading] = useState(false)
    const [shake, setShake] = useState(false)
    const [success, setSuccess] = useState(false)

    useEffect(() => {
        if (open) {
            setPin(''); setConfirmPin(''); setStage('enter')
            setError(''); setShake(false); setSuccess(false)
        }
    }, [open])

    const active = stage === 'enter' ? pin : confirmPin
    const setActive = stage === 'enter' ? setPin : setConfirmPin

    const triggerError = (msg) => {
        setError(msg)
        setShake(true)
        setTimeout(() => setShake(false), 500)
    }

    const press = (digit) => {
        if (active.length >= 4 || loading || success) return
        setError('')
        const next = active + digit
        setActive(next)
        if (next.length === 4) handleComplete(next)
    }

    const backspace = () => { setError(''); setActive(active.slice(0, -1)) }

    const finishSuccess = (cb) => {
        setSuccess(true)
        setTimeout(() => cb(), 700)
    }

    const handleComplete = async (value) => {
        if (mode === 'set') {
            if (stage === 'enter') {
                setTimeout(() => setStage('confirm'), 200)
                return
            }
            if (value !== pin) {
                triggerError("PINs don't match")
                setTimeout(() => { setPin(''); setConfirmPin(''); setStage('enter') }, 600)
                return
            }
            setLoading(true)
            try {
                await api.post('/pin/set', { pin: value })
                setLoading(false)
                finishSuccess(() => onSuccess(value))
            } catch (e) {
                setLoading(false)
                triggerError('Could not set PIN. Try again.')
                setPin(''); setConfirmPin(''); setStage('enter')
            }
            return
        }

        // verify mode
        setLoading(true)
        try {
            await api.post('/pin/verify', { pin: value })
            setLoading(false)
            finishSuccess(() => onSuccess(value))
        } catch (e) {
            setLoading(false)
            triggerError('Incorrect PIN')
            setTimeout(() => setPin(''), 500)
        }
    }

    const title = success
        ? (mode === 'set' ? 'PIN set!' : 'Verified!')
        : mode === 'set'
            ? (stage === 'enter' ? 'Create a 4-digit PIN' : 'Confirm your PIN')
            : 'Enter your PIN'

    const dotColor = (filled) => {
        if (error) return { background: 'var(--bad)', borderColor: 'transparent' }
        if (success) return { background: 'var(--ok)', borderColor: 'transparent' }
        return filled ? { background: 'var(--accent)', borderColor: 'transparent' } : {}
    }

    return (
        <AnimatePresence>
            {open && (
                <motion.div
                    initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                    className="fixed inset-0 bg-black/60 flex items-end sm:items-center justify-center z-[60] p-4"
                >
                    <motion.div
                        initial={{ y: 40, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 40, opacity: 0 }}
                        transition={{ duration: 0.4, ease }}
                        className="bg-surface border border-line rounded-3xl p-6 w-full max-w-[360px] card-shadow-lg"
                    >
                        <div className="flex items-center justify-between mb-6">
                            <h3 className={`text-[16px] font-semibold ${success ? 'text-ok' : 'text-txt'}`}>{title}</h3>
                            {!success && <button onClick={onClose} className="text-txt-3"><X size={20} /></button>}
                        </div>

                        {success ? (
                            <motion.div
                                initial={{ scale: 0 }} animate={{ scale: 1 }}
                                transition={{ type: 'spring', stiffness: 300, damping: 18 }}
                                className="flex justify-center py-6"
                            >
                                <div className="w-16 h-16 rounded-full bg-ok/15 flex items-center justify-center">
                                    <Check size={32} className="text-ok" />
                                </div>
                            </motion.div>
                        ) : (
                            <>
                                {/* PIN dots with shake */}
                                <motion.div
                                    animate={shake ? { x: [0, -10, 10, -8, 8, -4, 4, 0] } : { x: 0 }}
                                    transition={{ duration: 0.5 }}
                                    className="flex justify-center gap-4 mb-2"
                                >
                                    {[0, 1, 2, 3].map(i => (
                                        <div
                                            key={i}
                                            className={`w-4 h-4 rounded-full border-2 transition-all ${i < active.length || error ? 'border-transparent' : 'border-line'}`}
                                            style={dotColor(i < active.length)}
                                        />
                                    ))}
                                </motion.div>

                                <div className="h-6 text-center flex items-center justify-center">
                                    {error && <p className="text-bad text-[12px] font-medium">{error}</p>}
                                    {loading && <Loader2 size={16} className="animate-spin text-accent" />}
                                </div>

                                {/* Keypad */}
                                <div className="grid grid-cols-3 gap-3 mt-2">
                                    {[1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => (
                                        <motion.button
                                            key={n}
                                            whileTap={{ scale: 0.92 }}
                                            onClick={() => press(String(n))}
                                            disabled={loading}
                                            className="bg-raised text-txt text-[22px] font-semibold rounded-2xl py-4 transition-all"
                                        >
                                            {n}
                                        </motion.button>
                                    ))}
                                    <div />
                                    <motion.button
                                        whileTap={{ scale: 0.92 }}
                                        onClick={() => press('0')}
                                        disabled={loading}
                                        className="bg-raised text-txt text-[22px] font-semibold rounded-2xl py-4"
                                    >
                                        0
                                    </motion.button>
                                    <motion.button
                                        whileTap={{ scale: 0.92 }}
                                        onClick={backspace}
                                        disabled={loading}
                                        className="text-txt-2 rounded-2xl py-4 flex items-center justify-center"
                                    >
                                        <Delete size={22} />
                                    </motion.button>
                                </div>
                            </>
                        )}
                    </motion.div>
                </motion.div>
            )}
        </AnimatePresence>
    )
}