import { Text, 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 type { MailAccount } from '../../hooks/useMailStatus';

type Props = {
  visible: boolean;
  account: MailAccount;
  localTitle: string | null;
  isOAuth: boolean;
  plan: 'free' | 'pro' | 'legend';
  disconnecting?: boolean;
  onClose: () => void;
  onEditTitle: () => void;
  onEditPassword: () => 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({
  icon,
  label,
  value,
  onPress,
  destructive,
}: {
  icon: React.ComponentProps<typeof Ionicons>['name'];
  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',
      }}
    >
      <Ionicons
        name={icon}
        size={16}
        color={destructive ? '#dc2626' : '#737373'}
        style={{ marginRight: 12, width: 20 }}
      />
      <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>
  );
}

export function MailAccountSettingsSheet({
  visible,
  account,
  localTitle,
  isOAuth,
  plan,
  disconnecting,
  onClose,
  onEditTitle,
  onEditPassword,
  onDisconnectRequest,
  onIntervalChanged,
}: Props) {
  const { t } = useTranslation();
  const { setInterval, updating } = useMailInterval();
  const isLegend = plan === 'legend';
  const intervalOptions = INTERVAL_OPTIONS_BY_PLAN[plan];

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

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

  return (
    <FormSheet
      visible={visible}
      onClose={onClose}
      title={displayTitle}
      initialHeightPct={0.55}
      growWithKeyboard={false}
    >
      <View style={{ paddingTop: 8 }}>
        {/* Bezeichnung */}
        <SettingsRow
          icon="pencil-outline"
          label={t('mail.row_title')}
          value={localTitle ?? '—'}
          onPress={onEditTitle}
        />

        {/* E-Mail (read-only) */}
        <SettingsRow
          icon="mail-outline"
          label={t('mail.row_email')}
          value={account.email}
        />

        {/* Passwort — nur für IMAP-Accounts */}
        {!isOAuth && (
          <SettingsRow
            icon="key-outline"
            label={t('mail.row_password')}
            value="••••••••"
            onPress={onEditPassword}
          />
        )}

        {/* 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>
        )}

        {/* Separator */}
        <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>
    </FormSheet>
  );
}
