import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useUserAuthentication } from '@ohif/ui';
import { Icons } from '@ohif/ui-next';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const [, authContext] = useUserAuthentication();

  // Get the intended destination from URL query params or default to home
  const searchParams = new URLSearchParams(location.search);
  const redirectPath = searchParams.get('redirect') || '/';

  // Check if already authenticated
  useEffect(() => {
    const token = window.sessionStorage.getItem('ohif-auth-token');
    if (token) {
      // Already logged in, redirect to destination
      navigate(redirectPath, { replace: true });
    }
  }, [redirectPath, navigate]);

  const handleLogin = async e => {
    e.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      // Use window.config.goProxyHost for authentication endpoint
      const proxyHost = window.config?.goProxyHost || `https://${window.location.hostname}:5555`;
      const authEndpoint = `${proxyHost}/auth/login`;

      // Call go-ohif-proxy login endpoint
      const response = await fetch(authEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      });

      if (!response.ok) {
        throw new Error('Login failed. Please check your credentials.');
      }

      const data = await response.json();

      // Store token in sessionStorage
      window.sessionStorage.setItem('ohif-auth-token', data.access_token);

      // Decode token to extract role and user information
      let userInfo = data.user;

      // Update the auth context
      authContext.setUser({
        ...userInfo,
        token: data.access_token,
      });

      // Set window.config.sasGetToken for the injectAuth function
      if (window.config) {
        window.config.sasGetToken = () => window.sessionStorage.getItem('ohif-auth-token');
      }

      // Handle role-specific redirects if specified in response
      if (data.redirect_url) {
        navigate(data.redirect_url, { replace: true });
      } else {
        // Redirect to the original destination
        navigate(redirectPath, { replace: true });
      }
    } catch (error) {
      console.error('Login error:', error);
      setError(error.message || 'Failed to log in. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex h-screen w-screen items-center justify-center bg-black">
      <div className="bg-popover w-88 rounded p-8 shadow-lg">
        <div className="mb-4 flex justify-center">
          <Icons.OHIFLogo className="h-12 text-white" />
        </div>

        <h2 className="text-md text-center font-bold text-white">Login to</h2>
        <h1 className="mb-8 text-center text-2xl font-bold text-white">Cloud DICOM Viewer</h1>

        {error && <div className="mb-4 rounded bg-red-800 px-4 py-2 text-white">{error}</div>}

        <form onSubmit={handleLogin}>
          <div className="mb-4">
            <label className="mb-2 block text-sm font-bold text-white">Email</label>
            <input
              type="text"
              className="focus:shadow-outline w-full appearance-none rounded border py-2 px-3 leading-tight text-gray-700 shadow focus:outline-none"
              value={email}
              onChange={e => setEmail(e.target.value)}
              required
            />
          </div>

          <div className="mb-6">
            <label className="mb-2 block text-sm font-bold text-white">Password</label>
            <input
              type="password"
              className="focus:shadow-outline w-full appearance-none rounded border py-2 px-3 leading-tight text-gray-700 shadow focus:outline-none"
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
            />
          </div>

          <div className="flex items-center justify-center">
            <button
              type="submit"
              className="focus:shadow-outline w-full rounded bg-blue-500 py-2 px-4 font-bold text-white hover:bg-blue-700 focus:outline-none"
              disabled={isLoading}
            >
              {isLoading ? 'Logging in...' : 'Log In'}
            </button>
          </div>
          <p className="text-muted-foreground mt-8 text-center text-sm">
            Powered by OHIF & Google Cloud DICOM Storage
          </p>
        </form>
      </div>
    </div>
  );
};

export default Login;
