import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Mail } from 'lucide-react';
import { useMutation } from '@tanstack/react-query';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Button } from '@tamagui/button';
import { ADMIN_LOGIN_PATH } from '../constants';
import { MobileCard } from './components/Primitives';
import { MobileField, MobileInput } from './components/FormControls';
import { ADMIN_GRADIENTS, useAdminTheme } from './theme';

type ResetResponse = {
  status: string;
};

async function requestPasswordReset(email: string): Promise<ResetResponse> {
  const response = await fetch('/api/v1/tenant-auth/forgot-password', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({ email }),
  });

  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('Request failed.');
  }

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

export default function ForgotPasswordPage() {
  const { t } = useTranslation('auth');
  const navigate = useNavigate();
  const { text, muted, border, surface, accentSoft, primary, dangerBg, dangerText } = useAdminTheme();
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState<string | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const safeAreaStyle: React.CSSProperties = {
    paddingTop: 'calc(env(safe-area-inset-top, 0px) + 16px)',
    paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 16px)',
  };

  const mutation = useMutation({
    mutationKey: ['tenantAdminForgotPassword'],
    mutationFn: requestPasswordReset,
    onSuccess: (data) => {
      setError(null);
      setStatus(data.status ?? t('login.forgot.success', 'If your account exists, we will send a reset link.'));
    },
    onError: (err: unknown) => {
      const message = err instanceof Error ? err.message : String(err);
      setError(message);
    },
  });

  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 space="$2">
            <XStack alignItems="center" space="$2">
              <XStack
                width={42}
                height={42}
                borderRadius={12}
                alignItems="center"
                justifyContent="center"
                backgroundColor="rgba(255,255,255,0.12)"
                borderWidth={1}
                borderColor="rgba(255,255,255,0.15)"
              >
                <Mail size={18} color="white" />
              </XStack>
              <Text fontSize="$lg" fontWeight="800" color="white">
                {t('login.forgot.title', 'Forgot your password?')}
              </Text>
            </XStack>
            <Text fontSize="$sm" color="rgba(255,255,255,0.7)">
              {t('login.forgot.copy', 'Enter your email address and we will send you a reset link.')}
            </Text>
          </YStack>
        </MobileCard>

        <MobileCard backgroundColor={surface} borderColor={border}>
          <YStack space="$3">
            <MobileField label={t('login.email', 'Email address')}>
              <MobileInput
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                placeholder={t('login.email_placeholder', 'name@example.com')}
                autoComplete="email"
                required
              />
            </MobileField>

            {status ? (
              <YStack borderRadius={12} padding="$2.5" borderWidth={1} borderColor={border} backgroundColor={accentSoft}>
                <Text fontSize="$sm" color={text}>
                  {status}
                </Text>
              </YStack>
            ) : null}

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

            <Button
              onPress={() => mutation.mutate(email)}
              disabled={mutation.isPending || email.length === 0}
              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)' }}
            >
              {mutation.isPending ? t('login.forgot.loading', 'Sending ...') : t('login.forgot.submit', 'Send reset link')}
            </Button>
          </YStack>
        </MobileCard>

        <Button
          onPress={() => navigate(ADMIN_LOGIN_PATH)}
          backgroundColor="transparent"
          borderColor="rgba(255,255,255,0.5)"
          borderWidth={1}
          color="white"
          height={40}
          borderRadius={12}
        >
          {t('login.forgot.back', 'Back to login')}
        </Button>
      </YStack>
    </YStack>
  );
}
