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 { useSafeAreaInsets } from 'react-native-safe-area-context';
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 { MailActivityLog } 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,
  colors,
}: {
  expanded: boolean;
  onToggle: () => void;
  blockedByDay: import('../../hooks/useMailStats').BlockedByDayEntry[];
  colors: import('../../lib/theme').ColorScheme;
}) {
  const { t } = useTranslation();

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

  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>
            <Text
              style={{
                fontSize: 11,
                fontFamily: 'Nunito_400Regular',
                color: colors.textMuted,
                marginTop: 2,
              }}
              numberOfLines={1}
            >
              {t('mail.more_infos_subtitle')}
            </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,
            paddingVertical: 12,
          }}
        >
          <MailBlockedByDayChart data={blockedByDay} />
        </View>
      )}
    </View>
  );
}

export default function MailScreen() {
  const { t } = useTranslation();
  const tabBarHeight = useBottomTabBarHeight();
  const insets = useSafeAreaInsets();
  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 } = useMailStats(hasAccounts);

  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 [activityLogExpanded, setActivityLogExpanded] = useState(false);
  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);
    refresh();
  }

  function handleConnectSuccess() {
    refresh();
    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 + 88,
        }}
        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. ACCOUNT LIST */}
        {hasAccounts && (
          <View style={{ marginBottom: 10, paddingHorizontal: 2 }}>
            <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>
        )}

        {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={refresh}
                  onEditSuccess={handleConnectSuccess}
                  disconnecting={disconnectingId === account.id && disconnecting}
                  blockedLast30d={connStat?.count}
                />
              );
            })}
          </View>
        )}

        {/* 3. COLLAPSIBLE "MEHR INFOS" — Bar-Chart letzte 30 Tage */}
        {hasAccounts && (
          <View style={{ marginTop: 14 }}>
            <MoreInfosSection
              expanded={moreInfosExpanded}
              onToggle={() => setMoreInfosExpanded((p) => !p)}
              blockedByDay={blockedByDay}
              colors={colors}
            />
          </View>
        )}

        {/* 4. ACTIVITY LOG */}
        {hasAccounts && (
          <View style={{ marginTop: 14 }}>
            <MailActivityLog
              expanded={activityLogExpanded}
              onToggle={() => setActivityLogExpanded((p) => !p)}
              providers={distinctProviders}
            />
          </View>
        )}
      </ScrollView>

      {/* 5. FAB — Floating Action Button */}
      <TouchableOpacity
        onPress={handleAddPress}
        activeOpacity={0.85}
        accessibilityLabel={t('mail.add_account_a11y')}
        style={{
          position: 'absolute',
          right: 24,
          bottom: tabBarHeight + Math.max(insets.bottom, 16) + 16,
          width: 56,
          height: 56,
          borderRadius: 28,
          backgroundColor: colors.brandOrange,
          alignItems: 'center',
          justifyContent: 'center',
          shadowColor: '#000',
          shadowOffset: { width: 0, height: 2 },
          shadowOpacity: 0.18,
          shadowRadius: 6,
          elevation: 6,
        }}
      >
        <Ionicons name="add" size={28} color="#fff" />
      </TouchableOpacity>

      <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); refresh(); }}
        />
      )}

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