import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Flower2 } from 'lucide-react'
import { login, register } from '../api/client'
import { useShop } from '../store/shop'
import { PetalLayer, Pressable } from './components/motion'
import { BRAND } from './brand'

export default function Account() {
  const [mode, setMode] = useState<'login' | 'register'>('login')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [err, setErr] = useState('')
  const [loading, setLoading] = useState(false)
  const { setCustToken } = useShop()
  const nav = useNavigate()

  const submit = async (e: React.FormEvent) => {
    e.preventDefault(); setErr(''); setLoading(true)
    try {
      const res = mode === 'login'
        ? await login(username, password)
        : await register(username, password, displayName || username)
      const token = res.data?.data?.token
      if (!token) throw new Error('no token')
      setCustToken(token)
      nav('/home')
    } catch {
      setErr(mode === 'login' ? 'Login failed — check your username and password.' : 'Sign-up failed — that username may already be taken.')
    } finally { setLoading(false) }
  }

  return (
    <div className="relative min-h-screen bg-gradient-to-br from-blush-100 via-cream to-sage-100 flex items-center justify-center px-4 overflow-hidden">
      <PetalLayer count={12} />
      <motion.form
        onSubmit={submit}
        initial={{ opacity: 0, y: 22 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
        className="relative z-10 w-full max-w-sm bg-white/90 backdrop-blur rounded-4xl shadow-bloom p-8 border border-blush-100">
        <Link to="/home" className="flex flex-col items-center gap-1 mb-6">
          <Flower2 className="text-blush-500" size={32} />
          <span className="font-serif text-xl font-bold text-blush-900">Montvale Florist</span>
        </Link>
        <div className="flex gap-2 mb-6 bg-blush-50 rounded-full p-1 text-sm">
          {(['login', 'register'] as const).map(m => (
            <button key={m} type="button" onClick={() => { setMode(m); setErr('') }}
              className={`flex-1 py-2 rounded-full font-medium transition-colors ${mode === m ? 'bg-blush-500 text-white shadow-petal' : 'text-blush-700'}`}>
              {m === 'login' ? 'Sign In' : 'Create Account'}
            </button>
          ))}
        </div>

        <label className="block text-xs text-blush-700 mb-1">Username</label>
        <input value={username} onChange={e => setUsername(e.target.value)} required
          className="w-full mb-3 px-3 py-2.5 rounded-2xl bg-blush-50 border border-blush-100 text-sm outline-none focus:border-blush-400" />
        {mode === 'register' && (<>
          <label className="block text-xs text-blush-700 mb-1">Name</label>
          <input value={displayName} onChange={e => setDisplayName(e.target.value)}
            className="w-full mb-3 px-3 py-2.5 rounded-2xl bg-blush-50 border border-blush-100 text-sm outline-none focus:border-blush-400" />
        </>)}
        <label className="block text-xs text-blush-700 mb-1">Password</label>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)} required
          className="w-full mb-4 px-3 py-2.5 rounded-2xl bg-blush-50 border border-blush-100 text-sm outline-none focus:border-blush-400" />
        {err && <p className="text-blush-500 text-xs mb-3">{err}</p>}
        <Pressable type="submit" disabled={loading}
          className="w-full py-2.5 rounded-full bg-blush-500 text-white font-semibold hover:bg-blush-600 disabled:opacity-60">
          {loading ? 'Please wait…' : (mode === 'login' ? 'Sign In' : 'Create Account')}
        </Pressable>
        <p className="text-center text-[11px] text-[#a08a90] mt-4">Store & owner staff → <a href="/admin/login" className="text-blush-600">Admin Console</a></p>
        <p className="text-center text-[11px] text-sage-600 mt-2">{BRAND.tagline}</p>
      </motion.form>
    </div>
  )
}
