"use client";

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Lock, 
  Eye, 
  EyeOff, 
  Shield, 
  AlertTriangle, 
  CheckCircle,
  XCircle,
  Loader2
} from 'lucide-react';
import ModernAdminDashboard from '@/components/ModernAdminDashboard';

// Security constants
const MAX_ATTEMPTS = 3;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
const SESSION_DURATION = 2 * 60 * 60 * 1000; // 2 hours (reduced from 24h)
const RATE_LIMIT_DELAY = 1000; // 1 second base delay

// Password hashing removed - now handled server-side securely

// Rate limiting with exponential backoff
const getRateLimitDelay = (attempts: number): number => {
  return RATE_LIMIT_DELAY * Math.pow(2, attempts);
};

interface AuthState {
  isAuthenticated: boolean;
  isLoading: boolean;
  showLogin: boolean;
  password: string;
  showPassword: boolean;
  error: string;
  attempts: number;
  isLocked: boolean;
  lastAttempt: number;
  csrfToken: string;
}

const AdminPage = () => {
  const [authState, setAuthState] = useState<AuthState>({
    isAuthenticated: false,
    isLoading: true,
    showLogin: false,
    password: '',
    showPassword: false,
    error: '',
    attempts: 0,
    isLocked: false,
    lastAttempt: 0,
    csrfToken: ''
  });

  // Fetch CSRF token
  const fetchCSRFToken = useCallback(async () => {
    try {
      const response = await fetch('/api/auth/csrf');
      const data = await response.json();
      if (response.ok && data.csrfToken) {
        setAuthState(prev => ({ ...prev, csrfToken: data.csrfToken }));
        return data.csrfToken;
      }
    } catch (error) {
      console.error('Failed to fetch CSRF token:', error);
    }
    return '';
  }, []);

  // Check if user is locked out
  const checkLockout = useCallback(() => {
    const lockoutData = localStorage.getItem('admin_lockout');
    if (lockoutData) {
      try {
        const { timestamp, attempts } = JSON.parse(lockoutData);
        const now = Date.now();

        if (now - timestamp < LOCKOUT_DURATION) {
          setAuthState(prev => ({
            ...prev,
            isLocked: true,
            attempts,
            isLoading: false
          }));
          return true;
        } else {
          localStorage.removeItem('admin_lockout');
        }
      } catch (error) {
        localStorage.removeItem('admin_lockout');
      }
    }
    return false;
  }, []);

  // Check session validity via API
  const checkSession = useCallback(async () => {
    const authStatus = sessionStorage.getItem('admin_authenticated');
    const sessionToken = sessionStorage.getItem('admin_session_token');
    
    if (!authStatus || !sessionToken) {
      setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
      return false;
    }

    try {
      // Validate session with server
      const response = await fetch('/api/auth/validate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': authState.csrfToken
        },
        body: JSON.stringify({
          sessionToken,
          csrfToken: authState.csrfToken
        })
      });

      const data = await response.json();

      if (response.ok && data.valid) {
        setAuthState(prev => ({ 
          ...prev, 
          isAuthenticated: true, 
          isLoading: false,
          showLogin: false 
        }));
        return true;
      } else {
        // Session invalid, clear storage
        sessionStorage.clear();
        setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
        return false;
      }
    } catch (error) {
      // Network error, clear session
      sessionStorage.clear();
      setAuthState(prev => ({ ...prev, showLogin: true, isLoading: false }));
      return false;
    }
  }, []);

  // Initialize authentication check
  useEffect(() => {
    const initAuth = async () => {
      // Add random delay to prevent timing attacks
      await new Promise(resolve => setTimeout(resolve, Math.random() * 500 + 200));

      // Fetch CSRF token first
      await fetchCSRFToken();

      if (!checkLockout()) {
        await checkSession();
      }
    };

    initAuth();
  }, [checkLockout, checkSession, fetchCSRFToken]);

  // Handle login submission
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (authState.isLocked || authState.isLoading) return;

    setAuthState(prev => ({ ...prev, isLoading: true, error: '' }));

    try {
      // Rate limiting delay
      const delay = getRateLimitDelay(authState.attempts);
      await new Promise(resolve => setTimeout(resolve, delay));

      // Send login request to secure API
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': authState.csrfToken
        },
        body: JSON.stringify({
          password: authState.password,
          csrfToken: authState.csrfToken
        })
      });

      const data = await response.json();

      if (response.ok && data.success) {
        // Successful login
        const now = Date.now();
        const sessionToken = data.sessionToken;
        
        localStorage.removeItem('admin_lockout');
        sessionStorage.setItem('admin_authenticated', 'true');
        sessionStorage.setItem('admin_login_time', now.toString());
        sessionStorage.setItem('admin_session_token', sessionToken);
        
        setAuthState(prev => ({
          ...prev,
          isAuthenticated: true,
          showLogin: false,
          isLoading: false,
          password: '',
          attempts: 0,
          error: ''
        }));
      } else {
        // Failed login
        const newAttempts = authState.attempts + 1;
        const newLastAttempt = Date.now();
        
        if (newAttempts >= MAX_ATTEMPTS) {
          // Lock user out
          localStorage.setItem('admin_lockout', JSON.stringify({
            timestamp: newLastAttempt,
            attempts: newAttempts
          }));
          
          setAuthState(prev => ({
            ...prev,
            isLocked: true,
            attempts: newAttempts,
            lastAttempt: newLastAttempt,
            isLoading: false,
            error: `Zu viele fehlgeschlagene Versuche. Zugang für ${Math.ceil(LOCKOUT_DURATION / 60000)} Minuten gesperrt.`
          }));
        } else {
          setAuthState(prev => ({
            ...prev,
            attempts: newAttempts,
            lastAttempt: newLastAttempt,
            isLoading: false,
            error: data.error || `Falsches Passwort. ${MAX_ATTEMPTS - newAttempts} Versuche übrig.`,
            password: ''
          }));
        }
      }
    } catch (error) {
      setAuthState(prev => ({
        ...prev,
        isLoading: false,
        error: 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.'
      }));
    }
  };

  // Handle logout
  const handleLogout = () => {
    sessionStorage.clear();
    setAuthState(prev => ({
      ...prev,
      isAuthenticated: false,
      showLogin: true,
      password: '',
      error: ''
    }));
  };

  // Get remaining lockout time
  const getRemainingTime = () => {
    const lockoutData = localStorage.getItem('admin_lockout');
    if (lockoutData) {
      try {
        const { timestamp } = JSON.parse(lockoutData);
        const remaining = Math.ceil((LOCKOUT_DURATION - (Date.now() - timestamp)) / 1000 / 60);
        return Math.max(0, remaining);
      } catch {
        return 0;
      }
    }
    return 0;
  };

  // Loading state
  if (authState.isLoading && !authState.showLogin) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center"
        >
          <div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4">
            <Loader2 className="w-8 h-8 text-white animate-spin" />
          </div>
          <p className="text-white text-lg">Überprüfe Berechtigung...</p>
        </motion.div>
      </div>
    );
  }

  // Lockout state
  if (authState.isLocked) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-red-900 via-gray-900 to-red-900 flex items-center justify-center p-4">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-white/10 backdrop-blur-md rounded-2xl border border-red-500/30 p-8 max-w-md w-full text-center"
        >
          <div className="mb-6">
            <Shield className="w-16 h-16 text-red-400 mx-auto mb-4" />
            <h1 className="text-2xl font-bold text-white mb-2">Zugang gesperrt</h1>
            <p className="text-gray-300">
              Zu viele fehlgeschlagene Anmeldeversuche
            </p>
          </div>
          
          <div className="bg-red-500/20 border border-red-500/30 rounded-lg p-4 mb-6">
            <AlertTriangle className="w-8 h-8 text-red-400 mx-auto mb-2" />
            <p className="text-red-200 text-sm">
              Versuche: {authState.attempts}/{MAX_ATTEMPTS}
            </p>
            <p className="text-red-200 text-sm">
              Verbleibende Zeit: {getRemainingTime()} Minuten
            </p>
          </div>
          
          <p className="text-gray-400 text-sm">
            Der Zugang wird automatisch nach {Math.ceil(LOCKOUT_DURATION / 60000)} Minuten freigeschaltet.
          </p>
        </motion.div>
      </div>
    );
  }

  // Login form
  if (authState.showLogin || !authState.isAuthenticated) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center p-4">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white/10 backdrop-blur-md rounded-2xl border border-white/20 p-8 max-w-md w-full"
        >
          <div className="text-center mb-8">
            <div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <Lock className="w-8 h-8 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-white mb-2">Admin-Zugang</h1>
            <p className="text-gray-300">Bitte geben Sie das Admin-Passwort ein</p>
          </div>

          <form onSubmit={handleLogin} className="space-y-6">
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">
                Passwort
              </label>
              <div className="relative">
                <input
                  type={authState.showPassword ? 'text' : 'password'}
                  id="password"
                  value={authState.password}
                  onChange={(e) => setAuthState(prev => ({ ...prev, password: e.target.value }))}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all pr-12"
                  placeholder="Admin-Passwort eingeben"
                  required
                  disabled={authState.isLoading}
                  autoComplete="current-password"
                />
                <button
                  type="button"
                  onClick={() => setAuthState(prev => ({ ...prev, showPassword: !prev.showPassword }))}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors"
                  disabled={authState.isLoading}
                >
                  {authState.showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            <AnimatePresence>
              {authState.error && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="bg-red-500/20 border border-red-500/30 rounded-lg p-3"
                >
                  <p className="text-red-200 text-sm">{authState.error}</p>
                </motion.div>
              )}
            </AnimatePresence>

            <button
              type="submit"
              disabled={authState.isLoading || !authState.password}
              className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 disabled:from-gray-600 disabled:to-gray-700 text-white font-semibold py-3 px-4 rounded-lg transition-all duration-200 disabled:cursor-not-allowed"
            >
              {authState.isLoading ? (
                <div className="flex items-center justify-center">
                  <Loader2 className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"></Loader2>
                  Anmeldung...
                </div>
              ) : (
                'Anmelden'
              )}
            </button>
          </form>

          <div className="mt-6 text-center">
            <p className="text-gray-400 text-xs">
              Versuche: {authState.attempts}/{MAX_ATTEMPTS}
            </p>
          </div>
        </motion.div>
      </div>
    );
  }

  // Authenticated state - show admin dashboard
  return (
    <div className="relative">
      {/* Logout button */}
      <div className="fixed top-4 right-4 z-50">
        <button
          onClick={handleLogout}
          className="bg-red-500/20 hover:bg-red-500/30 border border-red-500/30 text-red-200 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2"
        >
          <XCircle className="w-4 h-4" />
          <span>Logout</span>
        </button>
      </div>
      
      <ModernAdminDashboard isAuthenticated={authState.isAuthenticated} />
    </div>
  );
};

export default AdminPage;