import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMsal } from '@azure/msal-react';
import { useAuthStore } from '../lib/auth';
import { loginRequest } from '../lib/msalConfig';
import { apiClient } from '../lib/api';
import type { UserRole } from '../types/api';

function getRoleRedirect(role: string): string {
  if (role === 'linguist' || role === 'reviewer') return '/qc/queue';
  return '/';
}

export function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [microsoftLoading, setMicrosoftLoading] = useState(false);
  const [showLocalLogin, setShowLocalLogin] = useState(false);
  const navigate = useNavigate();
  const { login, isLoading, setUser } = useAuthStore();
  const { instance } = useMsal();

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

    try {
      await login(email, password);
      const { user: loggedInUser } = useAuthStore.getState();
      navigate(getRoleRedirect(loggedInUser?.role || ''));
    } catch (err: unknown) {
      console.error('Login failed:', err);
      const error = err as { code?: string; response?: { data?: { message?: string } }; message?: string };
      if (error.code === 'ERR_NETWORK' || !error.response) {
        setError('Network error: Cannot connect to server. Please check if the backend is running.');
      } else {
        setError(error.response?.data?.message || error.message || 'Login failed. Please check your credentials.');
      }
    }
  };

  const handleMicrosoftLogin = async () => {
    setError('');
    setMicrosoftLoading(true);

    try {
      // Login with popup
      const response = await instance.loginPopup(loginRequest);

      // Get ID token from Microsoft response
      const idToken = response.idToken;

      // Send ID token to our backend for validation and user creation
      const loginResponse = await apiClient.loginWithMicrosoft(idToken);

      // Set user in auth store
      setUser({
        id: loginResponse.user_id,
        email: loginResponse.email,
        full_name: loginResponse.full_name,
        role: loginResponse.role as UserRole,
        auth_provider: loginResponse.auth_provider,
        is_active: true,
        created_at: new Date().toISOString(),
      });

      navigate(getRoleRedirect(loginResponse.role));
    } catch (err: unknown) {
      console.error('Microsoft login failed:', err);
      const error = err as { code?: string; response?: { data?: { detail?: string; message?: string } }; message?: string };

      if (error.code === 'ERR_NETWORK' || !error.response) {
        setError('Network error: Cannot connect to server. Please check if the backend is running.');
      } else if (error.message?.includes('user_cancelled') || error.message?.includes('AADB2C90091')) {
        // User cancelled the popup - don't show error
        setError('');
      } else {
        setError(error.response?.data?.detail || error.response?.data?.message || error.message || 'Microsoft authentication failed. Please try again.');
      }
    } finally {
      setMicrosoftLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex">
      {/* Left side - Branding */}
      <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-blue-600 via-purple-600 to-blue-800">
        <div className="flex flex-col justify-center px-12 py-24">
          <div className="mb-8">
            <div className="flex items-center space-x-4 mb-6">
              <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                <span className="text-white text-xl font-bold">VA</span>
              </div>
              <div>
                <h1 className="text-3xl font-bold text-white">Video Access</h1>
                <p className="text-blue-100">Accessibility Platform</p>
              </div>
            </div>
          </div>
          
          <div className="space-y-6 text-white">
            <h2 className="text-4xl font-bold leading-tight">
              Make your videos accessible to everyone
            </h2>
            <p className="text-xl text-blue-100 leading-relaxed">
              AI-powered captions, audio descriptions, and multi-language support for professional video accessibility.
            </p>
            
            <div className="space-y-4 mt-8">
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center">
                  <span>🤖</span>
                </div>
                <span className="text-blue-100">AI-powered processing</span>
              </div>
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center">
                  <span>🌍</span>
                </div>
                <span className="text-blue-100">Multi-language support</span>
              </div>
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center">
                  <span>✅</span>
                </div>
                <span className="text-blue-100">Quality assurance workflow</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Right side - Login Form */}
      <div className="flex-1 flex items-center justify-center px-4 py-12 bg-gray-50">
        <div className="max-w-md w-full">
          <div className="bg-white rounded-2xl shadow-xl p-8">
            <div className="text-center mb-8">
              <div className="lg:hidden mb-6">
                <div className="flex items-center justify-center space-x-3 mb-4">
                  <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                    <span className="text-white font-bold">VA</span>
                  </div>
                  <h1 className="text-2xl font-bold text-gray-900">Video Access</h1>
                </div>
              </div>
              <h2 className="text-3xl font-bold text-gray-900 mb-2">Welcome back!</h2>
              <p className="text-gray-600">Sign in to your account to continue</p>
            </div>

            {/* Error Display */}
            {error && (
              <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center mb-6">
                <span className="text-red-500 mr-2">❌</span>
                <span className="text-red-700 text-sm">{error}</span>
              </div>
            )}

            {/* Local Login Form (Conditionally Shown) */}
            {showLocalLogin && (
              <form className="space-y-6 mb-6" onSubmit={handleSubmit}>
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
                    Email Address
                  </label>
                  <input
                    id="email"
                    name="email"
                    type="email"
                    autoComplete="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter your email"
                  />
                </div>

                <div>
                  <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
                    Password
                  </label>
                  <input
                    id="password"
                    name="password"
                    type="password"
                    autoComplete="current-password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                    placeholder="Enter your password"
                  />
                </div>

                <button
                  type="submit"
                  disabled={isLoading || microsoftLoading}
                  className="w-full bg-gradient-to-r from-blue-500 to-blue-600 text-white py-3 px-4 rounded-lg font-semibold hover:from-blue-600 hover:to-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 transform hover:scale-105 disabled:transform-none shadow-lg hover:shadow-xl"
                >
                  {isLoading ? (
                    <div className="flex items-center justify-center">
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                      Signing in...
                    </div>
                  ) : (
                    'Sign In'
                  )}
                </button>
              </form>
            )}

            {/* Divider (Only when local form is visible) */}
            {showLocalLogin && (
              <div className="relative my-6">
                <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 text-gray-500">Or continue with</span>
                </div>
              </div>
            )}

            {/* Microsoft Sign In Button (Always Visible) */}
            <button
              type="button"
              onClick={handleMicrosoftLogin}
              disabled={isLoading || microsoftLoading}
              className="w-full bg-white border-2 border-gray-300 text-gray-700 py-3 px-4 rounded-lg font-semibold hover:bg-gray-50 hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-md hover:shadow-lg"
            >
              {microsoftLoading ? (
                <div className="flex items-center justify-center">
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-gray-700 mr-2"></div>
                  Signing in with Microsoft...
                </div>
              ) : (
                <div className="flex items-center justify-center">
                  <svg className="w-5 h-5 mr-2" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="1" y="1" width="9" height="9" fill="#F25022"/>
                    <rect x="1" y="11" width="9" height="9" fill="#00A4EF"/>
                    <rect x="11" y="1" width="9" height="9" fill="#7FBA00"/>
                    <rect x="11" y="11" width="9" height="9" fill="#FFB900"/>
                  </svg>
                  Sign in with Microsoft
                </div>
              )}
            </button>

            {/* Local Login Link (Only when form is hidden) */}
            {!showLocalLogin && (
              <div className="mt-6 text-center">
                <button
                  type="button"
                  onClick={() => setShowLocalLogin(true)}
                  className="text-sm text-gray-500 hover:text-gray-700 underline transition-colors"
                >
                  Local login
                </button>
              </div>
            )}

            {/* Support Contact */}
            <div className="mt-8 pt-6 border-t border-gray-200 text-center">
              <p className="text-xs text-gray-600">
                Need help? Contact{' '}
                <a href="mailto:vadymsamoilenko@oliver.agency" className="text-blue-600 hover:text-blue-700 font-medium">
                  vadymsamoilenko@oliver.agency
                </a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}