import React, { useState, useEffect, useRef } from 'react';
import { Shield, Lock, User, AlertCircle, Clock, Building2 } from 'lucide-react';
import { InputSanitizer } from '../utils/sanitizer';

interface LoginScreenProps {
  onLogin: (username: string, password: string) => Promise<void>;
}

const LoginScreen: React.FC<LoginScreenProps> = ({ onLogin }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [focusedField, setFocusedField] = useState<'username' | 'password' | null>(null);
  const [showInactivityWarning, setShowInactivityWarning] = useState(false);

  // Timer for auto-clearing form on inactivity
  const inactivityTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const INACTIVITY_TIMEOUT = 5 * 60 * 1000; // 5 minutes in milliseconds

  // Function to clear form on inactivity
  const clearFormDueToInactivity = () => {
    if (username || password) {
      setUsername('');
      setPassword('');
      setError(null);
      setShowInactivityWarning(true);

      // Hide warning after 5 seconds
      setTimeout(() => {
        setShowInactivityWarning(false);
      }, 5000);
    }
  };

  // Reset timer on user activity
  const resetInactivityTimer = () => {
    // Clear previous timer
    if (inactivityTimerRef.current) {
      clearTimeout(inactivityTimerRef.current);
    }

    // Set new 5 minute timer
    inactivityTimerRef.current = setTimeout(() => {
      clearFormDueToInactivity();
    }, INACTIVITY_TIMEOUT);
  };

  // Track activity
  const handleActivity = () => {
    setShowInactivityWarning(false);
    resetInactivityTimer();
  };

  // Set timer on mount and clear on unmount
  useEffect(() => {
    resetInactivityTimer();

    // Cleanup on unmount
    return () => {
      if (inactivityTimerRef.current) {
        clearTimeout(inactivityTimerRef.current);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Сбрасываем таймер при изменении полей формы
  useEffect(() => {
    if (username || password) {
      resetInactivityTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [username, password]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      // Санитизируем и валидируем данные перед отправкой
      const sanitizedUsername = InputSanitizer.sanitizeUsername(username);
      InputSanitizer.validatePassword(password);

      await onLogin(sanitizedUsername, password);
      // Очищаем форму после успешного входа
      setUsername('');
      setPassword('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Authentication failed. Please check your credentials and try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div 
      className="min-h-screen w-full bg-gradient-to-br from-kaspersky-secondary via-kaspersky-primary-dark to-kaspersky-secondary animate-gradient flex items-center justify-center p-4 overflow-hidden"
      onMouseMove={handleActivity}
      onClick={handleActivity}
      onKeyDown={handleActivity}
    >
      {/* Animated background pattern */}
      <div className="absolute inset-0 opacity-10 overflow-hidden">
        <div className="absolute inset-0 w-full h-full animate-pattern" style={{
          backgroundImage: `radial-gradient(circle at 2px 2px, rgba(0, 168, 142, 0.4) 1px, transparent 0)`,
          backgroundSize: '40px 40px'
        }} />
      </div>

      {/* Login Card */}
      <div className="relative z-10 w-full max-w-md select-none">
        {/* Logo/Header Section */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-20 h-20 bg-kaspersky-primary rounded-2xl shadow-kaspersky-xl mb-6 transform hover:scale-105 transition-transform duration-300">
            <Shield size={48} className="text-white" strokeWidth={1.5} />
          </div>
          <h1 className="text-4xl font-bold text-white mb-2 tracking-tight">
            URG Duty
          </h1>
          <p className="text-kaspersky-text-lighter text-lg">
            Remote Access Control Center
          </p>
        </div>

        {/* Login Form Card */}
        <div className="bg-white/95 backdrop-blur-sm rounded-2xl shadow-kaspersky-xl p-8">
          {/* Header */}
          <div className="text-center mb-8">
            <h2 className="text-2xl font-semibold text-kaspersky-text-dark mb-2">
              Sign In
            </h2>
            <p className="text-kaspersky-text-light text-sm">
              Enter your credentials to access the system
            </p>
          </div>

          {/* Inactivity Warning Message */}
          {showInactivityWarning && (
            <div className="mb-6 bg-orange-50 border-l-4 border-orange-500 rounded-lg p-4 flex items-start gap-3 animate-fadeIn select-none">
              <Clock size={20} className="text-orange-500 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <p className="text-sm font-medium text-orange-700">
                  Форма очищена
                </p>
                <p className="text-sm text-kaspersky-text-light mt-1">
                  Форма была очищена из-за неактивности (5 минут)
                </p>
              </div>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="mb-6 bg-red-50 border-l-4 border-kaspersky-danger rounded-lg p-4 flex items-start gap-3 animate-shake select-none">
              <AlertCircle size={20} className="text-kaspersky-danger flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <p className="text-sm font-medium text-kaspersky-danger">
                  Authentication Failed
                </p>
                <p className="text-sm text-kaspersky-text-light mt-1">
                  {error}
                </p>
              </div>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Username Field */}
            <div>
              <label 
                htmlFor="username" 
                className="block text-sm font-medium text-kaspersky-text-dark mb-2"
              >
                Username
              </label>
              <div className={`relative transition-all duration-300 ${
                focusedField === 'username' ? 'transform scale-[1.02]' : ''
              }`}>
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <User 
                    size={18} 
                    className={`transition-colors duration-300 ${
                      focusedField === 'username' ? 'text-kaspersky-primary' : 'text-kaspersky-text-lighter'
                    }`} 
                  />
                </div>
                <input
                  type="text"
                  id="username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  onFocus={() => setFocusedField('username')}
                  onBlur={() => setFocusedField(null)}
                  className={`w-full pl-10 pr-4 py-3 border-2 rounded-lg font-kaspersky
                    transition-all duration-300 outline-none
                    ${focusedField === 'username' 
                      ? 'border-kaspersky-primary bg-kaspersky-bg-card shadow-kaspersky' 
                      : 'border-kaspersky-border bg-kaspersky-bg-card hover:border-kaspersky-border-dark'
                    }
                    disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-gray-100
                  `}
                  placeholder="Enter your username"
                  required
                  disabled={isLoading}
                  autoFocus
                  autoComplete="username"
                />
              </div>
            </div>

            {/* Password Field */}
            <div>
              <label 
                htmlFor="password" 
                className="block text-sm font-medium text-kaspersky-text-dark mb-2"
              >
                Password
              </label>
              <div className={`relative transition-all duration-300 ${
                focusedField === 'password' ? 'transform scale-[1.02]' : ''
              }`}>
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock 
                    size={18} 
                    className={`transition-colors duration-300 ${
                      focusedField === 'password' ? 'text-kaspersky-primary' : 'text-kaspersky-text-lighter'
                    }`} 
                  />
                </div>
                <input
                  type="password"
                  id="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onFocus={() => setFocusedField('password')}
                  onBlur={() => setFocusedField(null)}
                  className={`w-full pl-10 pr-4 py-3 border-2 rounded-lg font-kaspersky
                    transition-all duration-300 outline-none
                    ${focusedField === 'password' 
                      ? 'border-kaspersky-primary bg-kaspersky-bg-card shadow-kaspersky' 
                      : 'border-kaspersky-border bg-kaspersky-bg-card hover:border-kaspersky-border-dark'
                    }
                    disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-gray-100
                  `}
                  placeholder="Enter your password"
                  required
                  disabled={isLoading}
                  autoComplete="current-password"
                />
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isLoading || !username || !password}
              className={`
                w-full py-3 px-6 rounded-lg font-semibold text-white
                transition-all duration-300 transform
                ${isLoading || !username || !password
                  ? 'bg-kaspersky-text-lighter cursor-not-allowed opacity-60'
                  : 'bg-kaspersky-primary hover:bg-kaspersky-primary-dark hover:shadow-kaspersky-lg active:scale-[0.98]'
                }
                disabled:transform-none
                focus:outline-none focus:ring-4 focus:ring-kaspersky-primary/30
              `}
            >
              {isLoading ? (
                <span className="flex items-center justify-center gap-2">
                  <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Authenticating...
                </span>
              ) : (
                'Sign In'
              )}
            </button>

            {/* Divider */}
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-gray-300"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-2 bg-white/95 backdrop-blur-sm text-gray-500">or</span>
              </div>
            </div>

            {/* ADFS Button (Coming Soon) */}
            <div className="relative">
              <button
                type="button"
                disabled
                className="w-full py-3 px-6 rounded-lg font-semibold text-gray-500 bg-gray-200 cursor-not-allowed opacity-60 flex items-center justify-center gap-3"
              >
                <Building2 size={20} className="text-gray-500" />
                <span>Sign in with ADFS</span>
              </button>
              {/* Бейдж SOON */}
              <span className="absolute -top-1 -right-1 bg-gradient-to-r from-kaspersky-primary to-kaspersky-danger text-white text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wide shadow-sm">
                Soon
              </span>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default LoginScreen;

