import React, { useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Eye, EyeOff } from 'lucide-react';
import { useAuth } from '../context/AuthContext';

const Login: React.FC = () => {
  const [loginId, setLoginId] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  
  const { login, isAuthenticated, isLoading, error } = useAuth();
  const location = useLocation();

  // Get the intended destination from location state or default to dashboard
  const from = location.state?.from?.pathname || '/dashboard';

  // Show loading spinner while authentication is being checked
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (isAuthenticated) {
    return <Navigate to={from} replace />;
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const success = await login(loginId, password);
      if (!success) {
        // Error is already set in the context
        return;
      }
    } catch (err) {
      // Error is already handled in the context
      console.error('Login error:', err);
    }
  };

  return (
    <div className="login-page min-h-screen relative flex items-center justify-center px-4 overflow-hidden">
      {/* Video Background */}
      <video
        autoPlay
        muted
        loop
        playsInline
        className="absolute inset-0 w-full h-full object-cover z-0"
      >
        <source src="/videos/background-video.mp4" type="video/mp4" />
        {/* Fallback for browsers that don't support video */}
        Your browser does not support the video tag.
      </video>
      
      {/* Dark Overlay for better text readability */}
      <div className="absolute inset-0 bg-black bg-opacity-50 z-10"></div>
      
      {/* Login Form */}
      <div className="max-w-md w-full relative z-20">
        <div className="bg-white bg-opacity-10 backdrop-blur-md rounded-2xl shadow-2xl p-8 border border-white border-opacity-20">
          <div className="text-center mb-8">
            {/* Navy Logo */}
            <div className="flex justify-center mb-4">
              <img 
                src="/Images/navyLogo.svg" 
                alt="Navy Logo" 
                className="object-contain" style={{ width: '125px' , height: '125px', marginBottom: '10px' }}
              />
            </div>
            
            <h1 className="text-3xl font-bold text-white">Naval CMS</h1>
            <p className="text-gray-200 mt-2">Contact Management System</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="loginId" className="block text-sm font-medium text-white mb-2">
                User ID
              </label>
              <input
                id="loginId"
                type="text"
                value={loginId}
                onChange={(e) => setLoginId(e.target.value)}
                placeholder="Enter your User ID"
                className="w-full px-4 py-3 bg-white bg-opacity-20 backdrop-blur-sm border border-white border-opacity-30 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent text-white placeholder-gray-200"
                required
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-white mb-2">
                Password
              </label>
              <div className="relative">
                <input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter your password"
                  className="w-full px-4 py-3 pr-12 bg-white bg-opacity-20 backdrop-blur-sm border border-white border-opacity-30 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent text-white placeholder-gray-200"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-200 hover:text-white"
                >
                  {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                </button>
              </div>
            </div>

            {error && (
              <div className="p-3 bg-red-500 bg-opacity-20 backdrop-blur-sm border border-red-400 border-opacity-30 rounded-lg">
                <p className="text-sm text-red-200">{error}</p>
                {error.includes('server is running') && (
                  <p className="text-xs text-red-300 mt-1">
                    Make sure to start your backend server on port 3001
                  </p>
                )}
              </div>
            )}

            {/* <div className="bg-blue-500 bg-opacity-20 backdrop-blur-sm border border-blue-400 border-opacity-30 p-4 rounded-lg">
              <p className="text-sm text-blue-100">
                <strong>Demo Credentials:</strong><br />
                <strong>HQ Admin:</strong> admin / admin123<br />
                <strong>Unit Commander:</strong> commander / commander123<br />
                <strong>Unit Commander:</strong> captain / captain123<br />
                <strong>Unit Commander:</strong> fatima / fatima123<br />
                <strong>Branch Admin:</strong> rahman / rahman123
              </p>
            </div> */}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full mt-[50px] bg-blue-600 bg-opacity-80 backdrop-blur-sm text-white py-3 px-4 rounded-lg hover:bg-blue-700 hover:bg-opacity-90 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 font-medium border border-blue-400 border-opacity-30" 
              style={{ marginTop: '50px' }}
            >
              {isLoading ? 'Signing In...' : 'Sign In'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;