"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 bg-[#fdfcf8]">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-stone-600" />
          <p className="text-stone-500">Loading...</p>
        </div>
      </div>
    );
  }

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

  // Login form
  if (authState.showLogin || !authState.isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center relative overflow-hidden bg-[#fdfcf8] z-0">
        
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="w-full max-w-md p-6"
        >
          <div className="bg-white/80 backdrop-blur-xl rounded-3xl p-8 border border-stone-200 shadow-2xl relative z-10">
            <div className="text-center mb-8">
              <div className="w-16 h-16 bg-[#f3f1e7] rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-sm border border-stone-100">
                <Lock className="w-6 h-6 text-stone-600" />
              </div>
              <h1 className="text-2xl font-bold text-stone-900 mb-2 tracking-tight">Admin Access</h1>
              <p className="text-stone-500">Enter your password to continue</p>
            </div>

            <form onSubmit={handleLogin} className="space-y-5">
              <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.5 bg-white border border-stone-200 rounded-xl text-stone-900 placeholder:text-stone-400 focus:outline-none focus:ring-2 focus:ring-stone-200 focus:border-stone-400 transition-all shadow-sm"
                    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-stone-400 hover:text-stone-600 p-1"
                  >
                    {authState.showPassword ? '👁️' : '👁️‍🗨️'}
                  </button>
                </div>
                {authState.error && (
                  <motion.p 
                    initial={{ opacity: 0, y: -5 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="mt-2 text-red-500 text-sm font-medium flex items-center"
                  >
                    <span className="w-1.5 h-1.5 bg-red-500 rounded-full mr-2" />
                    {authState.error}
                  </motion.p>
                )}
              </div>

              <button
                type="submit"
                disabled={authState.isLoading || !authState.password}
                className="w-full bg-stone-900 text-stone-50 py-3.5 px-6 rounded-xl font-semibold text-lg hover:bg-stone-800 focus:outline-none focus:ring-2 focus:ring-stone-200 focus:ring-offset-2 focus:ring-offset-white disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg flex items-center justify-center"
              >
                {authState.isLoading ? (
                  <div className="flex items-center justify-center space-x-2">
                    <Loader2 className="w-5 h-5 animate-spin" />
                    <span className="text-stone-50">Authenticating...</span>
                  </div>
                ) : (
                  <span className="text-stone-50">Sign In</span>
                )}
              </button>
            </form>
          </div>
        </motion.div>
      </div>
    );
  }

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

export default AdminPage;