import { useState } from 'react';
import {
  ActivityIndicator,
  LayoutAnimation,
  Platform,
  Pressable,
  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 { useMailInterval } from '../../hooks/useMailInterval';
import type { MailAccount } from '../../hooks/useMailStatus';

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;
};

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 formatRelativeTime(iso: string | null, t: (k: string) => string): string {
  if (!iso) return t('mail.account_never_scanned');
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60_000);
  if (mins < 2) return t('mail.account_just_now');
  if (mins < 60) return `${mins} min`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h`;
  return `${Math.floor(hours / 24)}d`;
}

const INTERVAL_OPTIONS_BY_PLAN: Record<'free' | 'pro' | 'legend', number[]> = {
  free: [4],
  pro: [1, 4, 8],
  legend: [1, 4, 8],
};

// Solid styles outside of render — no gap, no callback layout.
const HEADER_ROW = {
  flexDirection: 'row' as const,
  alignItems: 'center' as const,
  paddingHorizontal: 14,
  paddingVertical: 14,
};

const ACTION_BTN_BASE = {
  flex: 1,
  flexDirection: 'row' as const,
  alignItems: 'center' as const,
  justifyContent: 'center' as const,
  paddingVertical: 12,
  borderRadius: 10,
};

export function MailAccountCard({
  account,
  plan,
  expanded,
  onToggle,
  onDisconnect,
  onIntervalChanged,
  onEditSuccess,
  disconnecting,
}: Props) {
  const { t } = useTranslation();
  const [confirmVisible, setConfirmVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const { setInterval, updating } = useMailInterval();
  const { icon, color } = resolveProviderIcon(account.provider);

  const isLegend = plan === 'legend';
  const intervalOptions = INTERVAL_OPTIONS_BY_PLAN[plan];

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

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

  return (
    <>
      <View
        style={{
          backgroundColor: '#fff',
          borderRadius: 16,
          borderWidth: 1,
          borderColor: '#e5e5e5',
          overflow: 'hidden',
        }}
      >
        {/* ── Header ── */}
        <Pressable onPress={handleToggle} android_ripple={{ color: '#f5f5f5' }}>
          <View style={HEADER_ROW}>
            <View
              style={{
                width: 40,
                height: 40,
                borderRadius: 10,
                backgroundColor: color + '18',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: 12,
              }}
            >
              <Ionicons name={icon} size={19} color={color} />
            </View>

            <View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
              <Text
                style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: '#0a0a0a' }}
                numberOfLines={1}
              >
                {account.email}
              </Text>
              <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 3 }}>
                <View
                  style={{
                    width: 6,
                    height: 6,
                    borderRadius: 3,
                    backgroundColor: account.isActive ? '#16a34a' : '#dc2626',
                    marginRight: 5,
                  }}
                />
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_600SemiBold',
                    color: account.isActive ? '#16a34a' : '#dc2626',
                    marginRight: 8,
                  }}
                >
                  {account.isActive
                    ? isLegend
                      ? t('mail.live')
                      : t('mail.account_active')
                    : t('mail.account_inactive')}
                </Text>
                <Text
                  style={{ fontSize: 11, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}
                  numberOfLines={1}
                >
                  · {formatRelativeTime(account.lastScannedAt, t)}
                </Text>
              </View>
            </View>

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

        {/* ── Body ── */}
        {expanded && (
          <View style={{ borderTopWidth: 1, borderTopColor: '#f5f5f5', padding: 14 }}>
            {/* Big stat: Blocked */}
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#fef2f2',
                borderRadius: 12,
                paddingHorizontal: 14,
                paddingVertical: 12,
                marginBottom: 12,
              }}
            >
              <Ionicons name="shield-checkmark" size={20} color="#dc2626" style={{ marginRight: 10 }} />
              <View style={{ flex: 1 }}>
                <Text
                  style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: '#dc2626' }}
                >
                  {t('mail.account_stat_blocked')}
                </Text>
                <Text
                  style={{
                    fontSize: 22,
                    fontFamily: 'Nunito_800ExtraBold',
                    color: '#dc2626',
                    marginTop: 1,
                  }}
                >
                  {account.totalBlocked.toLocaleString()}
                </Text>
              </View>
              <Text
                style={{ fontSize: 11, fontFamily: 'Nunito_400Regular', color: '#737373' }}
              >
                {t('mail.account_of_scanned', {
                  scanned: account.totalScanned.toLocaleString(),
                })}
              </Text>
            </View>

            {/* Scan Mode */}
            {isLegend ? (
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  backgroundColor: '#f0fdf4',
                  borderRadius: 10,
                  paddingHorizontal: 12,
                  paddingVertical: 10,
                  marginBottom: 12,
                }}
              >
                <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>
            ) : (
              <View style={{ marginBottom: 12 }}>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'Nunito_600SemiBold',
                    color: '#737373',
                    textTransform: 'uppercase',
                    letterSpacing: 0.6,
                    marginBottom: 6,
                  }}
                >
                  {t('mail.scan_interval_label')}
                </Text>
                <View style={{ flexDirection: 'row' }}>
                  {intervalOptions.map((opt, idx) => {
                    const active = account.scanInterval === opt;
                    const disabled = plan === 'free' || updating === account.id;
                    return (
                      <Pressable
                        key={opt}
                        disabled={disabled}
                        onPress={() => handleSetInterval(opt)}
                        style={{
                          flex: 1,
                          paddingVertical: 9,
                          borderRadius: 10,
                          alignItems: 'center',
                          backgroundColor: active ? '#007AFF' : '#f5f5f5',
                          marginLeft: idx === 0 ? 0 : 6,
                          opacity: disabled && !active ? 0.5 : 1,
                        }}
                      >
                        <Text
                          style={{
                            fontSize: 13,
                            fontFamily: 'Nunito_700Bold',
                            color: active ? '#fff' : '#525252',
                          }}
                        >
                          {opt}h
                        </Text>
                      </Pressable>
                    );
                  })}
                </View>
                {plan === 'free' && (
                  <Text
                    style={{
                      fontSize: 10,
                      fontFamily: 'Nunito_400Regular',
                      color: '#a3a3a3',
                      marginTop: 6,
                    }}
                  >
                    {t('mail.free_scan_interval_hint')}
                  </Text>
                )}
              </View>
            )}

            {/* Action Row */}
            <View style={{ flexDirection: 'row' }}>
              <Pressable
                onPress={() => setEditVisible(true)}
                style={{ ...ACTION_BTN_BASE, backgroundColor: '#f5f5f5', marginRight: 6 }}
              >
                <Ionicons
                  name="key-outline"
                  size={14}
                  color="#525252"
                  style={{ marginRight: 6 }}
                />
                <Text
                  style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#525252' }}
                  numberOfLines={1}
                >
                  {t('mail.account_change_password')}
                </Text>
              </Pressable>
              <Pressable
                onPress={() => setConfirmVisible(true)}
                disabled={disconnecting}
                style={{
                  ...ACTION_BTN_BASE,
                  backgroundColor: '#fef2f2',
                  marginLeft: 6,
                  opacity: disconnecting ? 0.6 : 1,
                }}
              >
                {disconnecting ? (
                  <ActivityIndicator size="small" color="#dc2626" />
                ) : (
                  <>
                    <Ionicons
                      name="trash-outline"
                      size={14}
                      color="#dc2626"
                      style={{ marginRight: 6 }}
                    />
                    <Text
                      style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#dc2626' }}
                      numberOfLines={1}
                    >
                      {t('mail.disconnect')}
                    </Text>
                  </>
                )}
              </Pressable>
            </View>
          </View>
        )}
      </View>

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

      <EditMailAccountSheet
        visible={editVisible}
        email={account.email}
        onClose={() => setEditVisible(false)}
        onSuccess={onEditSuccess}
      />
    </>
  );
}
