import React, { useEffect, useState } from 'react';
import { themedColor } from '../../theme';
import {
  KeyboardAvoidingView,
  Modal,
  Platform,
  Pressable,
  Text,
  TextInput,
  View,
} from 'react-native';

import { renameAgentModalStyles as styles } from './renameAgentModalStyles';

export function RenameAgentModal({
  error,
  initialName,
  isSaving,
  isVisible,
  onClose,
  onSave,
}: {
  error?: string | null;
  initialName: string;
  isSaving: boolean;
  isVisible: boolean;
  onClose: () => void;
  onSave: (name: string) => void;
}) {
  const [name, setName] = useState(initialName);
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    if (isVisible) {
      setName(initialName);
      setLocalError(null);
    }
  }, [initialName, isVisible]);

  const save = () => {
    const trimmed = name.trim();
    if (!trimmed) {
      setLocalError('Name is required.');
      return;
    }
    onSave(trimmed);
  };

  return (
    <Modal animationType="fade" transparent visible={isVisible} onRequestClose={onClose}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.backdrop}
      >
        <View style={styles.card}>
          <Text style={styles.title}>Rename Superagent</Text>
          <TextInput
            autoCapitalize="words"
            autoCorrect
            autoFocus
            editable={!isSaving}
            maxLength={80}
            onChangeText={(value) => {
              setName(value);
              setLocalError(null);
            }}
            onSubmitEditing={save}
            placeholder="Superagent name"
            placeholderTextColor={themedColor('#8E8E93')}
            returnKeyType="done"
            selectTextOnFocus
            style={styles.input}
            value={name}
          />
          {localError || error ? (
            <Text style={styles.error}>{localError || error}</Text>
          ) : null}
          <View style={styles.actions}>
            <Pressable
              accessibilityRole="button"
              disabled={isSaving}
              onPress={onClose}
              style={({ pressed }) => [
                styles.button,
                styles.secondaryButton,
                pressed && styles.pressed,
              ]}
            >
              <Text style={styles.secondaryButtonText}>Cancel</Text>
            </Pressable>
            <Pressable
              accessibilityRole="button"
              disabled={isSaving}
              onPress={save}
              style={({ pressed }) => [
                styles.button,
                styles.primaryButton,
                (pressed || isSaving) && styles.primaryPressed,
              ]}
            >
              <Text style={styles.primaryButtonText}>{isSaving ? 'Saving...' : 'Save'}</Text>
            </Pressable>
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
