'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Mail, Lock, ArrowRight, Loader2, User, Shield, Smartphone, KeyRound, RotateCcw } from 'lucide-react';
import Image from 'next/image';

type TwoFAMethod = 'email' | 'sms' | 'authenticator';

interface TwoFAChallenge {
  challengeId: string;
  method: TwoFAMethod;
  message: string;
}

export default function Auth() {
  const [isLogin, setIsLogin] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({ name: '', email: '', password: '' });

  // 2FA state
  const [twoFAChallenge, setTwoFAChallenge] = useState<TwoFAChallenge | null>(null);
  const [twoFACode, setTwoFACode] = useState('');
  const [resendLoading, setResendLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const endpoint = isLogin ? '/api/auth/signin' : '/api/auth/signup';
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
        credentials: 'include',
      });
      const data = await response.json();

      // Check if 2FA is required
      if (response.status === 202 && data.requires2FA) {
        setTwoFAChallenge({
          challengeId: data.challengeId,
          method: data.method,
          message: data.message,
        });
        setLoading(false);
        return;
      }

      if (!response.ok) throw new Error(data.error || 'Authentication failed');
      window.location.href = '/';
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Authentication failed');
    } finally {
      setLoading(false);
    }
  };

  const handle2FAVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      if (!twoFAChallenge) return;

      const response = await fetch('/api/auth/2fa/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          challengeId: twoFAChallenge.challengeId,
          code: twoFACode,
        }),
        credentials: 'include',
      });
      const data = await response.json();

      if (!response.ok) throw new Error(data.error || '2FA verification failed');
      window.location.href = '/';
    } catch (err) {
      setError(err instanceof Error ? err.message : '2FA verification failed');
    } finally {
      setLoading(false);
    }
  };

  const handleResendCode = async () => {
    if (!twoFAChallenge) return;
    setResendLoading(true);
    setError('');
    try {
      const response = await fetch('/api/auth/2fa/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          challengeId: twoFAChallenge.challengeId,
          method: twoFAChallenge.method,
        }),
        credentials: 'include',
      });
      const data = await response.json();

      if (!response.ok) throw new Error(data.error || 'Failed to resend code');

      // Update challenge ID if new one was created
      if (data.challengeId) {
        setTwoFAChallenge({
          ...twoFAChallenge,
          challengeId: data.challengeId,
        });
      }

      setError('');
      // Show success message
      setTimeout(() => {
        alert(data.message || 'Code resent successfully');
      }, 100);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to resend code');
    } finally {
      setResendLoading(false);
    }
  };

  const handleCancel2FA = () => {
    setTwoFAChallenge(null);
    setTwoFACode('');
    setError('');
  };

  const get2FAMethodIcon = (method: TwoFAMethod) => {
    switch (method) {
      case 'email':
        return <Mail className="w-5 h-5" />;
      case 'sms':
        return <Smartphone className="w-5 h-5" />;
      case 'authenticator':
        return <KeyRound className="w-5 h-5" />;
    }
  };

  const get2FAMethodLabel = (method: TwoFAMethod) => {
    switch (method) {
      case 'email':
        return 'Email';
      case 'sms':
        return 'SMS';
      case 'authenticator':
        return 'Authenticator App';
    }
  };

  const inputClass = "w-full pl-10 pr-4 py-2.5 bg-surface border border-border rounded-lg text-foreground text-sm placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-accent focus:border-accent transition-colors";
  const twoFAInputClass = "w-full text-center px-4 py-3 bg-surface border border-border rounded-lg text-foreground text-2xl font-mono tracking-[0.5em] placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-accent focus:border-accent transition-colors";

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4">
      {/* subtle radial bg — brand orange */}
      <div className="fixed inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,145,77,0.06),transparent_60%)] pointer-events-none" />

      <motion.div
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="w-full max-w-sm relative z-10"
      >
        {/* Logo/Brand */}
        <div className="flex items-center justify-center gap-3 mb-8">
          <Image src="/logo-dark-theme.png" alt="Scriba AI" width={36} height={36} className="rounded-lg" />
          <span className="text-xl font-bold text-foreground tracking-tight">Scriba <span className="gradient-text">AI</span></span>
        </div>

        {/* Card */}
        <div className="glass rounded-xl p-6">
          <AnimatePresence mode="wait">
            {twoFAChallenge ? (
              // 2FA Verification UI
              <motion.div
                key="2fa"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.2 }}
              >
                <div className="mb-6 text-center">
                  <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-accent/10 mb-4">
                    <Shield className="w-6 h-6 text-accent" />
                  </div>
                  <h1 className="text-lg font-semibold text-foreground">
                    Two-Factor Authentication
                  </h1>
                  <p className="text-sm text-muted mt-1">
                    {twoFAChallenge.message}
                  </p>
                </div>

                <div className="flex items-center justify-center gap-2 mb-6">
                  <div className="flex items-center gap-2 px-3 py-1.5 bg-accent/10 rounded-full">
                    {get2FAMethodIcon(twoFAChallenge.method)}
                    <span className="text-sm font-medium text-accent">
                      {get2FAMethodLabel(twoFAChallenge.method)}
                    </span>
                  </div>
                </div>

                <form onSubmit={handle2FAVerify} className="space-y-4">
                  <div>
                    <label className="text-xs font-medium text-muted uppercase tracking-wider block text-center mb-2">
                      Verification Code
                    </label>
                    <input
                      type="text"
                      inputMode="numeric"
                      maxLength={6}
                      placeholder="000000"
                      value={twoFACode}
                      onChange={(e) => setTwoFACode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                      className={twoFAInputClass}
                      autoFocus
                      required
                    />
                  </div>

                  <AnimatePresence>
                    {error && (
                      <motion.p
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        exit={{ opacity: 0, height: 0 }}
                        className="text-xs text-danger bg-danger/10 border border-danger/20 rounded-lg px-3 py-2 text-center"
                      >
                        {error}
                      </motion.p>
                    )}
                  </AnimatePresence>

                  <button
                    type="submit"
                    disabled={loading || twoFACode.length !== 6}
                    className="w-full py-2.5 gradient-accent text-white rounded-lg text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                  >
                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : (
                      <>Verify<ArrowRight className="w-4 h-4" /></>
                    )}
                  </button>

                  <div className="flex gap-2">
                    {twoFAChallenge.method !== 'authenticator' && (
                      <button
                        type="button"
                        onClick={handleResendCode}
                        disabled={resendLoading}
                        className="flex-1 py-2 border border-border text-foreground rounded-lg text-sm font-medium hover:bg-surface transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
                      >
                        {resendLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RotateCcw className="w-4 h-4" />}
                        Resend Code
                      </button>
                    )}
                    <button
                      type="button"
                      onClick={handleCancel2FA}
                      className="flex-1 py-2 border border-border text-muted rounded-lg text-sm font-medium hover:bg-surface transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </motion.div>
            ) : (
              // Login/Signup Form
              <motion.div
                key="auth"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.15 }}
              >
                <div className="mb-6">
                  <h1 className="text-lg font-semibold text-foreground">
                    {isLogin ? 'Sign in to your account' : 'Create an account'}
                  </h1>
                  <p className="text-sm text-muted mt-1">
                    {isLogin ? 'Welcome back. Enter your credentials.' : 'Start your migration journey.'}
                  </p>
                </div>

                <form onSubmit={handleSubmit} className="space-y-4">
                  {!isLogin && (
                    <div>
                      <label className="text-xs font-medium text-muted uppercase tracking-wider">Name</label>
                      <div className="relative mt-1.5">
                        <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
                        <input type="text" placeholder="Your name" value={formData.name}
                          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                          className={inputClass} required={!isLogin} />
                      </div>
                    </div>
                  )}

                  <div>
                    <label className="text-xs font-medium text-muted uppercase tracking-wider">Email</label>
                    <div className="relative mt-1.5">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
                      <input type="email" placeholder="you@example.com" value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        className={inputClass} required />
                    </div>
                  </div>

                  <div>
                    <label className="text-xs font-medium text-muted uppercase tracking-wider">Password</label>
                    <div className="relative mt-1.5">
                      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
                      <input type="password" placeholder="••••••••" value={formData.password}
                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                        className={inputClass} required minLength={6} />
                    </div>
                  </div>

                  <AnimatePresence>
                    {error && (
                      <motion.p
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        exit={{ opacity: 0, height: 0 }}
                        className="text-xs text-danger bg-danger/10 border border-danger/20 rounded-lg px-3 py-2"
                      >
                        {error}
                      </motion.p>
                    )}
                  </AnimatePresence>

                  <button
                    type="submit"
                    disabled={loading}
                    className="w-full py-2.5 gradient-accent text-white rounded-lg text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer mt-2"
                  >
                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : (
                      <>{isLogin ? 'Sign In' : 'Create Account'}<ArrowRight className="w-4 h-4" /></>
                    )}
                  </button>
                </form>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Registration toggle — commented out: public sign-up disabled. Uncomment to restore.
          <div className="mt-5 pt-4 border-t border-border text-center">
            <button
              onClick={() => { setIsLogin(!isLogin); setError(''); }}
              className="text-xs text-muted hover:text-foreground transition-colors"
            >
              {isLogin ? "Don't have an account? " : 'Already have an account? '}
              <span className="text-accent-light">{isLogin ? 'Sign up' : 'Sign in'}</span>
            </button>
          </div>
          */}
        </div>

        <p className="text-center text-xs text-muted mt-4">
          AI-Powered Code Conversion Platform
        </p>
      </motion.div>
    </div>
  );
}
