/**
 * Platform Login Page Component
 * Secure login page exclusively for platform staff (superuser, platform_manager, platform_support)
 * This page is intentionally not linked publicly - platform staff must know the URL
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLogin } from '../../hooks/useAuth';
import { useNavigate } from 'react-router-dom';
import { AlertCircle, Loader2, Mail, Lock, ArrowRight, Shield } from 'lucide-react';
import { DevQuickLogin } from '../../components/DevQuickLogin';

const PlatformLoginPage: React.FC = () => {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const navigate = useNavigate();
  const loginMutation = useLogin();

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

    loginMutation.mutate(
      { email, password },
      {
        onSuccess: (data) => {
          // Check if MFA is required
          if (data.mfa_required) {
            sessionStorage.setItem('mfa_challenge', JSON.stringify({
              user_id: data.user_id,
              mfa_methods: data.mfa_methods,
              phone_last_4: data.phone_last_4,
            }));
            navigate('/mfa-verify');
            return;
          }

          const user = data.user!;

          // Platform login ONLY allows platform users
          const isPlatformUser = ['superuser', 'platform_manager', 'platform_support'].includes(user.role);

          if (!isPlatformUser) {
            // Non-platform users cannot login here
            setError(t('auth.invalidCredentials'));
            return;
          }

          // Platform user logged in successfully - go to dashboard
          navigate('/platform/dashboard');
        },
        onError: (err: any) => {
          setError(err.response?.data?.error || t('auth.invalidCredentials'));
        },
      }
    );
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-900 px-4 py-12">
      <div className="w-full max-w-md">
        {/* Platform Badge */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-brand-600/10 mb-4">
            <Shield className="w-8 h-8 text-brand-500" />
          </div>
          <h1 className="text-2xl font-bold text-white tracking-tight">
            {t('auth.platformLogin.title')}
          </h1>
          <p className="mt-2 text-sm text-gray-400">
            {t('auth.platformLogin.subtitle')}
          </p>
        </div>

        {/* Login Card */}
        <div className="bg-gray-800 rounded-xl shadow-xl border border-gray-700 p-8">
          {error && (
            <div className="mb-6 rounded-lg bg-red-900/30 p-4 border border-red-800/50 animate-in fade-in slide-in-from-top-2">
              <div className="flex">
                <div className="flex-shrink-0">
                  <AlertCircle className="h-5 w-5 text-red-400" aria-hidden="true" />
                </div>
                <div className="ml-3">
                  <h3 className="text-sm font-medium text-red-200">
                    {t('auth.authError')}
                  </h3>
                  <div className="mt-1 text-sm text-red-300">
                    {error}
                  </div>
                </div>
              </div>
            </div>
          )}

          <form className="space-y-6" onSubmit={handleSubmit}>
            {/* Email */}
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-1">
                {t('auth.email')}
              </label>
              <div className="relative rounded-md shadow-sm">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Mail className="h-5 w-5 text-gray-500" aria-hidden="true" />
                </div>
                <input
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required
                  className="focus:ring-brand-500 focus:border-brand-500 block w-full pl-10 sm:text-sm border-gray-600 rounded-lg py-3 bg-gray-700 text-white placeholder-gray-400 transition-colors"
                  placeholder={t('auth.enterEmail')}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>
            </div>

            {/* Password */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-1">
                {t('auth.password')}
              </label>
              <div className="relative rounded-md shadow-sm">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock className="h-5 w-5 text-gray-500" aria-hidden="true" />
                </div>
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required
                  className="focus:ring-brand-500 focus:border-brand-500 block w-full pl-10 sm:text-sm border-gray-600 rounded-lg py-3 bg-gray-700 text-white placeholder-gray-400 transition-colors"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
              </div>
            </div>

            <button
              type="submit"
              disabled={loginMutation.isPending}
              className="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-brand-500 disabled:opacity-70 disabled:cursor-not-allowed transition-all duration-200 ease-in-out transform active:scale-[0.98]"
            >
              {loginMutation.isPending ? (
                <span className="flex items-center gap-2">
                  <Loader2 className="animate-spin h-5 w-5" />
                  {t('auth.signingIn')}
                </span>
              ) : (
                <span className="flex items-center gap-2">
                  {t('auth.signIn')}
                  <ArrowRight className="h-4 w-4" />
                </span>
              )}
            </button>
          </form>
        </div>

        {/* Dev Quick Login - Platform Staff Only */}
        <DevQuickLogin embedded filter="platform" />

        {/* Footer */}
        <div className="mt-8 text-center text-xs text-gray-500">
          © {new Date().getFullYear()} SmoothSchedule. All rights reserved.
        </div>
      </div>
    </div>
  );
};

export default PlatformLoginPage;
