import { Redirect, useLocalSearchParams } from 'expo-router';
import { useEffect, useState } from 'react';
import { ActivityIndicator, StyleSheet, TextInput } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { Button } from '@/components/button';
import { ScreenBackground } from '@/components/screen-background';
import { ThemedText } from '@/components/themed-text';
import { Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useAuth } from '@/lib/auth-context';
import { supabase } from '@/lib/supabase';

export default function ResetPasswordScreen() {
  const { code } = useLocalSearchParams<{ code?: string }>();
  const { updatePassword } = useAuth();
  const theme = useTheme();

  const [exchanging, setExchanging] = useState(true);
  const [linkError, setLinkError] = useState<string | null>(null);
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);

  useEffect(() => {
    if (!code) {
      setLinkError('Este link de recuperación no es válido o ya expiró.');
      setExchanging(false);
      return;
    }
    supabase.auth.exchangeCodeForSession(code).then(({ error }) => {
      if (error) setLinkError(error.message);
      setExchanging(false);
    });
  }, [code]);

  if (done) return <Redirect href="/" />;

  async function handleSubmit() {
    setError(null);
    setSubmitting(true);
    const result = await updatePassword(password);
    setSubmitting(false);
    if (result) return setError(result);
    setDone(true);
  }

  return (
    <ScreenBackground style={styles.container}>
      <SafeAreaView style={styles.safeArea}>
        <ThemedText type="title" style={styles.title}>
          Nueva contraseña
        </ThemedText>

        {exchanging ? (
          <ActivityIndicator />
        ) : linkError ? (
          <ThemedText type="small" themeColor="error" style={styles.error}>
            {linkError}
          </ThemedText>
        ) : (
          <>
            <TextInput
              placeholder="Nueva contraseña"
              placeholderTextColor={theme.text + '80'}
              value={password}
              onChangeText={setPassword}
              secureTextEntry
              style={[styles.input, { color: theme.text, borderColor: theme.text + '30' }]}
            />
            {error && (
              <ThemedText type="small" themeColor="error" style={styles.error}>
                {error}
              </ThemedText>
            )}
            <Button label="Guardar contraseña" loading={submitting} onPress={handleSubmit} style={styles.button} />
          </>
        )}
      </SafeAreaView>
    </ScreenBackground>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  safeArea: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: Spacing.four,
    gap: Spacing.three,
  },
  title: { textAlign: 'center', marginBottom: Spacing.three, letterSpacing: 1 },
  input: {
    borderWidth: 2,
    borderRadius: Spacing.two,
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.three,
    fontSize: 16,
  },
  button: { marginTop: Spacing.two },
  error: { textAlign: 'center' },
});
