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 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 [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 handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    mutation.mutate({
      login,
      password,
      return_to: rawReturnTo,
    });
  };

  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 Aufgaben anzulegen.')}
              </Text>
            </YStack>
          </YStack>
        </MobileCard>

        <MobileCard backgroundColor={surface} borderColor={border}>
          <form onSubmit={handleSubmit}>
            <YStack space="$3">
              <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}
                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>
            </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>
  );
}
