'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';

/* ─── Intro Typewriter ───────────────────────────────────── */
function Intro({ onDone }: { onDone: () => void }) {
  const [text, setText] = useState('');
  const [phase, setPhase] = useState<'typing' | 'blink'>('typing');
  const fullText = 'Welcome to US Floral';

  useEffect(() => {
    let idx = 0;
    const t = setInterval(() => {
      idx++;
      setText(fullText.slice(0, idx));
      if (idx >= fullText.length) {
        clearInterval(t);
        setPhase('blink');
        setTimeout(() => onDone(), 1400);
      }
    }, 65);
    return () => clearInterval(t);
  }, [onDone]);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'linear-gradient(135deg, #1c5236 0%, #0d291b 60%, #2b7a50 100%)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      animation: phase === 'blink' ? 'irisClose 0.65s ease-in forwards' : 'fadeIn 0.4s ease',
    }}>
      <div style={{ position: 'absolute', width: '600px', height: '600px', borderRadius: '50%', border: '1px solid rgba(255,255,255,0.05)', animation: 'pulse 4s ease-in-out infinite' }} />
      <div style={{ position: 'absolute', width: '400px', height: '400px', borderRadius: '50%', border: '1px solid rgba(255,255,255,0.08)', animation: 'pulse 4s ease-in-out 1s infinite' }} />
      <div style={{ width: '120px', height: '120px', borderRadius: '50%', overflow: 'hidden', border: '4px solid rgba(255,255,255,0.3)', boxShadow: '0 0 60px rgba(209,107,118,0.4)', marginBottom: '2.5rem', animation: 'fadeInUp 0.8s ease 0.2s both' }}>
        <Image src="/logo_a.jpg" alt="US Floral" width={120} height={120} style={{ objectFit: 'cover', width: '100%', height: '100%' }} />
      </div>
      <h1 style={{ color: 'white', fontSize: '2.75rem', fontWeight: 800, letterSpacing: '-0.02em', textShadow: '0 0 40px rgba(255,255,255,0.2)', minHeight: '4rem', animation: 'fadeInUp 0.6s ease 0.5s both' }}>
        {text}
        <span style={{ display: 'inline-block', width: '3px', height: '3.2rem', background: 'rgba(209,107,118,0.9)', marginLeft: '4px', verticalAlign: 'middle', borderRadius: '2px', animation: 'blink 0.7s step-end infinite' }} />
      </h1>
      <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '1rem', marginTop: '1rem', letterSpacing: '0.2em', textTransform: 'uppercase', fontWeight: 500, animation: 'fadeInUp 0.6s ease 0.9s both' }}>
        Sistema de Gestión
      </p>
      <style>{`
        @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0} }
        @keyframes pulse { 0%,100%{transform:scale(1);opacity:.5} 50%{transform:scale(1.05);opacity:1} }
        @keyframes fadeIn { from{opacity:0} to{opacity:1} }
        @keyframes fadeInUp { from{opacity:0;transform:translateY(20px)} to{opacity:1;transform:translateY(0)} }
        @keyframes irisClose { 0%{clip-path:ellipse(100% 100% at 50% 50%);opacity:1} 100%{clip-path:ellipse(0% 0% at 50% 50%);opacity:0} }
      `}</style>
    </div>
  );
}

/* ─── Login Success Bloom ───────────────────────────────── */
function LoginBloom() {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'linear-gradient(135deg, #1c5236 0%, #0d291b 60%, #2b7a50 100%)',
      animation: 'bloomExpand 0.9s cubic-bezier(0.4, 0, 0.2, 1) forwards',
    }}>
      <div style={{ textAlign: 'center', animation: 'fadeInUp 0.4s ease 0.2s both' }}>
        <div style={{ width: '80px', height: '80px', borderRadius: '50%', overflow: 'hidden', border: '3px solid rgba(255,255,255,0.4)', margin: '0 auto 1rem' }}>
          <Image src="/logo_a.jpg" alt="" width={80} height={80} style={{ objectFit: 'cover', width: '100%', height: '100%' }} />
        </div>
        <p style={{ color: 'white', fontWeight: 700, fontSize: '1.1rem', letterSpacing: '0.05em' }}>¡Bienvenido!</p>
      </div>
      <style>{`
        @keyframes bloomExpand {
          0%   { clip-path: circle(0% at 50% 50%); opacity: 1; }
          60%  { clip-path: circle(100% at 50% 50%); opacity: 1; }
          100% { clip-path: circle(100% at 50% 50%); opacity: 0; }
        }
        @keyframes fadeInUp { from{opacity:0;transform:translateY(20px)} to{opacity:1;transform:translateY(0)} }
      `}</style>
    </div>
  );
}

/* ─── Login Page ──────────────────────────────────────────── */
export default function LoginPage() {
  const [showIntro, setShowIntro] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [showBloom, setShowBloom] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const seen = sessionStorage.getItem('intro-seen');
    if (!seen) {
      setShowIntro(true);
    } else {
      setShowLogin(true);
    }
  }, []);

  const handleIntroDone = () => {
    sessionStorage.setItem('intro-seen', '1');
    setShowIntro(false);
    setTimeout(() => setShowLogin(true), 150);
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      });

      const data = await res.json();

      if (res.ok) {
        setShowBloom(true);
        if (data.user) {
          localStorage.setItem('usf_user', JSON.stringify(data.user));
          if (data.user.role === 'FARM') {
            localStorage.setItem('usf_farm_user', JSON.stringify(data.user));
          }
        }
        const targetUrl = data.user?.redirectUrl || (data.user?.role === 'FARM' ? '/pedidos' : '/dashboard');
        // Give bloom animation time to play, then navigate to role-specific route
        setTimeout(() => { window.location.href = targetUrl; }, 950);
      } else {
        setError(data.error || 'Usuario o contraseña incorrectos');
        setLoading(false);
      }
    } catch {
      setError('Error de conexión. Intenta de nuevo.');
      setLoading(false);
    }
  };

  return (
    <>
      {showIntro && <Intro onDone={handleIntroDone} />}
      {showBloom && <LoginBloom />}

      <div className="auth-container" style={{ opacity: showLogin ? 1 : 0, transition: 'opacity 0.5s ease' }}>
        {/* Decorative blobs */}
        <div style={{ position: 'fixed', top: '-10%', right: '-5%', width: '400px', height: '400px', borderRadius: '50%', background: 'radial-gradient(circle, rgba(209,107,118,0.3) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ position: 'fixed', bottom: '-10%', left: '-5%', width: '500px', height: '500px', borderRadius: '50%', background: 'radial-gradient(circle, rgba(41,119,80,0.4) 0%, transparent 70%)', pointerEvents: 'none' }} />

        <div className="auth-card" style={{ transform: showLogin ? 'translateY(0) scale(1)' : 'translateY(30px) scale(0.95)', transition: 'transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)' }}>
          {/* Logo */}
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '1.5rem' }}>
            <div style={{ backgroundColor: 'white', borderRadius: '50%', padding: '6px', display: 'flex', alignItems: 'center', justifyContent: 'center', width: '110px', height: '110px', boxShadow: '0 8px 30px rgba(28,82,54,0.25)' }}>
              <Image src="/logo_a.jpg" alt="US Floral Logo" width={96} height={96} style={{ objectFit: 'cover', borderRadius: '50%' }} />
            </div>
          </div>

          <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
            <h1 style={{ fontSize: '1.75rem', marginBottom: '0.25rem', color: 'var(--primary-color)' }}>US Floral</h1>
            <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', fontWeight: 500 }}>Sistema de Gestión • Inicia Sesión</p>
          </div>

          {error && (
            <div style={{ background: 'rgba(225,29,72,0.08)', border: '1px solid rgba(225,29,72,0.25)', borderRadius: 'var(--radius-md)', padding: '0.875rem 1rem', marginBottom: '1.25rem', color: 'var(--danger-color)', fontSize: '0.875rem', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
              {error}
            </div>
          )}

          <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
            <div>
              <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.5rem', color: 'var(--primary-color)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Usuario o Correo Electrónico</label>
              <input type="text" placeholder="Ingresa tu correo o usuario" value={username} onChange={e => setUsername(e.target.value)} required />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.5rem', color: 'var(--primary-color)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Contraseña</label>
              <input type="password" placeholder="Ingresa tu contraseña" value={password} onChange={e => setPassword(e.target.value)} required />
            </div>
            <button type="submit" className="btn-primary" disabled={loading || showBloom} style={{ width: '100%', marginTop: '0.5rem', padding: '1rem', fontSize: '1rem' }}>
              {loading ? (
                <><svg style={{ animation: 'spin 1s linear infinite' }} width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>Verificando...</>
              ) : (
                <><svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1" /></svg>Ingresar al Sistema</>
              )}
            </button>
          </form>
          <p style={{ textAlign: 'center', marginTop: '1.75rem', fontSize: '0.75rem', color: 'var(--text-secondary)' }}>US Floral © {new Date().getFullYear()} — Sistema Interno</p>
        </div>
        <style>{`@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }`}</style>
      </div>
    </>
  );
}
