import { useState } from 'react';
import {
  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 { EditMailAccountSheet } from './EditMailAccountSheet';
import { EditMailTitleSheet } from './EditMailTitleSheet';
import { MailAccountSettingsSheet } from './MailAccountSettingsSheet';
import { MailBlockedByDayChart } from './MailBlockedByDayChart';
import type { MailAccount } from '../../hooks/useMailStatus';
import type { BlockedByDayEntry } from '../../hooks/useMailStats';

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

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;
  connectionBlockedByDay?: BlockedByDayEntry[];
};

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';
  if (!account.lastScannedAt) return 'waiting';
  const heartbeatAlive = idleHeartbeatAlive(account.lastIdleHeartbeatAt);
  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,
  connectionBlockedByDay,
}: Props) {
  const { t } = useTranslation();
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [editPasswordVisible, setEditPasswordVisible] = useState(false);
  const [editTitleVisible, setEditTitleVisible] = useState(false);
  const [confirmVisible, setConfirmVisible] = useState(false);
  const [oauthDisconnectHintVisible, setOauthDisconnectHintVisible] = useState(false);
  const [localTitle, setLocalTitle] = useState<string | null>(account.title ?? null);
  const { icon, color } = resolveProviderIcon(account.provider);

  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() {
    if (hasError) {
      setEditPasswordVisible(true);
      return;
    }
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    onToggle();
  }

  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 }}>
              {connectionBlockedByDay && connectionBlockedByDay.length > 0 ? (
                <MailBlockedByDayChart data={connectionBlockedByDay} />
              ) : (
                <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.account_chart_unavailable')}
                  </Text>
                </View>
              )}
            </View>

            {/* Einstellungen tap-row */}
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() => setSettingsVisible(true)}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 14,
                paddingVertical: 13,
                borderTopWidth: 1,
                borderTopColor: '#f5f5f5',
                marginTop: 8,
              }}
            >
              <Text
                style={{
                  flex: 1,
                  fontSize: 14,
                  fontFamily: 'Nunito_600SemiBold',
                  color: '#0a0a0a',
                }}
              >
                {t('mail.settings_section_label')}
              </Text>
              <Ionicons name="chevron-forward" size={16} color="#a3a3a3" />
            </TouchableOpacity>
          </View>
        )}
      </View>

      {/* Settings sub-sheet */}
      <MailAccountSettingsSheet
        visible={settingsVisible}
        account={account}
        localTitle={localTitle}
        isOAuth={isOAuth}
        plan={plan}
        disconnecting={disconnecting}
        onClose={() => setSettingsVisible(false)}
        onEditTitle={() => { setSettingsVisible(false); setEditTitleVisible(true); }}
        onEditPassword={() => { setSettingsVisible(false); setEditPasswordVisible(true); }}
        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}
      />

      {!isOAuth && (
        <EditMailAccountSheet
          visible={editPasswordVisible}
          email={account.email}
          onClose={() => setEditPasswordVisible(false)}
          onSuccess={onEditSuccess}
        />
      )}

      <EditMailTitleSheet
        visible={editTitleVisible}
        connectionId={account.id}
        currentTitle={localTitle}
        onClose={() => setEditTitleVisible(false)}
        onSuccess={handleTitleSaved}
      />
    </>
  );
}
