'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import { PawPrint, Eye, EyeOff, Mail, Lock, AlertCircle } from 'lucide-react';

export default function LoginPage() {
  const router = useRouter();
  const [showPass, setShowPass] = useState(false);
  const [email,    setEmail]    = useState('');
  const [password, setPassword] = useState('');
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState('');

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

    try {
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
      });

      if (result?.error) {
        setError('Email ou palavra-passe incorrectos. Tenta de novo.');
      } else {
        router.push('/');
        router.refresh();
      }
    } catch {
      setError('Erro de rede. Verifica a tua ligação e tenta de novo.');
    } finally {
      setLoading(false);
    }
  };

  const inputStyle: React.CSSProperties = {
    width:        '100%',
    padding:      '12px 16px 12px 40px',
    background:   'var(--color-bg, var(--cream))',
    border:       '1.5px solid var(--color-border, var(--parchment))',
    borderRadius: '10px',
    fontFamily:   'var(--font-body)',
    fontSize:     '15px',
    color:        'var(--color-text, var(--soil))',
    outline:      'none',
    transition:   'border-color 180ms ease',
    minHeight:    '48px',
    boxSizing:    'border-box',
  };

  const labelStyle: React.CSSProperties = {
    fontFamily:    'var(--font-accent, monospace)',
    fontSize:      '11px',
    fontWeight:    400,
    letterSpacing: '0.08em',
    textTransform: 'uppercase',
    color:         'var(--color-muted, var(--soil-faint))',
  };

  return (
    <div
      style={{
        width:        '100%',
        maxWidth:     '420px',
        background:   'var(--color-surface, var(--linen))',
        border:       '1px solid var(--color-border, var(--parchment))',
        borderRadius: '20px',
        padding:      'clamp(28px, 5vw, 44px)',
        boxShadow:    '0 8px 40px rgba(45,27,14,0.08)',
      }}
    >
      {/* Marca */}
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '28px' }}>
        <PawPrint size={20} style={{ color: 'var(--color-terra, var(--terra))' }} />
        <span
          style={{
            fontFamily: 'var(--font-playfair, Georgia, serif)',
            fontStyle:  'italic',
            fontWeight: 700,
            fontSize:   '20px',
            color:      'var(--color-terra, var(--terra))',
          }}
        >
          PetLink
        </span>
      </div>

      <h1
        style={{
          fontFamily:   'var(--font-playfair, Georgia, serif)',
          fontWeight:   900,
          fontSize:     '28px',
          color:        'var(--color-text, var(--soil))',
          marginBottom: '6px',
          lineHeight:   1.15,
        }}
      >
        Iniciar sessão.
      </h1>
      <p
        style={{
          fontFamily:   'var(--font-body)',
          fontSize:     '14px',
          color:        'var(--color-muted, var(--soil-mid))',
          marginBottom: '28px',
        }}
      >
        Ainda não tens conta?{' '}
        <Link href="/auth/register" style={{ color: 'var(--color-terra, var(--terra))', fontWeight: 500 }}>
          Registar
        </Link>
      </p>

      {/* Erro */}
      {error && (
        <div
          role="alert"
          style={{
            display:      'flex',
            alignItems:   'center',
            gap:          '10px',
            background:   'rgba(196,80,26,0.08)',
            border:       '1px solid rgba(196,80,26,0.25)',
            borderRadius: '10px',
            padding:      '12px 16px',
            marginBottom: '20px',
            fontFamily:   'var(--font-body)',
            fontSize:     '14px',
            color:        'var(--color-terra, var(--terra))',
          }}
        >
          <AlertCircle size={16} style={{ flexShrink: 0 }} />
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        {/* Email */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
          <label htmlFor="login-email" style={labelStyle}>Email</label>
          <div style={{ position: 'relative' }}>
            <Mail size={15} style={{ position: 'absolute', left: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--color-muted, var(--soil-faint))', pointerEvents: 'none' }} />
            <input
              id="login-email"
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="o.teu@email.pt"
              required
              autoComplete="email"
              style={inputStyle}
              onFocus={e => (e.target.style.borderColor = 'var(--color-terra, var(--terra))')}
              onBlur={e  => (e.target.style.borderColor = 'var(--color-border, var(--parchment))')}
            />
          </div>
        </div>

        {/* Password */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <label htmlFor="login-password" style={labelStyle}>Palavra-passe</label>
            <Link
              href="/auth/forgot-password"
              style={{ fontFamily: 'var(--font-body)', fontSize: '12px', color: 'var(--color-terra, var(--terra))', textDecoration: 'none' }}
            >
              Esqueceste-a?
            </Link>
          </div>
          <div style={{ position: 'relative' }}>
            <Lock size={15} style={{ position: 'absolute', left: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--color-muted, var(--soil-faint))', pointerEvents: 'none' }} />
            <input
              id="login-password"
              type={showPass ? 'text' : 'password'}
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="A tua palavra-passe"
              required
              autoComplete="current-password"
              style={{ ...inputStyle, paddingRight: '44px' }}
              onFocus={e => (e.target.style.borderColor = 'var(--color-terra, var(--terra))')}
              onBlur={e  => (e.target.style.borderColor = 'var(--color-border, var(--parchment))')}
            />
            <button
              type="button"
              onClick={() => setShowPass(s => !s)}
              style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-muted, var(--soil-faint))', padding: '4px', display: 'flex', alignItems: 'center' }}
              aria-label={showPass ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe'}
            >
              {showPass ? <EyeOff size={16} /> : <Eye size={16} />}
            </button>
          </div>
        </div>

        {/* Submit */}
        <button
          id="login-submit"
          type="submit"
          disabled={loading}
          style={{
            width:           '100%',
            padding:         '14px 24px',
            background:      loading ? 'var(--color-muted, var(--soil-faint))' : 'var(--color-terra, var(--terra))',
            color:           'white',
            border:          'none',
            borderRadius:    '100px',
            fontFamily:      'var(--font-body)',
            fontWeight:      600,
            fontSize:        '15px',
            cursor:          loading ? 'not-allowed' : 'pointer',
            transition:      'all 200ms ease',
            marginTop:       '8px',
            display:         'flex',
            alignItems:      'center',
            justifyContent:  'center',
            gap:             '8px',
          }}
          aria-label="Entrar na conta PetLink"
        >
          {loading ? (
            <>
              <span style={{ display: 'inline-block', width: '16px', height: '16px', border: '2px solid rgba(255,255,255,0.4)', borderTopColor: 'white', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }} />
              A entrar…
            </>
          ) : 'Iniciar sessão'}
        </button>

        {/* Registar */}
        <p style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontSize: '13px', color: 'var(--color-muted, var(--soil-mid))', marginTop: '4px' }}>
          Não tens conta?{' '}
          <Link href="/auth/register" style={{ color: 'var(--color-terra, var(--terra))', fontWeight: 500 }}>
            Criar conta grátis
          </Link>
        </p>
      </form>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}
