import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Lock } 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;
};

type FieldErrors = Record<string, string[]>;

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

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

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

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

export default function ResetPasswordPage() {
  const { t } = useTranslation('auth');
  const navigate = useNavigate();
  const { token } = useParams<{ token: string }>();
  const location = useLocation();
  const { text, muted, border, surface, accentSoft, primary, dangerBg, dangerText } = useAdminTheme();
  const searchParams = React.useMemo(() => new URLSearchParams(location.search), [location.search]);
  const presetEmail = searchParams.get('email') ?? '';
  const [email, setEmail] = React.useState(presetEmail);
  const [password, setPassword] = React.useState('');
  const [passwordConfirmation, setPasswordConfirmation] = React.useState('');
  const [status, setStatus] = React.useState<string | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = React.useState<FieldErrors>({});
  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: ['tenantAdminResetPassword'],
    mutationFn: resetPassword,
    onSuccess: (data) => {
      setFieldErrors({});
      setError(null);
      setStatus(data.status ?? t('login.reset.success', 'Password updated.'));
    },
    onError: (err: unknown) => {
      const typed = err as Error & { errors?: FieldErrors };
      setFieldErrors(typed.errors ?? {});
      setError(typed.message);
    },
  });

  const handleSubmit = () => {
    if (!token) {
      setError(t('login.reset.missing_token', 'Reset token missing.'));
      return;
    }
    setStatus(null);
    setError(null);
    mutation.mutate({
      token,
      email,
      password,
      password_confirmation: passwordConfirmation,
    });
  };

  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)"
              >
                <Lock size={18} color="white" />
              </XStack>
              <Text fontSize="$lg" fontWeight="800" color="white">
                {t('login.reset.title', 'Reset password')}
              </Text>
            </XStack>
            <Text fontSize="$sm" color="rgba(255,255,255,0.7)">
              {t('login.reset.copy', 'Choose a new password for your event admin account.')}
            </Text>
          </YStack>
        </MobileCard>

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

            <MobileField label={t('login.reset.password', 'New password')} error={fieldErrors.password?.[0]}>
              <MobileInput
                type="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                placeholder={t('login.reset.password_placeholder', '••••••••')}
                autoComplete="new-password"
                required
              />
            </MobileField>

            <MobileField
              label={t('login.reset.password_confirm', 'Confirm password')}
              error={fieldErrors.password_confirmation?.[0]}
            >
              <MobileInput
                type="password"
                value={passwordConfirmation}
                onChange={(event) => setPasswordConfirmation(event.target.value)}
                placeholder={t('login.reset.password_confirm_placeholder', '••••••••')}
                autoComplete="new-password"
                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={handleSubmit}
              disabled={mutation.isPending || !token}
              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.reset.loading', 'Saving ...') : t('login.reset.submit', 'Save new password')}
            </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.reset.back', 'Back to login')}
        </Button>
      </YStack>
    </YStack>
  );
}
