import { useState } from 'react';
import {
  ActivityIndicator,
  LayoutAnimation,
  Linking,
  Modal,
  Platform,
  TouchableOpacity,
  Text,
  UIManager,
  View,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { ConfirmAlert } from '../ConfirmAlert';
import { MailAccountSettingsSheet } from './MailAccountSettingsSheet';
import { MailBlockedByDayChart } from './MailBlockedByDayChart';
import { useMailConnectionStats } from '../../hooks/useMailStats';
import { apiFetch } from '../../lib/api';
import type { MailAccount } from '../../hooks/useMailStatus';

if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
  UIManager.setLayoutAnimationEnabledExperimental(true);
}

type ScanResult = { ok: boolean; scanned: number; blocked: number };

type Props = {
  account: MailAccount;
  plan: 'free' | 'pro' | 'legend';
  expanded: boolean;
  onToggle: () => void;
  onDisconnect: (id: string) => Promise<void>;
  onIntervalChanged: () => void;
  onEditSuccess: () => void;
  disconnecting?: boolean;
  blockedLast30d?: number;
  onScanSuccess?: () => void;
};

function OAuthDisconnectHintModal({
  visible,
  onClose,
  t,
}: {
  visible: boolean;
  onClose: () => void;
  t: (key: string) => string;
}) {
  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <TouchableOpacity
        activeOpacity={1}
        onPress={onClose}
        style={{
          flex: 1,
          backgroundColor: 'rgba(0,0,0,0.35)',
          justifyContent: 'center',
          alignItems: 'center',
          padding: 24,
        }}
      >
        <TouchableOpacity activeOpacity={1} onPress={() => {}} style={{ width: '88%', maxWidth: 340 }}>
          <View
            style={{
              backgroundColor: '#fff',
              borderRadius: 22,
              padding: 22,
              gap: 14,
              shadowColor: '#000',
              shadowOffset: { width: 0, height: 8 },
              shadowOpacity: 0.18,
              shadowRadius: 24,
              elevation: 16,
            }}
          >
            <View
              style={{
                width: 52,
                height: 52,
                borderRadius: 26,
                backgroundColor: '#16a34a',
                alignItems: 'center',
                justifyContent: 'center',
                alignSelf: 'center',
              }}
            >
              <Ionicons name="checkmark" size={28} color="#fff" />
            </View>

            <Text
              style={{
                fontSize: 17,
                fontFamily: 'Nunito_700Bold',
                color: '#0a0a0a',
                textAlign: 'center',
              }}
            >
              {t('mail.oauth.disconnect_hint_title')}
            </Text>

            <Text
              style={{
                fontSize: 13,
                fontFamily: 'Nunito_400Regular',
                color: '#525252',
                lineHeight: 19,
                textAlign: 'center',
              }}
            >
              {t('mail.oauth.disconnect_hint_body')}
            </Text>

            <View style={{ flexDirection: 'row', gap: 10 }}>
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => Linking.openURL('https://account.microsoft.com/consent').catch(() => {})}
                style={{
                  flex: 1,
                  paddingVertical: 10,
                  borderRadius: 10,
                  backgroundColor: '#eff6ff',
                  borderWidth: 1,
                  borderColor: '#bfdbfe',
                  alignItems: 'center',
                }}
              >
                <Text style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#007AFF' }}>
                  {t('mail.oauth.disconnect_hint_open_ms')}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                activeOpacity={0.7}
                onPress={onClose}
                style={{
                  flex: 1,
                  paddingVertical: 10,
                  borderRadius: 10,
                  backgroundColor: '#f5f5f5',
                  alignItems: 'center',
                }}
              >
                <Text style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#0a0a0a' }}>
                  OK
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </TouchableOpacity>
      </TouchableOpacity>
    </Modal>
  );
}

function resolveProviderIcon(provider: string): {
  icon: React.ComponentProps<typeof Ionicons>['name'];
  color: string;
} {
  const p = provider.toLowerCase();
  if (p.includes('gmail') || p.includes('google')) return { icon: 'mail', color: '#EA4335' };
  if (p.includes('icloud') || p.includes('apple')) return { icon: 'cloud', color: '#007AFF' };
  if (p.includes('outlook') || p.includes('hotmail') || p.includes('microsoft'))
    return { icon: 'mail-open', color: '#0078D4' };
  if (p.includes('yahoo')) return { icon: 'at', color: '#7C3AED' };
  if (p.includes('gmx') || p.includes('web.de'))
    return { icon: 'mail-unread', color: '#E87A22' };
  return { icon: 'server', color: '#737373' };
}

function isOAuthProvider(provider: string): boolean {
  return provider === 'outlook_oauth';
}

const STALE_THRESHOLD_MS = 5 * 60 * 1_000;
const IDLE_HEARTBEAT_STALE_MS = STALE_THRESHOLD_MS;

function idleHeartbeatAlive(lastIdleHeartbeatAt: string | null | undefined): boolean {
  if (!lastIdleHeartbeatAt) return false;
  return Date.now() - new Date(lastIdleHeartbeatAt).getTime() < IDLE_HEARTBEAT_STALE_MS;
}

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

type StatusDot = 'live' | 'stale' | 'error' | 'waiting';

function resolveStatusDot(account: MailAccount): StatusDot {
  if (account.lastConnectError) return 'error';
  // 'waiting' nur wenn weder ein lebendiger Heartbeat noch ein vergangener Scan
  // existiert. Bei frisch verbundenen Connections (z.B. OAuth-Outlook nach
  // ersten 5-30s) hat der Daemon schon einen Heartbeat geschrieben, aber
  // lastScannedAt bleibt NULL bis die erste Gambling-Mail trifft. Wir wollen
  // dann 'live' anzeigen, nicht 'waiting'.
  const heartbeatAlive = idleHeartbeatAlive(account.lastIdleHeartbeatAt);
  if (!account.lastScannedAt && !heartbeatAlive) return 'waiting';
  if (account.lastScannedAt) {
    const scannedAgo = Date.now() - new Date(account.lastScannedAt).getTime();
    if (!heartbeatAlive && scannedAgo > STALE_THRESHOLD_MS) return 'stale';
  }
  return 'live';
}

function StatusDotRow({
  account,
  isLegend,
  blockedLast30d,
  t,
}: {
  account: MailAccount;
  isLegend: boolean;
  blockedLast30d: number | undefined;
  t: (k: string) => string;
}) {
  const dot = resolveStatusDot(account);

  const dotColor =
    dot === 'live' ? '#16a34a' :
    dot === 'stale' ? '#d97706' :
    dot === 'error' ? '#dc2626' :
    '#a3a3a3';

  const label =
    dot === 'live' ? (isLegend ? t('mail.live') : t('mail.account_active')) :
    dot === 'stale' ? t('mail.status_stale') :
    dot === 'error' ? t('mail.status_auth_error') :
    t('mail.status_waiting_first_connect');

  const blockedLabel =
    blockedLast30d !== undefined
      ? `${blockedLast30d}`
      : account.totalBlocked > 0
        ? `${account.totalBlocked}`
        : '0';

  return (
    <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 3 }}>
      <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: dotColor, marginRight: 5 }} />
      <Text
        style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: dotColor, flex: 1 }}
        numberOfLines={1}
      >
        {label}
      </Text>
      <Text style={{ fontSize: 12, fontFamily: 'Nunito_700Bold', color: '#525252', marginRight: 6 }}>
        {blockedLabel}
      </Text>
      <Ionicons name="shield-checkmark" size={11} color="#a3a3a3" />
    </View>
  );
}

export function MailAccountCard({
  account,
  plan,
  expanded,
  onToggle,
  onDisconnect,
  onIntervalChanged,
  onEditSuccess,
  disconnecting,
  blockedLast30d,
  onScanSuccess,
}: Props) {
  const { t } = useTranslation();
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [confirmVisible, setConfirmVisible] = useState(false);
  const [oauthDisconnectHintVisible, setOauthDisconnectHintVisible] = useState(false);
  const [localTitle, setLocalTitle] = useState<string | null>(account.title ?? null);
  const [scanning, setScanning] = useState(false);
  const [scanFeedback, setScanFeedback] = useState<{ blocked: number } | null>(null);
  const { icon, color } = resolveProviderIcon(account.provider);
  const { data: connStats, granularity, loading: statsLoading, refresh: refreshStats } = useMailConnectionStats(
    account.id,
    account.createdAt ?? null,
    expanded,
  );

  const isOAuth = isOAuthProvider(account.provider);
  const isLegend = plan === 'legend';
  const isPaused = account.paused === true;
  const hasError = !!account.lastConnectError;

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

  function handleToggle() {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    onToggle();
  }

  async function handleScan() {
    setScanning(true);
    setScanFeedback(null);
    try {
      const result = await apiFetch<ScanResult>('/api/mail/scan', {
        method: 'POST',
        body: { connectionId: account.id },
      });
      setScanFeedback({ blocked: result.blocked });
      refreshStats();
      onScanSuccess?.();
    } catch {
      setScanFeedback({ blocked: -1 });
    } finally {
      setScanning(false);
    }
  }

  function handleTitleSaved(newTitle: string | null) {
    setLocalTitle(newTitle);
    onEditSuccess();
  }

  return (
    <>
      <View
        style={{
          backgroundColor: isPaused ? '#fafafa' : '#fff',
          borderRadius: 16,
          borderWidth: 1,
          borderColor: hasError ? '#fecaca' : isPaused ? '#d4d4d4' : '#e5e5e5',
          overflow: 'hidden',
          opacity: isPaused ? 0.75 : 1,
        }}
      >
        {/* Header */}
        <TouchableOpacity onPress={handleToggle} activeOpacity={0.85}>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              paddingHorizontal: 14,
              paddingVertical: 13,
            }}
          >
            <View
              style={{
                width: 38,
                height: 38,
                borderRadius: 10,
                backgroundColor: color + '18',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: 12,
              }}
            >
              <Ionicons name={icon} size={18} color={color} />
            </View>

            <View style={{ flex: 1, minWidth: 0 }}>
              <Text
                style={{
                  fontSize: 15,
                  fontFamily: 'Nunito_700Bold',
                  color: isPaused ? '#a3a3a3' : '#0a0a0a',
                }}
                numberOfLines={1}
              >
                {displayTitle}
              </Text>
              {isPaused ? (
                <View style={{ marginTop: 3 }}>
                  <Text style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: '#737373' }}>
                    {t('plan_limit.mail_account_paused')}
                  </Text>
                </View>
              ) : (
                <StatusDotRow
                  account={account}
                  isLegend={isLegend}
                  blockedLast30d={blockedLast30d}
                  t={t}
                />
              )}
            </View>

            <Ionicons
              name={expanded ? 'chevron-up' : 'chevron-down'}
              size={18}
              color="#a3a3a3"
              style={{ marginLeft: 8 }}
            />
          </View>
        </TouchableOpacity>

        {/* Expanded body */}
        {expanded && (
          <View style={{ borderTopWidth: 1, borderTopColor: '#f5f5f5' }}>
            {/* Per-connection bar chart */}
            <View style={{ paddingHorizontal: 14, paddingTop: 14, paddingBottom: 4 }}>
              {granularity === 'too-new' ? (
                <View
                  style={{
                    borderRadius: 12,
                    backgroundColor: '#f9fafb',
                    borderWidth: 1,
                    borderColor: '#e5e5e5',
                    paddingHorizontal: 14,
                    paddingVertical: 20,
                    alignItems: 'center',
                    gap: 4,
                  }}
                >
                  <Text style={{ fontSize: 13, fontFamily: 'Nunito_600SemiBold', color: '#525252' }}>
                    {t('mail.account_chart_collecting_title')}
                  </Text>
                  <Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3', textAlign: 'center' }}>
                    {t('mail.account_chart_collecting_body')}
                  </Text>
                </View>
              ) : statsLoading && connStats.length === 0 ? (
                <View
                  style={{
                    borderRadius: 12,
                    backgroundColor: '#f9fafb',
                    borderWidth: 1,
                    borderColor: '#e5e5e5',
                    paddingHorizontal: 14,
                    paddingVertical: 16,
                    alignItems: 'center',
                  }}
                >
                  <Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
                    {t('mail.loading')}
                  </Text>
                </View>
              ) : (
                <MailBlockedByDayChart data={connStats} granularity={granularity} />
              )}
            </View>

            {/* Scan-Button + Einstellungen — horizontal nebeneinander */}
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                borderTopWidth: 1,
                borderTopColor: '#f5f5f5',
                marginTop: 8,
              }}
            >
              <TouchableOpacity
                activeOpacity={scanning ? 1 : 0.7}
                onPress={scanning ? undefined : handleScan}
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  alignItems: 'center',
                  paddingHorizontal: 14,
                  paddingVertical: 13,
                  gap: 6,
                  borderRightWidth: 1,
                  borderRightColor: '#f5f5f5',
                }}
              >
                {scanning ? (
                  <ActivityIndicator size="small" color="#a3a3a3" />
                ) : (
                  <Ionicons name="refresh" size={15} color={scanFeedback?.blocked === -1 ? '#dc2626' : '#525252'} />
                )}
                <Text
                  style={{
                    fontSize: 13,
                    fontFamily: 'Nunito_600SemiBold',
                    color: scanning
                      ? '#a3a3a3'
                      : scanFeedback?.blocked === -1
                        ? '#dc2626'
                        : scanFeedback?.blocked !== undefined
                          ? '#16a34a'
                          : '#525252',
                  }}
                  numberOfLines={1}
                >
                  {scanning
                    ? t('mail.scan_running')
                    : scanFeedback?.blocked === -1
                      ? t('mail.scan_error')
                      : scanFeedback?.blocked !== undefined
                        ? t('mail.scan_done', { count: scanFeedback.blocked })
                        : t('mail.scan_now')}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => setSettingsVisible(true)}
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  paddingHorizontal: 14,
                  paddingVertical: 13,
                  gap: 4,
                }}
              >
                <Text
                  style={{
                    fontSize: 13,
                    fontFamily: 'Nunito_600SemiBold',
                    color: '#0a0a0a',
                  }}
                >
                  {t('mail.settings_section_label')}
                </Text>
                <Ionicons name="chevron-forward" size={15} color="#a3a3a3" />
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>

      {/* Settings sub-sheet — inline edit, no nested sheets */}
      <MailAccountSettingsSheet
        visible={settingsVisible}
        account={account}
        localTitle={localTitle}
        isOAuth={isOAuth}
        plan={plan}
        disconnecting={disconnecting}
        onClose={() => setSettingsVisible(false)}
        onTitleSaved={handleTitleSaved}
        onPasswordSaved={onEditSuccess}
        onDisconnectRequest={() => { setSettingsVisible(false); setConfirmVisible(true); }}
        onIntervalChanged={onIntervalChanged}
      />

      <ConfirmAlert
        visible={confirmVisible}
        title={t('mail.disconnect_confirm_title')}
        message={t('mail.disconnect_confirm_body', { email: account.email })}
        confirmLabel={t('mail.account_disconnect_confirm_btn')}
        destructive
        icon="trash"
        iconColor="#FF3B30"
        onConfirm={async () => {
          setConfirmVisible(false);
          await onDisconnect(account.id);
          if (isOAuth) setOauthDisconnectHintVisible(true);
        }}
        onCancel={() => setConfirmVisible(false)}
      />

      <OAuthDisconnectHintModal
        visible={oauthDisconnectHintVisible}
        onClose={() => setOauthDisconnectHintVisible(false)}
        t={t}
      />
    </>
  );
}
