import { useState } from 'react';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useMailTitleEdit } from '../../hooks/useMailTitleEdit';
import { FormSheet } from '../FormSheet';
import { SheetFieldStack } from '../SheetFieldStack';

type Props = {
  visible: boolean;
  connectionId: string;
  currentTitle: string | null;
  onClose: () => void;
  onSuccess: (newTitle: string | null) => void;
};

export function EditMailTitleSheet({
  visible,
  connectionId,
  currentTitle,
  onClose,
  onSuccess,
}: Props) {
  const { t } = useTranslation();
  const { saveTitle, saving, error } = useMailTitleEdit();
  const [title, setTitle] = useState(currentTitle ?? '');

  function handleClose() {
    setTitle(currentTitle ?? '');
    onClose();
  }

  async function handleSave() {
    const ok = await saveTitle(connectionId, title);
    if (ok) {
      onSuccess(title.trim() || null);
      onClose();
    }
  }

  return (
    <FormSheet
      visible={visible}
      onClose={handleClose}
      title={t('mail.title_edit_title')}
      initialHeightPct={0.45}
      growWithKeyboard
    >
      <SheetFieldStack
        fields={[
          {
            key: 'title',
            label: t('mail.title_label'),
            placeholder: t('mail.title_placeholder'),
            value: title,
            onChangeText: setTitle,
            autoCapitalize: 'sentences',
            autoCorrect: false,
          },
        ]}
        onComplete={() => {}}
      >
        {error && (
          <Text
            style={{
              fontSize: 13,
              fontFamily: 'Nunito_400Regular',
              color: '#dc2626',
              marginBottom: 10,
            }}
          >
            {error}
          </Text>
        )}

        <TouchableOpacity
          activeOpacity={0.85}
          onPress={handleSave}
          disabled={saving}
          style={{ marginTop: 4, marginBottom: 12 }}
        >
          <View
            style={{
              paddingVertical: 14,
              borderRadius: 12,
              backgroundColor: saving ? '#d4d4d4' : '#007AFF',
              alignItems: 'center',
            }}
          >
            {saving ? (
              <ActivityIndicator color="#fff" />
            ) : (
              <Text style={{ fontSize: 15, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
                {t('mail.title_save')}
              </Text>
            )}
          </View>
        </TouchableOpacity>
      </SheetFieldStack>
    </FormSheet>
  );
}
