import { useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  LayoutAnimation,
  Platform,
  ScrollView,
  Text,
  TouchableOpacity,
  UIManager,
  View,
} from 'react-native';
import { useBottomTabBarHeight } from 'react-native-bottom-tabs';
import { useTranslation } from 'react-i18next';
import { Ionicons } from '@expo/vector-icons';
import { AppHeader } from '../../components/AppHeader';
import { MailAccountCard } from '../../components/mail/MailAccountCard';
import { MailEmptyState } from '../../components/mail/MailEmptyState';
import { MailActivityLogBody } from '../../components/mail/MailActivityLog';
import { MailBlockedByDayChart } from '../../components/mail/MailBlockedByDayChart';
import { MailDistributionChart } from '../../components/mail/MailDistributionChart';
import { ConnectMailSheet } from '../../components/mail/ConnectMailSheet';
import { EditMailTitleSheet } from '../../components/mail/EditMailTitleSheet';
import { SuccessAlert } from '../../components/SuccessAlert';
import { useMailStatus } from '../../hooks/useMailStatus';
import { useMailDisconnect } from '../../hooks/useMailDisconnect';
import { useMailStats } from '../../hooks/useMailStats';
import { useUserPlan } from '../../hooks/useUserPlan';
import { useColors } from '../../lib/theme';
import { useMailConnectDraft } from '../../stores/mailConnectDraft';

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

const PLAN_LABEL: Record<string, string> = { free: 'Free', pro: 'Pro', legend: 'Legend' };

function MailOverLimitBanner({
  usedCount,
  maxAccounts,
  planLabel,
  pausedEmails,
  colors,
}: {
  usedCount: number;
  maxAccounts: number;
  planLabel: string;
  pausedEmails: string[];
  colors: import('../../lib/theme').ColorScheme;
}) {
  const { t } = useTranslation();
  const over = usedCount - maxAccounts;
  if (over <= 0) return null;

  return (
    <View
      style={{
        backgroundColor: 'rgba(217,119,6,0.08)',
        borderRadius: 14,
        padding: 14,
        marginBottom: 14,
        borderWidth: 1,
        borderColor: 'rgba(217,119,6,0.2)',
        gap: 6,
      }}
    >
      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
        <Ionicons name="warning-outline" size={16} color="#d97706" />
        <Text style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: '#d97706', flex: 1 }}>
          {t('plan_limit.mail_banner_title')}
        </Text>
      </View>
      <Text style={{ fontSize: 13, color: colors.text, fontFamily: 'Nunito_400Regular', lineHeight: 18 }}>
        {t(over === 1 ? 'plan_limit.mail_banner_body_one' : 'plan_limit.mail_banner_body_other', {
          used: usedCount,
          plan: planLabel,
          max: maxAccounts,
          over,
        })}
      </Text>
      {pausedEmails.length > 0 && (
        <Text style={{ fontSize: 12, color: colors.textMuted, fontFamily: 'Nunito_400Regular' }}>
          {pausedEmails.join(', ')}
        </Text>
      )}
    </View>
  );
}

function MoreInfosSection({
  expanded,
  onToggle,
  blockedByDay,
  providers,
  colors,
}: {
  expanded: boolean;
  onToggle: () => void;
  blockedByDay: import('../../hooks/useMailStats').BlockedByDayEntry[];
  providers: string[];
  colors: import('../../lib/theme').ColorScheme;
}) {
  const { t } = useTranslation();
  const [activityExpanded, setActivityExpanded] = useState(false);

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

  function handleActivityToggle() {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    setActivityExpanded((p) => !p);
  }

  return (
    <View
      style={{
        backgroundColor: colors.surface,
        borderRadius: 16,
        borderWidth: 1,
        borderColor: colors.border,
        overflow: 'hidden',
      }}
    >
      <TouchableOpacity onPress={handleToggle} activeOpacity={0.85}>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 14,
            paddingVertical: 14,
          }}
        >
          <View
            style={{
              width: 32,
              height: 32,
              borderRadius: 8,
              backgroundColor: '#eff6ff',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: 12,
            }}
          >
            <Ionicons name="bar-chart-outline" size={15} color="#2563eb" />
          </View>
          <View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
            <Text
              style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: colors.text }}
              numberOfLines={1}
            >
              {t('mail.more_infos_title')}
            </Text>
          </View>
          <Ionicons
            name={expanded ? 'chevron-up' : 'chevron-down'}
            size={18}
            color={colors.textMuted}
          />
        </View>
      </TouchableOpacity>

      {expanded && (
        <View
          style={{
            borderTopWidth: 1,
            borderTopColor: colors.border,
            paddingHorizontal: 12,
            paddingTop: 12,
            paddingBottom: 12,
            gap: 10,
          }}
        >
          {/* Bar-Chart direkt sichtbar */}
          <MailBlockedByDayChart data={blockedByDay} />

          {/* Nested: Kürzlich blockiert — default collapsed */}
          <View
            style={{
              backgroundColor: colors.surfaceElevated ?? colors.surface,
              borderRadius: 12,
              borderWidth: 1,
              borderColor: colors.border,
              overflow: 'hidden',
            }}
          >
            <TouchableOpacity onPress={handleActivityToggle} activeOpacity={0.85}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  paddingHorizontal: 12,
                  paddingVertical: 12,
                }}
              >
                <View
                  style={{
                    width: 28,
                    height: 28,
                    borderRadius: 7,
                    backgroundColor: '#fef2f2',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: 10,
                  }}
                >
                  <Ionicons name="trash" size={13} color="#dc2626" />
                </View>
                <View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
                  <Text
                    style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: colors.text }}
                    numberOfLines={1}
                  >
                    {t('mail.activity_log_title')}
                  </Text>
                  <Text
                    style={{
                      fontSize: 11,
                      fontFamily: 'Nunito_400Regular',
                      color: colors.textMuted,
                      marginTop: 1,
                    }}
                    numberOfLines={1}
                  >
                    {t('mail.activity_log_subtitle')}
                  </Text>
                </View>
                <Ionicons
                  name={activityExpanded ? 'chevron-up' : 'chevron-down'}
                  size={16}
                  color={colors.textMuted}
                />
              </View>
            </TouchableOpacity>

            {activityExpanded && (
              <MailActivityLogBody providers={providers} colors={colors} />
            )}
          </View>
        </View>
      )}
    </View>
  );
}

export default function MailScreen() {
  const { t } = useTranslation();
  const tabBarHeight = useBottomTabBarHeight();
  const colors = useColors();

  const { plan } = useUserPlan();

  const { accounts, totalBlocked, maxAccounts, loading, refresh } =
    useMailStatus(plan);
  const { disconnect, disconnecting } = useMailDisconnect();
  const hasAccounts = accounts.length > 0;
  const { blockedByDay, blockedByConnection, refresh: refreshStats } = useMailStats(hasAccounts);

  // Globaler Refresh-Handler für alle reactive-Trigger (Scan-Success,
  // Interval-Change, Connect/Disconnect): refresht beide Datenquellen
  // parallel — useMailStatus (accounts, connect-errors, heartbeat) UND
  // useMailStats (blockedByDay, blockedByConnection für Charts + Counter).
  const refreshAll = () => {
    refresh();
    refreshStats();
  };

  const [sheetVisible, setSheetVisible] = useState(false);
  const [successVisible, setSuccessVisible] = useState(false);
  const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
  const [expandedAccount, setExpandedAccount] = useState<string | null>(null);
  const [moreInfosExpanded, setMoreInfosExpanded] = useState(false);
  const [oauthTitleSheetConnectionId, setOauthTitleSheetConnectionId] = useState<string | null>(null);

  const { pendingOAuthConnectionId, setPendingOAuthConnectionId } = useMailConnectDraft();

  const pausedAccounts = accounts.filter((a) => a.paused === true);
  const overLimit = maxAccounts !== Infinity && accounts.length > maxAccounts;
  const limitReached = maxAccounts !== Infinity && accounts.length >= maxAccounts;

  const distinctProviders = [
    ...new Set(accounts.map((a) => a.provider.toLowerCase())),
  ];

  // Show distribution chart only when ≥2 accounts have data
  const showDistributionHero = blockedByConnection.length >= 2;

  function handleAddPress() {
    if (limitReached) {
      Alert.alert(t('mail.upgrade_alert_title'), t('mail.upgrade_alert_desc'));
      return;
    }
    setSheetVisible(true);
  }

  async function handleDisconnect(id: string) {
    setDisconnectingId(id);
    await disconnect(id);
    setDisconnectingId(null);
    if (expandedAccount === id) setExpandedAccount(null);
    refreshAll();
  }

  function handleConnectSuccess() {
    refreshAll();
    if (pendingOAuthConnectionId) {
      setOauthTitleSheetConnectionId(pendingOAuthConnectionId);
      setPendingOAuthConnectionId(null);
    } else {
      setSuccessVisible(true);
    }
  }

  function toggleAccount(id: string) {
    setExpandedAccount((prev) => (prev === id ? null : id));
  }

  if (loading) {
    return (
      <View style={{ flex: 1, backgroundColor: colors.bg }}>
        <AppHeader />
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator size="large" color="#007AFF" />
        </View>
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: colors.bg }}>
      <AppHeader />

      <ScrollView
        contentContainerStyle={{
          paddingHorizontal: 16,
          paddingTop: 16,
          paddingBottom: tabBarHeight + 24,
        }}
        showsVerticalScrollIndicator={false}
      >
        {/* Over-limit banner */}
        {overLimit && pausedAccounts.length > 0 && (
          <MailOverLimitBanner
            usedCount={accounts.length}
            maxAccounts={maxAccounts}
            planLabel={PLAN_LABEL[plan] ?? plan}
            pausedEmails={pausedAccounts.map((a) => a.email)}
            colors={colors}
          />
        )}

        {/* 1. HERO — Half-Donut with integrated title row */}
        {hasAccounts && showDistributionHero && (
          <View style={{ marginBottom: 14 }}>
            <MailDistributionChart
              data={blockedByConnection}
              hero
              totalBlocked={totalBlocked}
              accountCount={accounts.length}
              isLegend={plan === 'legend'}
            />
          </View>
        )}

        {/* Fallback stats row when donut is not shown (0-1 accounts with data) */}
        {hasAccounts && !showDistributionHero && (
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 16,
              borderWidth: 1,
              borderColor: colors.border,
              paddingHorizontal: 16,
              paddingVertical: 16,
              marginBottom: 14,
              flexDirection: 'row',
              alignItems: 'center',
            }}
          >
            <View style={{ flex: 1 }}>
              <Text
                style={{
                  fontSize: 22,
                  fontFamily: 'Nunito_800ExtraBold',
                  color: colors.error,
                  lineHeight: 26,
                }}
              >
                {totalBlocked.toLocaleString()}
              </Text>
              <Text
                style={{
                  fontSize: 12,
                  fontFamily: 'Nunito_400Regular',
                  color: colors.textMuted,
                  marginTop: 2,
                }}
              >
                {t('mail.stats_account_summary', { count: accounts.length })}
              </Text>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 10,
                paddingVertical: 5,
                borderRadius: 999,
                backgroundColor: plan === 'legend' ? '#f0fdf4' : '#eff6ff',
              }}
            >
              <View
                style={{
                  width: 6,
                  height: 6,
                  borderRadius: 3,
                  backgroundColor: plan === 'legend' ? '#16a34a' : '#2563eb',
                  marginRight: 6,
                }}
              />
              <Text
                style={{
                  fontSize: 12,
                  fontFamily: 'Nunito_700Bold',
                  color: plan === 'legend' ? '#16a34a' : '#2563eb',
                }}
              >
                {plan === 'legend' ? t('mail.live') : t('mail.scheduled')}
              </Text>
            </View>
          </View>
        )}

        {/* 2. COLLAPSIBLE "MEHR INFOS" — Bar-Chart + nested Kürzlich blockiert */}
        {hasAccounts && (
          <View style={{ marginBottom: 14 }}>
            <MoreInfosSection
              expanded={moreInfosExpanded}
              onToggle={() => setMoreInfosExpanded((p) => !p)}
              blockedByDay={blockedByDay}
              providers={distinctProviders}
              colors={colors}
            />
          </View>
        )}

        {/* 3. ACCOUNT LIST */}
        {hasAccounts && (
          <View style={{ marginBottom: 10, paddingHorizontal: 2 }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <View style={{ flex: 1 }}>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_700Bold',
                    color: colors.textMuted,
                    textTransform: 'uppercase',
                    letterSpacing: 0.8,
                  }}
                >
                  {t('mail.section_accounts')}
                </Text>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_400Regular',
                    color: colors.textMuted,
                    marginTop: 2,
                  }}
                >
                  {maxAccounts === Infinity
                    ? t('mail.section_accounts_count_unlimited', { used: accounts.length })
                    : t('mail.section_accounts_count', {
                        used: accounts.length,
                        max: maxAccounts,
                      })}
                </Text>
              </View>
              <TouchableOpacity
                onPress={handleAddPress}
                activeOpacity={0.7}
                accessibilityLabel={t('mail.add_account_a11y')}
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 4,
                  paddingVertical: 4,
                  paddingLeft: 8,
                }}
              >
                <Ionicons name="add-circle-outline" size={18} color={colors.brandOrange} />
                <Text
                  style={{
                    fontSize: 13,
                    fontFamily: 'Nunito_600SemiBold',
                    color: colors.brandOrange,
                  }}
                >
                  {t('mail.add_account')}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {accounts.length === 0 ? (
          <MailEmptyState onConnectPress={handleAddPress} />
        ) : (
          <View style={{ gap: 10 }}>
            {accounts.map((account) => {
              const connStat = blockedByConnection.find((c) => c.connectionId === account.id);
              return (
                <MailAccountCard
                  key={account.id}
                  account={account}
                  plan={plan}
                  expanded={expandedAccount === account.id}
                  onToggle={() => toggleAccount(account.id)}
                  onDisconnect={handleDisconnect}
                  onIntervalChanged={refreshAll}
                  onEditSuccess={handleConnectSuccess}
                  disconnecting={disconnectingId === account.id && disconnecting}
                  blockedLast30d={connStat?.count}
                  onScanSuccess={refreshAll}
                />
              );
            })}
          </View>
        )}
      </ScrollView>

      <ConnectMailSheet
        visible={sheetVisible}
        onClose={() => setSheetVisible(false)}
        onSuccess={handleConnectSuccess}
      />

      {oauthTitleSheetConnectionId && (
        <EditMailTitleSheet
          visible={!!oauthTitleSheetConnectionId}
          connectionId={oauthTitleSheetConnectionId}
          currentTitle={null}
          onClose={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); }}
          onSuccess={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); refreshAll(); }}
        />
      )}

      <SuccessAlert
        visible={successVisible}
        title={t('mail.connect_success_title')}
        message={t('mail.connect_success_message')}
        onClose={() => setSuccessVisible(false)}
      />
    </View>
  );
}
