import {
  LayoutAnimation,
  Platform,
  Pressable,
  Text,
  UIManager,
  View,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useMailResults, type MailBlockedItem } from '../../hooks/useMailResults';

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

type Props = {
  expanded: boolean;
  onToggle: () => void;
};

function formatDate(iso: string, t: (k: string) => string): string {
  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`;
}

export function MailActivityLog({ expanded, onToggle }: Props) {
  const { t } = useTranslation();
  const { results, total, loading, refresh } = useMailResults(expanded);

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

  return (
    <View
      style={{
        backgroundColor: '#fff',
        borderRadius: 16,
        borderWidth: 1,
        borderColor: '#e5e5e5',
        overflow: 'hidden',
      }}
    >
      <Pressable onPress={handleToggle} android_ripple={{ color: '#f5f5f5' }}>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 14,
            paddingVertical: 14,
          }}
        >
          <View
            style={{
              width: 32,
              height: 32,
              borderRadius: 8,
              backgroundColor: '#fef2f2',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: 12,
            }}
          >
            <Ionicons name="trash" size={15} color="#dc2626" />
          </View>
          <View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
            <Text
              style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: '#0a0a0a' }}
              numberOfLines={1}
            >
              {t('mail.activity_log_title')}
            </Text>
            <Text
              style={{
                fontSize: 11,
                fontFamily: 'Nunito_400Regular',
                color: '#a3a3a3',
                marginTop: 2,
              }}
              numberOfLines={1}
            >
              {t('mail.activity_log_subtitle')}
            </Text>
          </View>
          <Ionicons
            name={expanded ? 'chevron-up' : 'chevron-down'}
            size={18}
            color="#a3a3a3"
          />
        </View>
      </Pressable>

      {expanded && (
        <View style={{ borderTopWidth: 1, borderTopColor: '#f5f5f5' }}>
          {loading && results.length === 0 ? (
            <View style={{ padding: 20, alignItems: 'center' }}>
              <Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
                {t('mail.loading')}
              </Text>
            </View>
          ) : results.length === 0 ? (
            <View style={{ padding: 24, alignItems: 'center' }}>
              <Ionicons name="checkmark-circle-outline" size={28} color="#16a34a" />
              <Text
                style={{
                  fontSize: 12,
                  fontFamily: 'Nunito_600SemiBold',
                  color: '#525252',
                  marginTop: 6,
                }}
              >
                {t('mail.activity_log_empty')}
              </Text>
            </View>
          ) : (
            <>
              {results.slice(0, 10).map((item) => (
                <ActivityItem key={item.id} item={item} t={t} />
              ))}
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  paddingHorizontal: 14,
                  paddingVertical: 10,
                  borderTopWidth: 1,
                  borderTopColor: '#fafafa',
                }}
              >
                <Text style={{ fontSize: 11, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
                  {total > 10
                    ? t('mail.activity_log_more', { count: total - 10 })
                    : t('mail.activity_log_count', { count: total })}
                </Text>
                <Pressable onPress={refresh} hitSlop={8}>
                  <Ionicons name="refresh" size={14} color="#737373" />
                </Pressable>
              </View>
            </>
          )}
        </View>
      )}
    </View>
  );
}

function ActivityItem({
  item,
  t,
}: {
  item: MailBlockedItem;
  t: (k: string, opts?: any) => string;
}) {
  return (
    <View
      style={{
        flexDirection: 'row',
        alignItems: 'flex-start',
        paddingHorizontal: 14,
        paddingVertical: 10,
        borderTopWidth: 1,
        borderTopColor: '#fafafa',
      }}
    >
      <View
        style={{
          width: 22,
          height: 22,
          borderRadius: 6,
          backgroundColor: '#fef2f2',
          alignItems: 'center',
          justifyContent: 'center',
          marginRight: 10,
          marginTop: 1,
        }}
      >
        <Ionicons name="close" size={12} color="#dc2626" />
      </View>
      <View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
        <Text
          style={{ fontSize: 13, fontFamily: 'Nunito_600SemiBold', color: '#0a0a0a' }}
          numberOfLines={1}
        >
          {item.subject || t('mail.activity_no_subject')}
        </Text>
        <Text
          style={{
            fontSize: 11,
            fontFamily: 'Nunito_400Regular',
            color: '#737373',
            marginTop: 1,
          }}
          numberOfLines={1}
        >
          {item.sender_name || item.sender_email}
        </Text>
      </View>
      <Text
        style={{
          fontSize: 10,
          fontFamily: 'Nunito_400Regular',
          color: '#a3a3a3',
          marginTop: 2,
        }}
      >
        {formatDate(item.received_at, t)}
      </Text>
    </View>
  );
}
