import { useMemo, useState } from 'react';
import { X } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { useLanguage } from '../contexts/LanguageContext';

interface AuthModalProps {
  onClose: () => void;
  mandatory?: boolean;
}

export default function AuthModal({ onClose, mandatory = false }: AuthModalProps) {
  const { signIn, signUp, beginGoogleOAuth, authPhase, authError } = useAuth();
  const { t } = useLanguage();

  const [mode, setMode] = useState<'signin' | 'signup'>('signin');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [localError, setLocalError] = useState('');
  const [fieldErrors, setFieldErrors] = useState<{ email?: string; password?: string; confirmPassword?: string }>({});

  const isBusy = useMemo(
    () => ['email_signing_in', 'email_signing_up', 'oauth_redirecting', 'oauth_exchanging'].includes(authPhase),
    [authPhase]
  );

  const submitText = mode === 'signup' ? t.auth.signUp : t.auth.signIn;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError('');
    const nextFieldErrors: { email?: string; password?: string; confirmPassword?: string } = {};
    const normalizedEmail = email.trim();

    if (!normalizedEmail) {
      nextFieldErrors.email = t.auth.emailRequired;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) {
      nextFieldErrors.email = t.auth.emailInvalid;
    }

    if (!password) {
      nextFieldErrors.password = t.auth.passwordRequired;
    }

    if (mode === 'signup') {
      if (password && password.length < 6) {
        nextFieldErrors.password = t.auth.passwordHint;
      }

      if (!confirmPassword) {
        nextFieldErrors.confirmPassword = t.auth.passwordRequired;
      } else if (password !== confirmPassword) {
        nextFieldErrors.confirmPassword = t.auth.passwordMismatch;
      }
    }

    setFieldErrors(nextFieldErrors);
    if (Object.keys(nextFieldErrors).length > 0) {
      return;
    }

    const result = mode === 'signup' ? await signUp(normalizedEmail, password) : await signIn(normalizedEmail, password);

    if (!result.error) {
      onClose();
    }
  };

  const handleGoogleOAuth = async () => {
    await beginGoogleOAuth();
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-gray-900">
            {mode === 'signup' ? t.auth.signUpTitle : t.auth.signInTitle}
          </h2>
          {!mandatory && (
            <button
              type="button"
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              aria-label="close"
              disabled={isBusy}
            >
              <X size={20} />
            </button>
          )}
        </div>

        <div className="grid grid-cols-2 gap-2 rounded-lg bg-gray-100 p-1 mb-4">
          <button
            type="button"
            onClick={() => {
              setMode('signin');
              setFieldErrors({});
              setLocalError('');
            }}
            aria-pressed={mode === 'signin'}
            disabled={isBusy}
            className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${
              mode === 'signin' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            {t.auth.signIn}
          </button>
          <button
            type="button"
            onClick={() => {
              setMode('signup');
              setFieldErrors({});
              setLocalError('');
            }}
            aria-pressed={mode === 'signup'}
            disabled={isBusy}
            className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${
              mode === 'signup' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            {t.auth.signUp}
          </button>
        </div>

        <form onSubmit={handleSubmit} noValidate className="space-y-4">
          <div>
            <label htmlFor="auth-email" className="block text-sm font-medium text-gray-700 mb-1">
              {t.auth.email}
            </label>
            <input
              id="auth-email"
              type="email"
              value={email}
              onChange={(e) => {
                setEmail(e.target.value);
                if (fieldErrors.email) {
                  setFieldErrors((prev) => ({ ...prev, email: undefined }));
                }
              }}
              className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                fieldErrors.email ? 'border-red-400' : 'border-gray-300'
              }`}
              placeholder="your@email.com"
              required
              disabled={isBusy}
            />
            {fieldErrors.email && <p className="mt-1 text-xs text-red-600">{fieldErrors.email}</p>}
            {mode === 'signup' && (
              <p className="mt-1 text-xs text-gray-500">{t.auth.emailHint}</p>
            )}
          </div>

          <div>
            <label htmlFor="auth-password" className="block text-sm font-medium text-gray-700 mb-1">
              {t.auth.password}
            </label>
            <input
              id="auth-password"
              type="password"
              value={password}
              onChange={(e) => {
                setPassword(e.target.value);
                if (fieldErrors.password) {
                  setFieldErrors((prev) => ({ ...prev, password: undefined }));
                }
              }}
              className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                fieldErrors.password ? 'border-red-400' : 'border-gray-300'
              }`}
              placeholder="••••••••"
              required
              minLength={6}
              disabled={isBusy}
            />
            {fieldErrors.password && <p className="mt-1 text-xs text-red-600">{fieldErrors.password}</p>}
            {mode === 'signup' && (
              <p className="mt-1 text-xs text-gray-500">{t.auth.passwordHint}</p>
            )}
          </div>

          {mode === 'signup' && (
            <div>
              <label htmlFor="auth-password-confirm" className="block text-sm font-medium text-gray-700 mb-1">
                {t.auth.confirmPassword}
              </label>
              <input
                id="auth-password-confirm"
                type="password"
                value={confirmPassword}
                onChange={(e) => {
                  setConfirmPassword(e.target.value);
                  if (fieldErrors.confirmPassword) {
                    setFieldErrors((prev) => ({ ...prev, confirmPassword: undefined }));
                  }
                }}
                className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
                  fieldErrors.confirmPassword ? 'border-red-400' : 'border-gray-300'
                }`}
                placeholder="••••••••"
                required
                minLength={6}
                disabled={isBusy}
              />
              {fieldErrors.confirmPassword && <p className="mt-1 text-xs text-red-600">{fieldErrors.confirmPassword}</p>}
            </div>
          )}

          {(localError || authError) && (
            <div className="p-3 bg-red-100 border border-red-300 text-red-700 rounded-lg text-sm font-medium">
              {t.auth.error}: {localError || authError}
            </div>
          )}

          <button
            type="submit"
            disabled={isBusy}
            className="w-full py-3 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium disabled:opacity-80 disabled:cursor-wait"
          >
            {submitText}
          </button>

          <div className="relative py-1">
            <div className="absolute inset-0 flex items-center" aria-hidden="true">
              <div className="w-full border-t border-gray-200" />
            </div>
            <div className="relative flex justify-center text-xs">
              <span className="bg-white px-2 text-gray-400">OR</span>
            </div>
          </div>

          <button
            type="button"
            onClick={handleGoogleOAuth}
            disabled={isBusy}
            className="w-full py-3 px-4 border border-gray-300 text-gray-800 rounded-lg hover:bg-gray-50 transition-colors font-medium disabled:opacity-80 disabled:cursor-wait inline-flex items-center justify-center gap-2"
          >
            <img
              src="https://upload.wikimedia.org/wikipedia/commons/7/7e/Gmail_icon_%282020%29.svg"
              alt=""
              aria-hidden="true"
              className="w-[18px] h-[18px]"
              loading="lazy"
              decoding="async"
            />
            {authPhase === 'oauth_redirecting' ? t.auth.oauthRedirecting : t.auth.continueWithGoogle}
          </button>
        </form>
      </div>
    </div>
  );
}
