import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { loadFrappeTranslations } from '../i18n';
import apiService, { ApiError } from '../services/apiService';
import { persistUserProfileAndGetRoute, resolveAuthenticatedRoute } from '../utils/appRouting';

const SESSION_STORAGE_FLAG_KEY = 'asm_show_after_password_reset';

interface LoginFormData {
  email: string;
  password: string;
}

const Login: React.FC = () => {
  const [formData, setFormData] = useState<LoginFormData>({
    email: '',
    password: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [forgotOpen, setForgotOpen] = useState(false);
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotLoading, setForgotLoading] = useState(false);
  const [forgotError, setForgotError] = useState<string | null>(null);
  const [forgotMessage, setForgotMessage] = useState<string | null>(null);
  const [pwdResetBusy, setPwdResetBusy] = useState(false);
  const [postResetBanner, setPostResetBanner] = useState(false);
  const manualLoginHandledRef = useRef(false);
  const forgotAbortRef = useRef<AbortController | null>(null);

  const navigate = useNavigate();
  const location = useLocation();
  const { t } = useTranslation();
  const baseUrl = import.meta.env.BASE_URL || '/';
  const logoVersion = import.meta.env.DEV
    ? `?v=${Date.now()}`
    : `?v=1765198405`;

  const closeForgotModal = useCallback(() => {
    forgotAbortRef.current?.abort();
    forgotAbortRef.current = null;
    setForgotOpen(false);
    setForgotEmail('');
    setForgotError(null);
    setForgotMessage(null);
    setForgotLoading(false);
  }, []);

  const openForgotModal = () => {
    setForgotOpen(true);
    setForgotError(null);
    setForgotMessage(null);
  };

  useEffect(() => {
    if (!forgotOpen) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeForgotModal();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [forgotOpen, closeForgotModal]);

  useEffect(() => {
    const params = new URLSearchParams(location.search);
    if (params.get('manual_login') !== '1' || manualLoginHandledRef.current) {
      return;
    }
    manualLoginHandledRef.current = true;

    const finishPostResetLogout = async () => {
      setPwdResetBusy(true);
      try {
        localStorage.removeItem('user');
        localStorage.removeItem('frappe_session_id');

        const csrfToken = await apiService.getCSRFTokenForGuest();
        const headers: Record<string, string> = {
          Accept: 'application/json',
        };
        if (csrfToken) {
          headers['X-Frappe-CSRF-Token'] = csrfToken;
        }

        await fetch('/api/method/logout', {
          method: 'POST',
          headers,
          credentials: 'include',
        }).catch(() => {
          // proceed even if logout fails
        });

        sessionStorage.setItem(SESSION_STORAGE_FLAG_KEY, '1');
        navigate('/login', { replace: true });
      } finally {
        setPwdResetBusy(false);
      }
    };

    finishPostResetLogout();
  }, [location.pathname, location.search, navigate]);

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_STORAGE_FLAG_KEY) === '1') {
      sessionStorage.removeItem(SESSION_STORAGE_FLAG_KEY);
      setPostResetBanner(true);
    }
  }, [location.pathname, location.search]);

  useEffect(() => {
    if (pwdResetBusy) return;
    const params = new URLSearchParams(location.search);
    if (params.get('manual_login') === '1') return;

    const storedUser = localStorage.getItem('user');
    if (!storedUser) {
      loadFrappeTranslations().catch(() => {
        // static translations only before login
      });
      return;
    }

    let cancelled = false;

    const verifySessionAndRedirect = async () => {
      const route = await resolveAuthenticatedRoute();
      if (cancelled) return;

      if (route) {
        navigate(route, { replace: true });
        return;
      }

      loadFrappeTranslations().catch(() => {
        // static translations only before login
      });
    };

    verifySessionAndRedirect();

    return () => {
      cancelled = true;
    };
  }, [location.pathname, location.search, navigate, pwdResetBusy]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    setError(null);
  };

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

    try {
      const response = await apiService.login(formData);

      if (response && response.message) {
        const userData = {
          ...response.message,
          email: formData.email,
        };
        localStorage.setItem('user', JSON.stringify(userData));

        if (response.message.sid) {
          apiService.setSessionId(response.message.sid);
        }

        try {
          await loadFrappeTranslations();
        } catch (err) {
          console.warn('Could not load translations after login:', err);
        }

        const route = await persistUserProfileAndGetRoute();
        navigate(route);
      } else {
        setError(t('login.loginFailed'));
      }
    } catch (err: unknown) {
      console.error('Login error:', err);
      const message = err instanceof Error ? err.message : t('login.loginFailed');
      setError(message || t('login.loginFailed'));
    } finally {
      setLoading(false);
    }
  };

  const handleDemoLogin = async () => {
    const demoUser = {
      full_name: 'Demo User',
      email: 'demo@seeraarabia.com',
      user_image: '',
      roles: ['System Manager', 'Administrator'],
    };

    localStorage.setItem('user', JSON.stringify(demoUser));

    try {
      await loadFrappeTranslations();
    } catch (err) {
      console.warn('Could not load translations after demo login:', err);
    }

    navigate('/dashboard');
  };

  const handleForgotSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = forgotEmail.trim();
    if (!trimmed) {
      setForgotError(t('login.forgotPasswordUserRequired'));
      setForgotMessage(null);
      return;
    }

    forgotAbortRef.current?.abort();
    const controller = new AbortController();
    forgotAbortRef.current = controller;

    setForgotLoading(true);
    setForgotError(null);
    setForgotMessage(null);

    try {
      await apiService.requestPasswordReset(trimmed, controller.signal);
      setForgotMessage(t('login.forgotPasswordSentSuccess'));
    } catch (err: unknown) {
      if (err instanceof ApiError) {
        if (err.code === 'NOT_FOUND') {
          setForgotError(t('login.forgotPasswordNotFound'));
        } else if (err.code === 'CANNOT_RESET') {
          setForgotError(t('login.forgotPasswordCannotReset'));
        } else if (err.code === 'FORBIDDEN') {
          setForgotError(t('login.forgotPasswordFailed'));
        } else if (err.code === 'TIMEOUT') {
          setForgotError(t('login.forgotPasswordTimeout'));
        } else {
          setForgotError(t('login.forgotPasswordFailed'));
        }
      } else {
        setForgotError(t('login.forgotPasswordFailed'));
      }
    } finally {
      setForgotLoading(false);
      if (forgotAbortRef.current === controller) {
        forgotAbortRef.current = null;
      }
    }
  };

  if (pwdResetBusy) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="flex items-center text-gray-700 dark:text-gray-300">
          <svg
            className="animate-spin -ml-1 mr-3 h-5 w-5"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
          >
            <circle
              className="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              strokeWidth="4"
            />
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            />
          </svg>
          {t('login.finishingSignOut')}
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <div className="flex justify-center mb-6">
            <div className="w-32 h-32 flex items-center justify-center bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-4">
              <img
                src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png${logoVersion}`}
                alt="Seera Arabia"
                className="w-full h-full object-contain"
                onError={(e) => {
                  const container = e.currentTarget.parentElement;
                  if (container) {
                    container.classList.add(
                      'bg-gradient-to-br',
                      'from-indigo-600',
                      'to-purple-600'
                    );
                  }
                  e.currentTarget.style.display = 'none';
                  const nextSibling = e.currentTarget.nextElementSibling;
                  if (nextSibling) {
                    nextSibling.classList.remove('hidden');
                  }
                }}
              />
              <svg
                className="w-20 h-20 hidden"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M12 2L2 7L12 12L22 7L12 2Z"
                  fill="white"
                  fillOpacity="0.9"
                />
                <path
                  d="M2 17L12 22L22 17V12L12 17L2 12V17Z"
                  fill="white"
                  fillOpacity="0.7"
                />
                <path
                  d="M12 12V17"
                  stroke="white"
                  strokeWidth="2"
                  strokeLinecap="round"
                />
              </svg>
            </div>
          </div>
          <h2 className="text-center text-3xl font-semibold text-gray-900 dark:text-white">
            {t('login.title')}
          </h2>
          <p className="mt-2 text-center text-sm font-medium text-indigo-600 dark:text-indigo-400">
            {t('login.subtitle')}
          </p>
          <p className="mt-1 text-center text-xs text-gray-600 dark:text-gray-400">
            {t('login.signIn')}
          </p>
        </div>

        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          {postResetBanner && (
            <div className="rounded-md bg-green-50 dark:bg-green-900/20 p-4 border border-green-200 dark:border-green-800">
              <p className="text-sm text-green-800 dark:text-green-300 text-center">
                {t('login.afterPasswordResetSignIn')}
              </p>
            </div>
          )}

          <div className="rounded-md shadow-sm -space-y-px">
            <div>
              <label htmlFor="email" className="sr-only">
                {t('common.email')}
              </label>
              <input
                id="email"
                name="email"
                type="email"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-800 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder={t('login.emailPlaceholder')}
                value={formData.email}
                onChange={handleChange}
              />
            </div>
            <div>
              <label htmlFor="password" className="sr-only">
                {t('common.password')}
              </label>
              <input
                id="password"
                name="password"
                type="password"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-800 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder={t('login.passwordPlaceholder')}
                value={formData.password}
                onChange={handleChange}
              />
            </div>
          </div>

          {error && (
            <div className="rounded-md bg-red-50 dark:bg-red-900/20 p-4">
              <div className="text-sm text-red-700 dark:text-red-400">{error}</div>
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? (
              <div className="flex items-center">
                <svg
                  className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  />
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  />
                </svg>
                {t('common.loading')}
              </div>
            ) : (
              t('common.login')
            )}
          </button>

          <p className="text-center -mt-2">
            <button
              type="button"
              onClick={openForgotModal}
              className="text-sm font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300"
            >
              {t('login.forgotPassword')}
            </button>
          </p>

          <div className="hidden relative pt-2" aria-hidden="true">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300 dark:border-gray-600" />
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-gray-50 dark:bg-gray-900 text-gray-500 dark:text-gray-400">
                or
              </span>
            </div>
          </div>

          <button
            type="button"
            onClick={handleDemoLogin}
            className="hidden w-full flex justify-center py-2 px-4 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            aria-hidden="true"
            tabIndex={-1}
          >
            🚀 {t('login.demoLogin')}
          </button>
        </form>
      </div>

      {forgotOpen && (
        <div
          className="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm"
          onClick={closeForgotModal}
          role="presentation"
        >
          <div
            className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg p-6"
            onClick={(e) => e.stopPropagation()}
            role="dialog"
            aria-modal="true"
            aria-labelledby="forgot-password-title"
          >
            <div className="flex items-start justify-between gap-4 mb-4">
              <h3
                id="forgot-password-title"
                className="text-xl font-semibold text-gray-900 dark:text-white"
              >
                {t('login.forgotPassword')}
              </h3>
              <button
                type="button"
                onClick={closeForgotModal}
                className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-2xl leading-none shrink-0"
                aria-label={t('login.forgotPasswordClose')}
              >
                ×
              </button>
            </div>

            <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
              {t('login.forgotPasswordHint')}
            </p>

            <form onSubmit={handleForgotSubmit}>
              <input
                type="text"
                autoComplete="username"
                className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder={t('login.forgotPasswordUserPlaceholder')}
                value={forgotEmail}
                onChange={(e) => {
                  setForgotEmail(e.target.value);
                  setForgotError(null);
                  setForgotMessage(null);
                }}
                disabled={forgotLoading}
              />

              {forgotError && (
                <div className="mt-4 rounded-md bg-red-50 dark:bg-red-900/20 p-3">
                  <p className="text-sm text-red-700 dark:text-red-400">{forgotError}</p>
                </div>
              )}

              {forgotMessage && (
                <div className="mt-4 rounded-md bg-green-50 dark:bg-green-900/20 p-3">
                  <p className="text-sm text-green-700 dark:text-green-400">{forgotMessage}</p>
                </div>
              )}

              <div className="flex justify-end gap-3 mt-6">
                <button
                  type="button"
                  onClick={closeForgotModal}
                  disabled={forgotLoading}
                  className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                >
                  {t('common.cancel')}
                </button>
                <button
                  type="submit"
                  disabled={forgotLoading}
                  className="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {forgotLoading ? t('common.loading') : t('login.forgotPasswordSubmit')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Login;
