import { useState } from 'react';
import {
  ActivityIndicator,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { FormSheet } from '../FormSheet';
import { useMailInterval } from '../../hooks/useMailInterval';
import { useMailTitleEdit } from '../../hooks/useMailTitleEdit';
import { useMailConnect } from '../../hooks/useMailConnect';
import { useColors } from '../../lib/theme';
import type { MailAccount } from '../../hooks/useMailStatus';

type EditMode = 'list' | 'edit-title' | 'edit-email' | 'edit-password';

type Props = {
  visible: boolean;
  account: MailAccount;
  localTitle: string | null;
  isOAuth: boolean;
  plan: 'free' | 'pro' | 'legend';
  disconnecting?: boolean;
  onClose: () => void;
  onTitleSaved: (newTitle: string | null) => void;
  onPasswordSaved: () => void;
  onDisconnectRequest: () => void;
  onIntervalChanged: () => void;
};

const INTERVAL_OPTIONS_BY_PLAN: Record<'free' | 'pro' | 'legend', number[]> = {
  free: [4],
  pro: [1, 4, 8],
  legend: [1, 4, 8],
};

function domainFromEmail(email: string): string {
  return email.split('@')[1] ?? email;
}

function SettingsRow({
  label,
  value,
  onPress,
  destructive,
}: {
  label: string;
  value?: string;
  onPress?: () => void;
  destructive?: boolean;
}) {
  const labelColor = destructive ? '#dc2626' : '#0a0a0a';
  const Wrapper = onPress ? TouchableOpacity : View;
  const wrapperProps = onPress ? { activeOpacity: 0.7 as const, onPress } : {};

  return (
    <Wrapper
      {...(wrapperProps as any)}
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 13,
        paddingHorizontal: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#f5f5f5',
      }}
    >
      <Text
        style={{ flex: 1, fontSize: 14, fontFamily: 'Nunito_600SemiBold', color: labelColor }}
      >
        {label}
      </Text>
      {value !== undefined && (
        <Text
          style={{
            fontSize: 13,
            fontFamily: 'Nunito_400Regular',
            color: '#a3a3a3',
            marginRight: onPress && !destructive ? 4 : 0,
            maxWidth: 160,
          }}
          numberOfLines={1}
        >
          {value}
        </Text>
      )}
      {onPress && !destructive && (
        <Ionicons name="chevron-forward" size={14} color="#d4d4d4" />
      )}
    </Wrapper>
  );
}

function EditView({
  label,
  value,
  onChangeText,
  onSave,
  onBack,
  saving,
  error,
  secureTextEntry,
  keyboardType,
  autoCapitalize,
  placeholder,
}: {
  label: string;
  value: string;
  onChangeText: (v: string) => void;
  onSave: () => void;
  onBack: () => void;
  saving: boolean;
  error: string | null;
  secureTextEntry?: boolean;
  keyboardType?: TextInput['props']['keyboardType'];
  autoCapitalize?: TextInput['props']['autoCapitalize'];
  placeholder?: string;
}) {
  const { t } = useTranslation();
  const colors = useColors();

  return (
    <View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 4 }}>
      {/* Back row */}
      <TouchableOpacity
        activeOpacity={0.7}
        onPress={onBack}
        style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 20, gap: 4 }}
      >
        <Ionicons name="chevron-back" size={18} color="#007AFF" />
        <Text style={{ fontSize: 15, fontFamily: 'Nunito_600SemiBold', color: '#007AFF' }}>
          {label}
        </Text>
      </TouchableOpacity>

      {/* Input */}
      <View
        style={{
          backgroundColor: colors.surfaceElevated,
          borderRadius: 12,
          paddingHorizontal: 14,
          marginBottom: error ? 6 : 16,
        }}
      >
        <TextInput
          autoFocus
          value={value}
          onChangeText={onChangeText}
          placeholder={placeholder}
          placeholderTextColor={colors.textMuted}
          secureTextEntry={secureTextEntry}
          keyboardType={keyboardType ?? 'default'}
          autoCapitalize={autoCapitalize ?? 'sentences'}
          autoCorrect={false}
          returnKeyType="done"
          onSubmitEditing={onSave}
          style={{
            paddingVertical: 13,
            fontSize: 15,
            fontFamily: 'Nunito_400Regular',
            color: colors.text,
          }}
        />
      </View>

      {error && (
        <Text
          style={{
            fontSize: 12,
            fontFamily: 'Nunito_400Regular',
            color: '#dc2626',
            marginBottom: 12,
          }}
        >
          {error}
        </Text>
      )}

      {/* Save button */}
      <TouchableOpacity
        activeOpacity={0.85}
        onPress={onSave}
        disabled={saving}
      >
        <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>
    </View>
  );
}

export function MailAccountSettingsSheet({
  visible,
  account,
  localTitle,
  isOAuth,
  plan,
  disconnecting,
  onClose,
  onTitleSaved,
  onPasswordSaved,
  onDisconnectRequest,
  onIntervalChanged,
}: Props) {
  const { t } = useTranslation();
  const { setInterval, updating } = useMailInterval();
  const { saveTitle, saving: savingTitle, error: titleError } = useMailTitleEdit();
  const { connect, connecting: connectingPassword, error: connectError } = useMailConnect();

  const isLegend = plan === 'legend';
  const intervalOptions = INTERVAL_OPTIONS_BY_PLAN[plan];

  const displayTitle = localTitle ?? domainFromEmail(account.email);

  const [mode, setMode] = useState<EditMode>('list');
  const [titleDraft, setTitleDraft] = useState(localTitle ?? '');
  const [passwordDraft, setPasswordDraft] = useState('');
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [localError, setLocalError] = useState<string | null>(null);

  function handleClose() {
    setMode('list');
    setTitleDraft(localTitle ?? '');
    setPasswordDraft('');
    setPasswordVisible(false);
    setLocalError(null);
    onClose();
  }

  function goBack() {
    setMode('list');
    setLocalError(null);
  }

  async function handleSetInterval(value: number) {
    const res = await setInterval(account.id, value);
    if (res.ok) onIntervalChanged();
  }

  async function handleSaveTitle() {
    const ok = await saveTitle(account.id, titleDraft);
    if (ok) {
      const newTitle = titleDraft.trim() || null;
      // Sheet ZUERST dismissen, dann nach Animation-Complete Parent informieren.
      // Sonst rendern Sheet (closing) + SuccessAlert (opening) gleichzeitig → iOS
      // wirft „already presenting"-Crash + Page-Freeze. ~350ms = FormSheet-Dismiss.
      handleClose();
      setTimeout(() => onTitleSaved(newTitle), 350);
    }
  }

  async function handleSavePassword() {
    setLocalError(null);
    const result = await connect({ email: account.email, password: passwordDraft });
    if (result.ok) {
      // Symmetrisch zu handleSaveTitle: Sheet zuerst dismissen, dann nach
      // Animation-Complete Parent informieren — sonst Modal-Conflict-Crash.
      handleClose();
      setTimeout(() => onPasswordSaved(), 350);
    } else {
      setLocalError(result.error ?? t('mail.connect_failed'));
    }
  }

  const sheetTitle = mode === 'list'
    ? displayTitle
    : mode === 'edit-title'
      ? t('mail.row_title')
      : mode === 'edit-email'
        ? t('mail.row_email')
        : t('mail.row_password');

  return (
    <FormSheet
      visible={visible}
      onClose={handleClose}
      title={sheetTitle}
      initialHeightPct={mode === 'list' ? 0.55 : 0.5}
      growWithKeyboard={mode !== 'list'}
    >
      {mode === 'list' && (
        <View style={{ paddingTop: 8 }}>
          {/* Bezeichnung */}
          <SettingsRow
            label={t('mail.row_title')}
            value={localTitle ?? '—'}
            onPress={() => { setTitleDraft(localTitle ?? ''); setMode('edit-title'); }}
          />

          {/* E-Mail */}
          <SettingsRow
            label={t('mail.row_email')}
            value={account.email}
            onPress={!isOAuth ? () => setMode('edit-email') : undefined}
          />

          {/* Passwort — nur IMAP */}
          {!isOAuth && (
            <SettingsRow
              label={t('mail.row_password')}
              value="••••••••"
              onPress={() => { setPasswordDraft(''); setPasswordVisible(false); setMode('edit-password'); }}
            />
          )}

          {/* Scan-Intervall */}
          {!isLegend ? (
            <View
              style={{
                paddingHorizontal: 16,
                paddingVertical: 14,
                borderBottomWidth: 1,
                borderBottomColor: '#f5f5f5',
              }}
            >
              <Text
                style={{
                  fontSize: 11,
                  fontFamily: 'Nunito_600SemiBold',
                  color: '#737373',
                  textTransform: 'uppercase',
                  letterSpacing: 0.6,
                  marginBottom: 8,
                }}
              >
                {t('mail.scan_interval_label')}
              </Text>
              <View style={{ flexDirection: 'row', gap: 6 }}>
                {intervalOptions.map((opt) => {
                  const active = account.scanInterval === opt;
                  const disabled = plan === 'free' || updating === account.id;
                  return (
                    <TouchableOpacity
                      key={opt}
                      activeOpacity={0.7}
                      disabled={disabled}
                      onPress={() => handleSetInterval(opt)}
                      style={{
                        flex: 1,
                        paddingVertical: 9,
                        borderRadius: 10,
                        alignItems: 'center',
                        backgroundColor: active ? '#007AFF' : '#f5f5f5',
                        opacity: disabled && !active ? 0.5 : 1,
                      }}
                    >
                      <Text
                        style={{
                          fontSize: 13,
                          fontFamily: 'Nunito_700Bold',
                          color: active ? '#fff' : '#525252',
                        }}
                      >
                        {opt}h
                      </Text>
                    </TouchableOpacity>
                  );
                })}
              </View>
              {plan === 'free' && (
                <Text
                  style={{
                    fontSize: 10,
                    fontFamily: 'Nunito_400Regular',
                    color: '#a3a3a3',
                    marginTop: 6,
                  }}
                >
                  {t('mail.free_scan_interval_hint')}
                </Text>
              )}
            </View>
          ) : (
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#f0fdf4',
                marginHorizontal: 16,
                marginVertical: 10,
                borderRadius: 10,
                paddingHorizontal: 12,
                paddingVertical: 10,
              }}
            >
              <Ionicons name="flash" size={14} color="#16a34a" style={{ marginRight: 8 }} />
              <Text
                style={{ flex: 1, fontSize: 12, fontFamily: 'Nunito_600SemiBold', color: '#16a34a' }}
              >
                {t('mail.realtime_desc')}
              </Text>
            </View>
          )}

          <View style={{ height: 20 }} />

          {/* Verbindung trennen */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={onDisconnectRequest}
            disabled={disconnecting}
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              paddingVertical: 13,
              paddingHorizontal: 16,
              borderTopWidth: 1,
              borderTopColor: '#f5f5f5',
              opacity: disconnecting ? 0.5 : 1,
            }}
          >
            <Ionicons
              name="trash-outline"
              size={16}
              color="#dc2626"
              style={{ marginRight: 12, width: 20 }}
            />
            <Text
              style={{ flex: 1, fontSize: 14, fontFamily: 'Nunito_600SemiBold', color: '#dc2626' }}
            >
              {t('mail.row_disconnect')}
            </Text>
          </TouchableOpacity>
        </View>
      )}

      {mode === 'edit-title' && (
        <EditView
          label={t('mail.row_title')}
          value={titleDraft}
          onChangeText={setTitleDraft}
          onSave={handleSaveTitle}
          onBack={goBack}
          saving={savingTitle}
          error={titleError}
          placeholder={t('mail.title_placeholder')}
          autoCapitalize="sentences"
        />
      )}

      {mode === 'edit-email' && (
        <EditView
          label={t('mail.row_email')}
          value={account.email}
          onChangeText={() => {}}
          onSave={() => {}}
          onBack={goBack}
          saving={false}
          error={t('mail.email_change_not_supported')}
          keyboardType="email-address"
          autoCapitalize="none"
          placeholder={account.email}
        />
      )}

      {mode === 'edit-password' && (
        <View style={{ flex: 1, paddingHorizontal: 16, paddingTop: 4 }}>
          {/* Back row */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={goBack}
            style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 20, gap: 4 }}
          >
            <Ionicons name="chevron-back" size={18} color="#007AFF" />
            <Text style={{ fontSize: 15, fontFamily: 'Nunito_600SemiBold', color: '#007AFF' }}>
              {t('mail.row_password')}
            </Text>
          </TouchableOpacity>

          {/* Password input with visibility toggle */}
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              backgroundColor: '#f5f5f5',
              borderRadius: 12,
              paddingHorizontal: 14,
              marginBottom: (localError ?? connectError) ? 6 : 16,
            }}
          >
            <TextInput
              autoFocus
              value={passwordDraft}
              onChangeText={(v) => { setPasswordDraft(v); setLocalError(null); }}
              placeholder={t('mail.app_password_placeholder')}
              placeholderTextColor="#a3a3a3"
              secureTextEntry={!passwordVisible}
              autoCapitalize="none"
              autoCorrect={false}
              returnKeyType="done"
              onSubmitEditing={handleSavePassword}
              style={{
                flex: 1,
                paddingVertical: 13,
                fontSize: 15,
                fontFamily: 'Nunito_400Regular',
                color: '#0a0a0a',
              }}
            />
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() => setPasswordVisible((p) => !p)}
              hitSlop={8}
            >
              <Ionicons
                name={passwordVisible ? 'eye-off-outline' : 'eye-outline'}
                size={18}
                color="#737373"
              />
            </TouchableOpacity>
          </View>

          {(localError ?? connectError) && (
            <Text
              style={{
                fontSize: 12,
                fontFamily: 'Nunito_400Regular',
                color: '#dc2626',
                marginBottom: 12,
              }}
            >
              {localError ?? connectError}
            </Text>
          )}

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