"use client";

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Lock,
  Eye,
  EyeOff,
  Shield,
  AlertTriangle,
  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 RATE_LIMIT_DELAY = 1000; // 1 second base delay

// 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 {
      console.error('Failed to fetch CSRF token');
    }
    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 {
        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');
    const csrfToken = authState.csrfToken;

    // If no session data, show login immediately
    if (!authStatus || !sessionToken || !csrfToken) {
      setAuthState(prev => ({
        ...prev,
        isAuthenticated: false,
        isLoading: false,
        showLogin: true
      }));
      return;
    }

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

      if (response.ok) {
        setAuthState(prev => ({
          ...prev,
          isAuthenticated: true,
          isLoading: false,
          showLogin: false
        }));
        return;
      } else {
        // Clear invalid session
        sessionStorage.removeItem('admin_authenticated');
        sessionStorage.removeItem('admin_session_token');
        setAuthState(prev => ({
          ...prev,
          isAuthenticated: false,
          isLoading: false,
          showLogin: true
        }));
      }
    } catch (error) {
      console.error('Session validation error:', error);
      // Clear session on error
      sessionStorage.removeItem('admin_authenticated');
      sessionStorage.removeItem('admin_session_token');
      setAuthState(prev => ({
        ...prev,
        isAuthenticated: false,
        isLoading: false,
        showLogin: true
      }));
    }
  }, [authState.csrfToken]);

  // Initialize
  useEffect(() => {
    const init = async () => {
      if (checkLockout()) return;
      
      const token = await fetchCSRFToken();
      if (token) {
        setAuthState(prev => ({ ...prev, csrfToken: token }));
      }
    };
    
    init();
  }, [checkLockout, fetchCSRFToken]);

  useEffect(() => {
    if (authState.csrfToken && !authState.isLocked) {
      checkSession();
    }
  }, [authState.csrfToken, authState.isLocked]);

  // Handle logout
  const handleLogout = useCallback(() => {
    sessionStorage.removeItem('admin_authenticated');
    sessionStorage.removeItem('admin_session_token');
    setAuthState(prev => ({
      ...prev,
      isAuthenticated: false,
      showLogin: true,
      password: '',
      error: ''
    }));
  }, []);

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

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

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

    try {
      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) {
        // Store session
        sessionStorage.setItem('admin_authenticated', 'true');
        sessionStorage.setItem('admin_session_token', data.sessionToken);
        
        // Clear lockout data
        localStorage.removeItem('admin_lockout');
        
        // Update state
        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: `Too many failed attempts. Access locked for ${Math.ceil(LOCKOUT_DURATION / 60000)} minutes.`
          }));
        } else {
          setAuthState(prev => ({
            ...prev,
            attempts: newAttempts,
            lastAttempt: newLastAttempt,
            isLoading: false,
            error: data.error || `Wrong password. ${MAX_ATTEMPTS - newAttempts} attempts remaining.`,
            password: ''
          }));
        }
      }
    } catch {
      setAuthState(prev => ({
        ...prev,
        isLoading: false,
        error: 'An error occurred. Please try again.'
      }));
    }
  };

  // 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">
        <div className="fixed inset-0 animated-bg"></div>
        <div className="relative z-10 min-h-screen flex items-center justify-center">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="text-center admin-glass-card p-8 rounded-2xl"
          >
            <div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
              <Loader2 className="w-8 h-8 text-white animate-spin" />
            </div>
            <p className="text-white text-xl font-semibold">Verifying Access...</p>
            <p className="text-white/60 text-sm mt-2">Please wait while we authenticate your session</p>
          </motion.div>
        </div>
      </div>
    );
  }

  // Lockout state
  if (authState.isLocked) {
    return (
      <div className="min-h-screen">
        <div className="fixed inset-0 animated-bg"></div>
        <div className="relative z-10 min-h-screen flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="admin-glass-card border-red-500/40 p-8 lg:p-12 rounded-2xl max-w-md w-full text-center shadow-2xl"
          >
            <div className="mb-8">
              <div className="w-16 h-16 bg-gradient-to-r from-red-500 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
                <Shield className="w-8 h-8 text-white" />
              </div>
              <h1 className="text-3xl font-bold text-white mb-3">Access Locked</h1>
              <p className="text-white/80 text-lg">
                Too many failed authentication attempts
              </p>
            </div>
            
            <div className="admin-glass-light border border-red-500/40 rounded-xl p-6 mb-8">
              <AlertTriangle className="w-8 h-8 text-red-400 mx-auto mb-4" />
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <p className="text-white/60 mb-1">Attempts</p>
                  <p className="text-red-300 font-bold text-lg">{authState.attempts}/{MAX_ATTEMPTS}</p>
                </div>
                <div>
                  <p className="text-white/60 mb-1">Time Left</p>
                  <p className="text-orange-300 font-bold text-lg">{getRemainingTime()}m</p>
                </div>
              </div>
            </div>
            
            <div className="admin-glass-light border border-blue-500/30 rounded-xl p-4">
              <p className="text-white/70 text-sm">
                Access will be automatically restored in {Math.ceil(LOCKOUT_DURATION / 60000)} minutes
              </p>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  // Login form
  if (authState.showLogin || !authState.isAuthenticated) {
    return (
      <div className="min-h-screen">
        {/* Animated Background - same as admin dashboard */}
        <div className="fixed inset-0 animated-bg"></div>

        <div className="relative z-10 min-h-screen flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="admin-glass-card p-8 lg:p-12 rounded-2xl max-w-md w-full shadow-2xl"
          >
            <div className="text-center mb-8">
              <div className="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
                <Shield className="w-8 h-8 text-white" />
              </div>
              <h1 className="text-3xl font-bold text-white mb-3">Admin Panel</h1>
              <p className="text-white/80 text-lg">Secure access to dashboard</p>
              <div className="flex items-center justify-center space-x-2 mt-4">
                <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                <span className="text-white/60 text-sm font-medium">System Online</span>
              </div>
            </div>

            <form onSubmit={handleLogin} className="space-y-6">
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-white/80 mb-3">
                  Admin Password
                </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-4 admin-glass-light border border-white/30 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500/50 transition-all text-lg pr-12"
                    placeholder="Enter admin password"
                    required
                    disabled={authState.isLoading}
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={() => setAuthState(prev => ({ ...prev, showPassword: !prev.showPassword }))}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-white/60 hover:text-white transition-colors p-1"
                    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, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="admin-glass-light border border-red-500/40 rounded-xl p-4 flex items-center space-x-3"
                  >
                    <XCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
                    <p className="text-red-300 text-sm font-medium">{authState.error}</p>
                  </motion.div>
                )}
              </AnimatePresence>

              {/* Security info */}
              <div className="admin-glass-light border border-blue-500/30 rounded-xl p-6">
                <div className="flex items-center space-x-3 mb-4">
                  <Shield className="w-5 h-5 text-blue-400" />
                  <h3 className="text-blue-300 font-semibold">Security Information</h3>
                </div>
                <div className="grid grid-cols-2 gap-4 text-xs">
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-white/60">Max Attempts:</span>
                      <span className="text-white font-medium">{MAX_ATTEMPTS}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-white/60">Lockout:</span>
                      <span className="text-white font-medium">{Math.ceil(LOCKOUT_DURATION / 60000)}m</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-white/60">Session:</span>
                      <span className="text-white font-medium">2h</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-white/60">Attempts:</span>
                      <span className={`font-medium ${authState.attempts > 0 ? 'text-orange-400' : 'text-green-400'}`}>
                        {authState.attempts}/{MAX_ATTEMPTS}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <button
                type="submit"
                disabled={authState.isLoading || !authState.password}
                className="w-full bg-gradient-to-r from-blue-500 to-purple-500 text-white py-4 px-6 rounded-xl font-semibold text-lg hover:from-blue-600 hover:to-purple-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-transparent disabled:opacity-50 disabled:cursor-not-allowed transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg"
              >
                {authState.isLoading ? (
                  <div className="flex items-center justify-center space-x-3">
                    <Loader2 className="w-5 h-5 animate-spin" />
                    <span>Authenticating...</span>
                  </div>
                ) : (
                  <div className="flex items-center justify-center space-x-2">
                    <Lock size={18} />
                    <span>Secure Login</span>
                  </div>
                )}
              </button>
            </form>

            {/* Debug: Clear Session Button */}
            <div className="mt-6 pt-6 border-t border-white/20">
              <button
                type="button"
                onClick={handleLogout}
                className="w-full text-white/60 hover:text-white/80 text-sm py-2 px-4 rounded-lg border border-white/20 hover:border-white/40 transition-all"
              >
                Clear Session & Reload
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  // Authenticated state - show admin dashboard
  return (
    <div className="relative">
      <ModernAdminDashboard isAuthenticated={authState.isAuthenticated} />
    </div>
  );
};

export default AdminPage;