import React, { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { Eye, EyeOff, ArrowRight, 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]

export default function Login() {
    const navigate = useNavigate()
    const { theme, toggleTheme } = useStore()
    const [form, setForm] = useState({ login: '', password: '' })
    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 mascotMode =
        done ? 'happy'
        : Object.keys(errors).length > 0 ? 'worried'
        : focusField === 'password' ? (showPassword ? 'peek' : 'covered')
        : focusField === 'login' && form.login.length > 0 ? 'typing'
        : 'idle'

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

    const handleSubmit = async () => {
        if (loading) return
        setLoading(true)
        setErrors({})
        try {
            const res = await api.post('/login', form)
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('user', JSON.stringify(res.data.user))
            setDone(true)
            setTimeout(() => navigate('/dashboard'), 800)
        } 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)
            } else if (err.response?.status === 403) {
                setErrors({ general: err.response.data.message })
            } else {
                setErrors({ general: 'Invalid credentials. Try again.' })
            }
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="min-h-screen bg-bg flex flex-col items-center justify-center p-6 relative">
            {/* Theme toggle */}
            <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]"
            >
                {/* Wordmark */}
                <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={form.login.length} />

                    <h2 className="text-txt text-[20px] font-semibold mt-5 mb-1 text-center">
                        Welcome back
                    </h2>
                    <p className="text-txt-3 text-[14px] text-center mb-6">
                        Sign in to continue
                    </p>

                    <AnimatePresence>
                        {errors.general && (
                            <motion.div
                                initial={{ opacity: 0, height: 0 }}
                                animate={{ opacity: 1, height: 'auto' }}
                                exit={{ opacity: 0, height: 0 }}
                                className="overflow-hidden"
                            >
                                <div className="text-bad text-[13px] bg-bad/8 border border-bad/20 rounded-xl px-4 py-3 mb-5">
                                    {errors.general}
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>

                    {/* Email or phone */}
                    <div className="mb-4">
                        <label className="block text-txt-2 text-[13px] font-medium mb-2">
                            Email or phone
                        </label>
                        <input
                            name="login"
                            type="text"
                            autoComplete="username"
                            value={form.login}
                            onChange={handleChange}
                            onFocus={() => setFocusField('login')}
                            onBlur={() => setFocusField(null)}
                            onKeyDown={e => e.key === 'Enter' && handleSubmit()}
                            className={`glow-focus w-full bg-raised text-txt text-[15px] rounded-xl px-4 py-3.5 border outline-none transition-all
                                ${errors.login ? 'border-bad' : 'border-line'}`}
                        />
                        {errors.login && <p className="text-bad text-[12px] mt-1.5">{errors.login}</p>}
                    </div>

                    {/* Password */}
                    <div className="mb-6">
                        <label className="block text-txt-2 text-[13px] font-medium mb-2">
                            Password
                        </label>
                        <div className="relative">
                            <input
                                name="password"
                                type={showPassword ? 'text' : 'password'}
                                autoComplete="current-password"
                                value={form.password}
                                onChange={handleChange}
                                onFocus={() => setFocusField('password')}
                                onBlur={() => setFocusField(null)}
                                onKeyDown={e => e.key === 'Enter' && handleSubmit()}
                                className={`glow-focus w-full bg-raised text-txt text-[15px] rounded-xl pl-4 pr-12 py-3.5 border outline-none transition-all
                                    ${errors.password ? 'border-bad' : 'border-line'}`}
                            />
                            <button
                                type="button"
                                onMouseDown={e => e.preventDefault()}
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute right-4 top-1/2 -translate-y-1/2 text-txt-3 hover:text-txt-2 transition-colors"
                            >
                                {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                            </button>
                        </div>
                        {errors.password && <p className="text-bad text-[12px] mt-1.5">{errors.password}</p>}
                    </div>

                    {/* Submit */}
                    <motion.button
                        whileTap={{ scale: 0.98 }}
                        onClick={handleSubmit}
                        disabled={loading || done}
                        className="w-full bg-accent hover:bg-accent-hover disabled:opacity-50 text-white font-semibold text-[15px] rounded-xl py-3.5 flex items-center justify-center gap-2 transition-colors"
                        style={{ background: 'var(--accent)' }}
                    >
                        {done ? 'Welcome!' : loading ? 'Signing in…' : <>Sign in <ArrowRight size={17} /></>}
                    </motion.button>
                </div>

                <p className="text-center text-txt-3 text-[14px] mt-6">
                    New here?{' '}
                    <Link to="/register" className="text-accent font-semibold">
                        Create an account
                    </Link>
                </p>
            </motion.div>
        </div>
    )
}