import React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Loader2, Lock, Mail } from 'lucide-react';
import { useMutation } from '@tanstack/react-query';
import { adminPath, ADMIN_DEFAULT_AFTER_LOGIN_PATH, ADMIN_EVENTS_PATH } from '../constants';
import { useAuth } from '../auth/context';
import { resolveReturnTarget } from '../lib/returnTo';

type LoginResponse = {
  token: string;
  token_type: string;
  abilities: string[];
};

async function performLogin(payload: { login: string; password: string; return_to?: string | null }): Promise<LoginResponse> {
  const response = await fetch('/api/v1/tenant-auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({
      ...payload,
      remember: true,
    }),
  });

  if (response.status === 422) {
    const data = await response.json();
    const errors = data.errors ?? {};
    const flattened = Object.values(errors).flat();
    throw new Error(flattened.join(' ') || 'Validation failed');
  }

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

  return (await response.json()) as LoginResponse;
}

export default function MobileLoginPage() {
  const { status, applyToken, abilities } = useAuth();
  const { t } = useTranslation('auth');
  const location = useLocation();
  const navigate = useNavigate();

  const searchParams = React.useMemo(() => new URLSearchParams(location.search), [location.search]);
  const rawReturnTo = searchParams.get('return_to');

  const computeDefaultAfterLogin = React.useCallback(
    (abilityList?: string[]) => {
      const source = abilityList ?? abilities;
      return source.includes('tenant-admin') ? ADMIN_DEFAULT_AFTER_LOGIN_PATH : ADMIN_EVENTS_PATH;
    },
    [abilities],
  );

  const fallbackTarget = computeDefaultAfterLogin();
  const { finalTarget } = React.useMemo(
    () => resolveReturnTarget(rawReturnTo, fallbackTarget),
    [rawReturnTo, fallbackTarget],
  );

  React.useEffect(() => {
    if (status === 'authenticated') {
      navigate(finalTarget, { replace: true });
    }
  }, [finalTarget, navigate, status]);

  const [login, setLogin] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState<string | null>(null);

  const mutation = useMutation({
    mutationKey: ['tenantAdminLoginMobile'],
    mutationFn: performLogin,
    onError: (err: unknown) => {
      const message = err instanceof Error ? err.message : String(err);
      setError(message);
    },
    onSuccess: async (data) => {
      setError(null);
      await applyToken(data.token, data.abilities ?? []);
      const postLoginFallback = computeDefaultAfterLogin(data.abilities ?? []);
      const { finalTarget: successTarget } = resolveReturnTarget(rawReturnTo, postLoginFallback);
      navigate(successTarget, { replace: true });
    },
  });

  const isSubmitting =
    (mutation as { isPending?: boolean; isLoading?: boolean }).isPending ??
    (mutation as { isPending?: boolean; isLoading?: boolean }).isLoading ??
    false;

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    mutation.mutate({
      login,
      password,
      return_to: rawReturnTo,
    });
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-[#0b1020] via-[#0f172a] to-[#0b1020] px-5 py-10 text-white">
      <div className="w-full max-w-md space-y-8 rounded-3xl border border-white/10 bg-white/5 p-8 shadow-2xl shadow-blue-500/10 backdrop-blur-lg">
        <div className="flex flex-col items-center gap-3 text-center">
          <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/10 ring-1 ring-white/15">
            <img src="/logo-transparent-md.png" alt="Fotospiel" className="h-10 w-10" />
          </div>
          <h1 className="text-2xl font-semibold tracking-tight">{t('login.panel_title', 'Team Login')}</h1>
          <p className="text-sm text-white/70">
            {t('login.panel_copy', 'Melde dich an, um Events, Fotos und Aufgaben zu verwalten.')}
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <label className="text-sm font-semibold text-white/90" htmlFor="login-mobile">
              {t('login.username_or_email', 'E-Mail oder Benutzername')}
            </label>
            <div className="flex items-center gap-2 rounded-2xl border border-white/10 bg-white/10 px-3 py-3">
              <Mail size={16} className="text-white/70" />
              <input
                id="login-mobile"
                type="text"
                autoComplete="username"
                value={login}
                onChange={(e) => setLogin(e.target.value)}
                placeholder={t('login.username_or_email_placeholder', 'name@example.com')}
                className="w-full bg-transparent text-sm text-white placeholder:text-white/50 focus:outline-none"
                required
              />
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold text-white/90" htmlFor="password-mobile">
              {t('login.password', 'Passwort')}
            </label>
            <div className="flex items-center gap-2 rounded-2xl border border-white/10 bg-white/10 px-3 py-3">
              <Lock size={16} className="text-white/70" />
              <input
                id="password-mobile"
                type="password"
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('login.password_placeholder', '••••••••')}
                className="w-full bg-transparent text-sm text-white placeholder:text-white/50 focus:outline-none"
                required
              />
            </div>
          </div>

          {error ? (
            <div className="rounded-2xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-sm text-rose-100">
              {error}
            </div>
          ) : null}

          <button
            type="submit"
            disabled={isSubmitting}
            className="flex h-12 w-full items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-[#2563eb] via-[#3b82f6] to-[#22d3ee] text-sm font-semibold text-white shadow-lg shadow-blue-500/25 transition hover:brightness-110 disabled:opacity-70"
          >
            <Loader2 className={`h-4 w-4 animate-spin ${isSubmitting ? 'opacity-100' : 'opacity-0'}`} />
            <span>{isSubmitting ? t('login.loading', 'Anmeldung …') : t('login.submit', 'Anmelden')}</span>
          </button>
        </form>

        <div className="text-center text-xs text-white/60">
          {t('login.support', 'Fragen? Schreib uns an support@fotospiel.de oder antworte direkt auf deine Einladung.')}
        </div>

        <div className="text-center">
          <button
            type="button"
            onClick={() => navigate(adminPath('/faq'))}
            className="text-xs font-semibold text-white/70 underline underline-offset-4"
          >
            {t('login.faq', 'Hilfe & FAQ')}
          </button>
        </div>
      </div>
    </div>
  );
}
