"use client";

import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Lock, Loader2 } from 'lucide-react';
import ModernAdminDashboard from '@/components/ModernAdminDashboard';

// Constants
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
const RATE_LIMIT_DELAY = 1000; // 1 second base delay

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 () => {
    try {
      const sessionToken = sessionStorage.getItem('admin_session_token');
      if (!sessionToken) {
        setAuthState(prev => ({ 
          ...prev, 
          isAuthenticated: false, 
          showLogin: true, 
          isLoading: false 
        }));
        return;
      }

      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, 
          showLogin: false, 
          isLoading: false 
        }));
        sessionStorage.setItem('admin_authenticated', 'true');
      } else {
        sessionStorage.removeItem('admin_authenticated');
        sessionStorage.removeItem('admin_session_token');
        setAuthState(prev => ({ 
          ...prev, 
          isAuthenticated: false, 
          showLogin: true, 
          isLoading: false 
        }));
      }
    } catch {
      setAuthState(prev => ({ 
        ...prev, 
        isAuthenticated: false, 
        showLogin: true, 
        isLoading: false 
      }));
    }
  }, [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, checkSession]);


  // 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) {
        sessionStorage.setItem('admin_authenticated', 'true');
        sessionStorage.setItem('admin_session_token', data.sessionToken);
        setAuthState(prev => ({
          ...prev,
          isAuthenticated: true,
          showLogin: false,
          password: '',
          error: '',
          attempts: 0,
          isLoading: false
        }));
        localStorage.removeItem('admin_lockout');
      } else {
        const newAttempts = authState.attempts + 1;
        setAuthState(prev => ({
          ...prev,
          error: data.error || 'Login failed',
          attempts: newAttempts,
          isLoading: false
        }));

        if (newAttempts >= 5) {
          localStorage.setItem('admin_lockout', JSON.stringify({
            timestamp: Date.now(),
            attempts: newAttempts
          }));
          setAuthState(prev => ({
            ...prev,
            isLocked: true,
            error: 'Too many failed attempts. Please try again in 15 minutes.'
          }));
        }
      }
    } catch {
      setAuthState(prev => ({
        ...prev,
        error: 'Network error. Please try again.',
        isLoading: false
      }));
    }
  };

  // Loading state
  if (authState.isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-blue-500" />
          <p className="text-white">Loading...</p>
        </div>
      </div>
    );
  }

  // Lockout state
  if (authState.isLocked) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <Lock className="w-16 h-16 mx-auto mb-4 text-red-500" />
          <h2 className="text-2xl font-bold text-white mb-2">Account Locked</h2>
          <p className="text-white/60">Too many failed attempts. Please try again in 15 minutes.</p>
          <button
            onClick={() => {
              localStorage.removeItem('admin_lockout');
              window.location.reload();
            }}
            className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  // Login form
  if (authState.showLogin || !authState.isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="w-full max-w-md p-8"
        >
          <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-8 border border-white/20">
            <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">
                <Lock className="w-8 h-8 text-white" />
              </div>
              <h1 className="text-2xl font-bold text-white mb-2">Admin Access</h1>
              <p className="text-white/60">Enter your password to continue</p>
            </div>

            <form onSubmit={handleLogin} className="space-y-6">
              <div>
                <div className="relative">
                  <input
                    type={authState.showPassword ? 'text' : 'password'}
                    value={authState.password}
                    onChange={(e) => setAuthState(prev => ({ ...prev, password: e.target.value }))}
                    placeholder="Enter password"
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    disabled={authState.isLoading}
                  />
                  <button
                    type="button"
                    onClick={() => setAuthState(prev => ({ ...prev, showPassword: !prev.showPassword }))}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-white/50 hover:text-white"
                  >
                    {authState.showPassword ? '👁️' : '👁️‍🗨️'}
                  </button>
                </div>
                {authState.error && (
                  <p className="mt-2 text-red-400 text-sm">{authState.error}</p>
                )}
              </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>
          </div>
        </motion.div>
      </div>
    );
  }

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

export default AdminPage;