import React, { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { Eye, EyeOff, ArrowRight, ArrowLeft, Check, Sun, Moon } from 'lucide-react'
import api from '../axios'
import Mascot from '../components/Mascot'
import useStore from '../store/useStore'

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

const steps = [
    { key: 'name', label: "What's your name?", field: 'name', type: 'text', auto: 'name' },
    { key: 'contact', label: 'How can we reach you?', field: 'email', type: 'email', auto: 'email' },
    { key: 'password', label: 'Secure your account', field: 'password', type: 'password', auto: 'new-password' },
]

export default function Register() {
    const navigate = useNavigate()
    const { theme, toggleTheme } = useStore()
    const [step, setStep] = useState(0)
    const [form, setForm] = useState({ name: '', email: '', phone: '', password: '', password_confirmation: '' })
    const [errors, setErrors] = useState({})
    const [loading, setLoading] = useState(false)
    const [showPassword, setShowPassword] = useState(false)
    const [focusField, setFocusField] = useState(null)
    const [done, setDone] = useState(false)

    const current = steps[step]

    const mascotMode =
        done ? 'happy'
        : Object.keys(errors).length > 0 ? 'worried'
        : focusField === 'password' ? (showPassword ? 'peek' : 'covered')
        : focusField && form[focusField]?.length > 0 ? 'typing'
        : 'idle'

    const typedLength = focusField ? (form[focusField]?.length || 0) : 0

    const handleChange = (e) => {
        setForm({ ...form, [e.target.name]: e.target.value })
        setErrors({})
    }

    const canProceed = () => {
        if (step === 0) return form.name.trim().length >= 2
        if (step === 1) return form.email.includes('@') && form.phone.length >= 11
        if (step === 2) return form.password.length >= 6 && form.password === form.password_confirmation
        return false
    }

    const next = () => {
        if (step < steps.length - 1) setStep(step + 1)
        else handleSubmit()
    }

    const back = () => {
        if (step > 0) setStep(step - 1)
        setErrors({})
    }

    const handleSubmit = async () => {
        if (loading) return
        setLoading(true)
        setErrors({})
        try {
            const res = await api.post('/register', form)
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('user', JSON.stringify(res.data.user))
            setDone(true)
            setTimeout(() => navigate('/dashboard'), 1300)
        } 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)
                if (flat.name) setStep(0)
                else if (flat.email || flat.phone) setStep(1)
                else if (flat.password) setStep(2)
            } else {
                setErrors({ general: 'Something went wrong. Try again.' })
            }
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="min-h-screen bg-bg flex flex-col items-center justify-center p-6 relative">
            <button
                onClick={toggleTheme}
                className="absolute top-6 right-6 w-10 h-10 rounded-full 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.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, ease }}
                className="w-full max-w-[400px]"
            >
                <div className="text-center mb-8">
                    <span className="text-txt text-[24px] font-bold tracking-tight">Fargo</span>
                    <span className="text-accent text-[24px] font-bold tracking-tight">Topup</span>
                </div>

                <div className="bg-surface border border-line rounded-3xl p-8 card-shadow-lg">
                    <Mascot mode={mascotMode} typedLength={typedLength} />

                    {!done && (
                        <div className="flex justify-center gap-2 mt-5 mb-6">
                            {steps.map((_, i) => (
                                <motion.div
                                    key={i}
                                    animate={{
                                        width: i === step ? 24 : 7,
                                        backgroundColor: i <= step ? 'var(--accent)' : 'var(--line)',
                                    }}
                                    transition={transition}
                                    className="h-[7px] rounded-full"
                                />
                            ))}
                        </div>
                    )}

                    {done ? (
                        <motion.div
                            initial={{ opacity: 0, scale: 0.95 }}
                            animate={{ opacity: 1, scale: 1 }}
                            transition={transition}
                            className="text-center py-4"
                        >
                            <div className="w-14 h-14 rounded-full bg-ok/15 flex items-center justify-center mx-auto mb-4">
                                <Check size={28} className="text-ok" />
                            </div>
                            <p className="text-txt text-[17px] font-semibold">You're in!</p>
                            <p className="text-txt-3 text-[13px] mt-1">Taking you to your dashboard…</p>
                        </motion.div>
                    ) : (
                        <>
                            <AnimatePresence mode="wait">
                                <motion.div
                                    key={step}
                                    initial={{ opacity: 0, x: 24 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    exit={{ opacity: 0, x: -24 }}
                                    transition={transition}
                                >
                                    <h2 className="text-txt text-[18px] font-semibold mb-5 text-center">
                                        {current.label}
                                    </h2>

                                    <input
                                        name={current.field}
                                        type={current.field === 'password' ? (showPassword ? 'text' : 'password') : current.type}
                                        autoComplete={current.auto}
                                        value={form[current.field]}
                                        onChange={handleChange}
                                        onFocus={() => setFocusField(current.field)}
                                        onBlur={() => setFocusField(null)}
                                        onKeyDown={e => e.key === 'Enter' && canProceed() && next()}
                                        autoFocus
                                        placeholder={step === 0 ? 'Your full name' : step === 1 ? 'you@email.com' : 'Create a password'}
                                        className={`glow-focus w-full bg-raised text-txt text-[15px] rounded-xl px-4 py-3.5 border outline-none transition-all
                                            ${errors[current.field] ? 'border-bad' : 'border-line'}`}
                                    />
                                    {errors[current.field] && <p className="text-bad text-[12px] mt-1.5">{errors[current.field]}</p>}

                                    {step === 1 && (
                                        <>
                                            <input
                                                name="phone"
                                                type="tel"
                                                autoComplete="tel"
                                                placeholder="08012345678"
                                                value={form.phone}
                                                onChange={handleChange}
                                                onFocus={() => setFocusField('phone')}
                                                onBlur={() => setFocusField(null)}
                                                onKeyDown={e => e.key === 'Enter' && canProceed() && next()}
                                                className={`glow-focus w-full bg-raised text-txt text-[15px] rounded-xl px-4 py-3.5 border outline-none transition-all mt-3
                                                    ${errors.phone ? 'border-bad' : 'border-line'}`}
                                            />
                                            {errors.phone && <p className="text-bad text-[12px] mt-1.5">{errors.phone}</p>}
                                        </>
                                    )}

                                    {step === 2 && (
                                        <>
                                            <div className="relative mt-3">
                                                <input
                                                    name="password_confirmation"
                                                    type={showPassword ? 'text' : 'password'}
                                                    autoComplete="new-password"
                                                    placeholder="Confirm password"
                                                    value={form.password_confirmation}
                                                    onChange={handleChange}
                                                    onFocus={() => setFocusField('password')}
                                                    onBlur={() => setFocusField(null)}
                                                    onKeyDown={e => e.key === 'Enter' && canProceed() && next()}
                                                    className="glow-focus w-full bg-raised text-txt text-[15px] rounded-xl pl-4 pr-12 py-3.5 border border-line outline-none transition-all"
                                                />
                                                <button
                                                    type="button"
                                                    onMouseDown={e => e.preventDefault()}
                                                    onClick={() => setShowPassword(!showPassword)}
                                                    className="absolute right-4 top-1/2 -translate-y-1/2 text-txt-3"
                                                >
                                                    {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                                </button>
                                            </div>
                                            {form.password && form.password_confirmation && form.password !== form.password_confirmation && (
                                                <p className="text-bad text-[12px] mt-1.5">Passwords don't match</p>
                                            )}
                                        </>
                                    )}
                                </motion.div>
                            </AnimatePresence>

                            {errors.general && <p className="text-bad text-[12px] mt-3 text-center">{errors.general}</p>}

                            <div className="flex gap-3 mt-6">
                                {step > 0 && (
                                    <motion.button
                                        whileTap={{ scale: 0.97 }}
                                        onClick={back}
                                        className="bg-raised border border-line text-txt-2 rounded-xl px-5 py-3.5 flex items-center justify-center"
                                    >
                                        <ArrowLeft size={18} />
                                    </motion.button>
                                )}
                                <motion.button
                                    whileTap={{ scale: 0.98 }}
                                    onClick={next}
                                    disabled={!canProceed() || loading}
                                    className="flex-1 text-white font-semibold text-[15px] rounded-xl py-3.5 flex items-center justify-center gap-2 transition-all disabled:opacity-40"
                                    style={{ background: 'var(--accent)' }}
                                >
                                    {loading ? 'Creating…'
                                        : step === steps.length - 1 ? <>Create account <Check size={17} /></>
                                        : <>Continue <ArrowRight size={17} /></>}
                                </motion.button>
                            </div>
                        </>
                    )}
                </div>

                {!done && (
                    <p className="text-center text-txt-3 text-[14px] mt-6">
                        Already have an account?{' '}
                        <Link to="/login" className="text-accent font-semibold">Sign in</Link>
                    </p>
                )}
            </motion.div>
        </div>
    )
}