import React, { useState } from 'react';
import {
  View, Text, StyleSheet,
  TouchableOpacity, ActivityIndicator, Platform
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { Image } from 'expo-image';
import { Feather } from '@expo/vector-icons';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { useToast } from '../../context/ToastContext';
import { useForm } from '../../hooks/useForm';
import { useAppTheme } from '../../context/ThemeContext';
import { useAppConfig } from '../../context/ConfigContext';
import { useTranslation } from '../../context/LanguageContext';
import { AIInput, AIButton, AppScreen } from '../../components/UI';

export default function ForgotPasswordScreen() {
  const router = useRouter();
  const { showToast } = useToast();
  const { colors, isDark } = useAppTheme();
  const { config } = useAppConfig();
  const { t } = useTranslation();
  const { values, handleChange } = useForm({ email: '' });
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const handleReset = async () => {
    if (!values.email.includes('@')) {
      showToast(t('invalidEmail'), 'error');
      return;
    }
    setLoading(true);
    try {
      // Technical Note: This calls the real API from ApiService if implemented,
      // but here we keep the simulation logic as requested for demo stability.
      await new Promise(res => setTimeout(res, 2000));
      setSent(true);
      showToast(t('emailSent'), 'success');
    } catch (err) {
      showToast(t('sendFailed'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const cardBg = colors.surface;
  const border = colors.border;

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <SafeAreaView style={{ flex: 1 }}>
        {/* Back Button */}
        <TouchableOpacity style={styles.backBtn} onPress={() => router.back()}>
          <Feather name="arrow-left" size={24} color={colors.text} />
        </TouchableOpacity>

        <KeyboardAwareScrollView
          enableOnAndroid
          contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}
          showsVerticalScrollIndicator={false}
          style={styles.scroll}
        >
          {/* Header */}
          <View style={styles.header}>
            <View style={[styles.iconWrap, { backgroundColor: colors.surface }]}>
              {config?.branding?.logo_url ? (
                <Image source={{ uri: config.branding.logo_url }} style={{ width: 56, height: 56 }} contentFit="contain" />
              ) : (
                <Feather name="lock" size={40} color={colors.primary} />
              )}
            </View>
            <Text style={[styles.title, { color: colors.text }]}>{t('resetPass')}</Text>
            <Text style={[styles.subtitle, { color: colors.textSecondary }]}>
              {t('resetSubtitle')} {config?.branding?.app_name || 'biiproject'}.
            </Text>
          </View>

          {/* Card */}
          <View style={[styles.card, { backgroundColor: cardBg, borderColor: border }]}>
            {sent ? (
              <View style={styles.successBox}>
                <View style={[styles.successIcon, { backgroundColor: `${colors.primary}20` }]}>
                  <Feather name="check-circle" size={44} color={colors.primary} />
                </View>
                <Text style={[styles.successTitle, { color: colors.text }]}>{t('emailSentTitle')}</Text>
                <Text style={[styles.successDesc, { color: colors.textSecondary }]}>
                  {t('emailSentDesc')}
                </Text>
                <AIButton
                  title={t('backToSignIn')}
                  onPress={() => router.back()}
                  style={{ width: '100%' }}
                />
              </View>
            ) : (
              <>
                <AIInput 
                  label={t('email')}
                  icon="mail"
                  placeholder="email@example.com"
                  value={values.email}
                  onChangeText={(v: string) => handleChange('email', v)}
                  keyboardType="email-address"
                />

                <AIButton
                  title={t('sendInstructions')}
                  onPress={handleReset}
                  loading={loading}
                  style={{ marginTop: 12 }}
                />

                <TouchableOpacity style={styles.cancelBtn} onPress={() => router.back()}>
                  <Text style={[styles.cancelText, { color: colors.textSecondary }]}>{t('cancel')}</Text>
                </TouchableOpacity>
              </>
            )}
          </View>
        </KeyboardAwareScrollView>
      </SafeAreaView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  backBtn: { padding: 20, position: 'absolute', top: 0, left: 0, zIndex: 10 },
  scroll: { paddingHorizontal: 24 },
  header: { alignItems: 'center', marginBottom: 36 },
  iconWrap: { width: 100, height: 100, borderRadius: 32, alignItems: 'center', justifyContent: 'center', elevation: 4, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.05, shadowRadius: 10 },
  title: { fontSize: 32, fontFamily: 'Outfit_800ExtraBold', marginTop: 24 },
  subtitle: { fontSize: 15, fontFamily: 'Outfit_400Regular', textAlign: 'center', marginTop: 10, paddingHorizontal: 20, lineHeight: 24 },
  card: { borderRadius: 28, padding: 28, borderWidth: 1 },
  cancelBtn: { alignItems: 'center', marginTop: 20 },
  cancelText: { fontSize: 14, fontFamily: 'Outfit_600SemiBold' },
  successBox: { alignItems: 'center', paddingVertical: 10 },
  successIcon: { width: 88, height: 88, borderRadius: 44, alignItems: 'center', justifyContent: 'center', marginBottom: 24 },
  successTitle: { fontSize: 24, fontFamily: 'Outfit_700Bold', marginBottom: 12 },
  successDesc: { fontSize: 15, fontFamily: 'Outfit_400Regular', textAlign: 'center', marginBottom: 32, lineHeight: 24 },
});
