import React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { useMutation } from '@tanstack/react-query';
import {
  ADMIN_DEFAULT_AFTER_LOGIN_PATH,
  ADMIN_EVENTS_PATH,
  ADMIN_PUBLIC_FORGOT_PASSWORD_PATH,
  ADMIN_PUBLIC_HELP_PATH,
} from '../constants';
import { useAuth } from '../auth/context';
import { resolveReturnTarget } from '../lib/returnTo';
import { useInstallPrompt } from './hooks/useInstallPrompt';
import { getInstallBannerDismissed, setInstallBannerDismissed, shouldShowInstallBanner } from './lib/installBanner';
import { MobileInstallBanner } from './components/MobileInstallBanner';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Button } from '@tamagui/button';
import { MobileCard } from './components/Primitives';
import { MobileField, MobileInput } from './components/FormControls';
import { ADMIN_GRADIENTS, useAdminTheme } from './theme';

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 installPrompt = useInstallPrompt();
  const { text, muted, primary, dangerBg, dangerText, border, surface } = useAdminTheme();
  const safeAreaStyle: React.CSSProperties = {
    paddingTop: 'calc(env(safe-area-inset-top, 0px) + 16px)',
    paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 16px)',
  };

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

  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, encodedFinal } = React.useMemo(
    () => resolveReturnTarget(rawReturnTo, fallbackTarget),
    [rawReturnTo, fallbackTarget],
  );

  const oauthMessage = React.useMemo(() => {
    if (!oauthError) {
      return null;
    }

    const fallback = oauthDescription ?? oauthError;

    return t(`login.oauth_errors.${oauthError}`, { defaultValue: fallback });
  }, [oauthDescription, oauthError, t]);

  const googleHref = React.useMemo(() => {
    if (!encodedFinal) {
      return '/event-admin/auth/google';
    }

    const params = new URLSearchParams({ return_to: encodedFinal });

    return `/event-admin/auth/google?${params.toString()}`;
  }, [encodedFinal]);

  const facebookHref = React.useMemo(() => {
    if (!encodedFinal) {
      return '/event-admin/auth/facebook';
    }

    const params = new URLSearchParams({ return_to: encodedFinal });

    return `/event-admin/auth/facebook?${params.toString()}`;
  }, [encodedFinal]);

  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 [isRedirectingToGoogle, setIsRedirectingToGoogle] = React.useState(false);
  const [isRedirectingToFacebook, setIsRedirectingToFacebook] = React.useState(false);
  const [installBannerDismissed, setInstallBannerDismissedState] = React.useState(() => getInstallBannerDismissed());
  const installBanner = shouldShowInstallBanner(
    {
      isInstalled: installPrompt.isInstalled,
      isStandalone: installPrompt.isStandalone,
      canInstall: installPrompt.canInstall,
      isIos: installPrompt.isIos,
    },
    installBannerDismissed,
  );

  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 isFormValid = login.trim().length > 0 && password.length > 0;

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

  const handleGoogleLogin = React.useCallback(() => {
    if (typeof window === 'undefined') {
      return;
    }

    setIsRedirectingToGoogle(true);
    window.location.assign(googleHref);
  }, [googleHref]);

  const handleFacebookLogin = React.useCallback(() => {
    if (typeof window === 'undefined') {
      return;
    }

    setIsRedirectingToFacebook(true);
    window.location.assign(facebookHref);
  }, [facebookHref]);

  return (
    <YStack
      minHeight="100vh"
      alignItems="center"
      justifyContent="center"
      paddingHorizontal="$4"
      paddingVertical="$5"
      style={{ ...safeAreaStyle, background: ADMIN_GRADIENTS.loginBackground }}
    >
      <YStack width="100%" maxWidth={520} space="$4">
        <MobileCard backgroundColor="rgba(15, 23, 42, 0.6)" borderColor="rgba(255,255,255,0.12)">
          <YStack alignItems="center" space="$3">
            <XStack
              width={56}
              height={56}
              borderRadius={16}
              alignItems="center"
              justifyContent="center"
              backgroundColor="rgba(255,255,255,0.12)"
              borderWidth={1}
              borderColor="rgba(255,255,255,0.15)"
            >
              <img src="/logo-transparent-md.png" alt={t('auth.logoAlt', 'Fotospiel')} width={40} height={40} />
            </XStack>
            <YStack alignItems="center" space="$1">
              <Text fontSize="$xl" fontWeight="800" color="white" textAlign="center">
                {t('login.panel_title', 'Fotospiel.App Event Login')}
              </Text>
              <Text fontSize="$sm" color="rgba(255,255,255,0.7)" textAlign="center">
                {t('login.panel_copy', 'Melde dich an, um Events zu planen, Fotos zu moderieren und Fotoaufgaben anzulegen.')}
              </Text>
            </YStack>
          </YStack>
        </MobileCard>

        <MobileCard backgroundColor={surface} borderColor={border}>
          <form onSubmit={handleSubmit}>
            <YStack space="$3">
              {oauthMessage ? (
                <YStack
                  borderRadius={12}
                  padding="$2.5"
                  borderWidth={1}
                  borderColor={dangerText}
                  backgroundColor={dangerBg}
                >
                  <Text fontSize="$sm" fontWeight="800" color={dangerText}>
                    {t('login.oauth_error_title', 'Login aktuell nicht moeglich')}
                  </Text>
                  <Text fontSize="$xs" color={dangerText}>
                    {oauthMessage}
                  </Text>
                </YStack>
              ) : null}
              <MobileField
                label={t('login.email', 'E-Mail-Adresse')}
                hint={t('login.email_hint', 'Dein Benutzername ist deine E-Mail-Adresse.')}
              >
                <MobileInput
                  id="login-mobile"
                  type="email"
                  autoComplete="username"
                  value={login}
                  onChange={(e) => setLogin(e.target.value)}
                  placeholder={t('login.email_placeholder', 'name@example.com')}
                  required
                />
              </MobileField>

            <MobileField label={t('login.password', 'Passwort')}>
              <MobileInput
                id="password-mobile"
                type="password"
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('login.password_placeholder', '••••••••')}
                required
              />
            </MobileField>

            <Button
              type="button"
              onPress={() => navigate(ADMIN_PUBLIC_FORGOT_PASSWORD_PATH)}
              backgroundColor="transparent"
              borderColor="transparent"
              color={muted}
              height={32}
              alignSelf="flex-start"
              paddingHorizontal={0}
            >
              {t('login.forgot.link', 'Forgot your password?')}
            </Button>

              {error ? (
                <YStack
                  borderRadius={12}
                  padding="$2.5"
                  borderWidth={1}
                  borderColor={dangerText}
                  backgroundColor={dangerBg}
                >
                  <Text fontSize="$sm" color={dangerText}>
                    {error}
                  </Text>
                </YStack>
              ) : null}

              <Button
                type="submit"
                disabled={isSubmitting || !isFormValid}
                height={52}
                borderRadius={16}
                backgroundColor={primary}
                borderColor="transparent"
                color="white"
                fontWeight="800"
                pressStyle={{ opacity: 0.9 }}
                style={{ boxShadow: '0 12px 24px rgba(255, 90, 95, 0.25)' }}
              >
                <XStack alignItems="center" space="$2">
                  <Loader2 size={16} className={isSubmitting ? 'animate-spin' : ''} />
                  <Text fontSize="$sm" color="white" fontWeight="800">
                    {isSubmitting ? t('login.loading', 'Anmeldung …') : t('login.submit', 'Anmelden')}
                  </Text>
                </XStack>
              </Button>

              <Button
                type="button"
                onPress={handleGoogleLogin}
                disabled={isRedirectingToGoogle || isSubmitting}
                height={52}
                borderRadius={16}
                backgroundColor={surface}
                borderColor={border}
                borderWidth={1}
                color={text}
              >
                <XStack alignItems="center" space="$2">
                  {isRedirectingToGoogle ? (
                    <Loader2 size={16} className="animate-spin" />
                  ) : (
                    <GoogleIcon size={18} />
                  )}
                  <Text fontSize="$sm" color={text} fontWeight="700">
                    {t('login.google_cta', 'Mit Google anmelden')}
                  </Text>
                </XStack>
              </Button>

              <Button
                type="button"
                onPress={handleFacebookLogin}
                disabled={isRedirectingToFacebook || isSubmitting}
                height={52}
                borderRadius={16}
                backgroundColor={surface}
                borderColor={border}
                borderWidth={1}
                color={text}
              >
                <XStack alignItems="center" space="$2">
                  {isRedirectingToFacebook ? (
                    <Loader2 size={16} className="animate-spin" />
                  ) : (
                    <FacebookIcon size={18} />
                  )}
                  <Text fontSize="$sm" color={text} fontWeight="700">
                    {t('login.facebook_cta', 'Mit Facebook anmelden')}
                  </Text>
                </XStack>
              </Button>
            </YStack>
          </form>
        </MobileCard>

        <MobileInstallBanner
          state={installBanner}
          density="compact"
          onInstall={installPrompt.canInstall ? () => void installPrompt.promptInstall() : undefined}
          onDismiss={() => {
            setInstallBannerDismissed(true);
            setInstallBannerDismissedState(true);
          }}
        />

        <YStack alignItems="center" space="$2">
          <Text fontSize="$xs" color={muted} textAlign="center">
            {t('login.support', 'Fragen? Schreib uns an support@fotospiel.de oder antworte direkt auf deine Einladung.')}
          </Text>
          <Button
            onPress={() => navigate(ADMIN_PUBLIC_HELP_PATH)}
            backgroundColor="transparent"
            borderColor="rgba(255,255,255,0.5)"
            borderWidth={1}
            color="white"
            height={40}
            borderRadius={12}
          >
            {t('login.faq', 'Hilfe & FAQ')}
          </Button>
        </YStack>
      </YStack>
    </YStack>
  );
}

function GoogleIcon({ size = 18 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden>
      <path
        fill="#EA4335"
        d="M12 11.999v4.8h6.7c-.3 1.7-2 4.9-6.7 4.9-4 0-7.4-3.3-7.4-7.4S8 6 12 6c2.3 0 3.9 1 4.8 1.9l3.3-3.2C18.1 2.6 15.3 1 12 1 5.9 1 1 5.9 1 12s4.9 11 11 11c6.3 0 10.5-4.4 10.5-10.6 0-.7-.1-1.2-.2-1.8H12z"
      />
    </svg>
  );
}

function FacebookIcon({ size = 18 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden>
      <path
        fill="#1877F2"
        d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
      />
    </svg>
  );
}
