import { useMemo } from 'react';
import { Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../lib/theme';
import type { BlockedByDayEntry } from '../../hooks/useMailStats';

type Props = {
  data: BlockedByDayEntry[];
  granularity?: 'day' | 'week' | 'month';
};

const BAR_AREA_HEIGHT = 64;
const MIN_BAR_HEIGHT = 3;

function formatAxisLabel(dateStr: string): string {
  const d = new Date(dateStr + 'T00:00:00');
  return `${d.getDate()}.${d.getMonth() + 1}.`;
}

function headingKey(granularity: 'day' | 'week' | 'month'): string {
  if (granularity === 'week') return 'mail.stats.blocked_per_week_heading';
  if (granularity === 'month') return 'mail.stats.blocked_per_month_heading';
  return 'mail.stats.blocked_per_day_heading';
}

export function MailBlockedByDayChart({ data, granularity = 'day' }: Props) {
  const { t } = useTranslation();
  const colors = useColors();

  const allZero = data.every((d) => d.count === 0);
  const total = data.reduce((s, d) => s + d.count, 0);
  const weekAvg = data.length >= 7
    ? Math.round(data.slice(-7).reduce((s, d) => s + d.count, 0))
    : total;

  const maxCount = useMemo(() => Math.max(...data.map((d) => d.count), 1), [data]);

  const axisIndices = useMemo(() => {
    if (data.length === 0) return [];
    const step = Math.floor(data.length / 4);
    return [0, step, step * 2, step * 3, data.length - 1].filter(
      (v, i, arr) => arr.indexOf(v) === i,
    );
  }, [data]);

  return (
    <View
      style={{
        backgroundColor: colors.surface,
        borderRadius: 16,
        borderWidth: 1,
        borderColor: colors.border,
        paddingHorizontal: 16,
        paddingTop: 14,
        paddingBottom: 14,
      }}
    >
      <Text
        style={{
          fontSize: 11,
          fontFamily: 'Nunito_700Bold',
          color: colors.textMuted,
          textTransform: 'uppercase',
          letterSpacing: 0.7,
          marginBottom: 10,
        }}
      >
        {t(headingKey(granularity))}
      </Text>

      {allZero ? (
        <View style={{ paddingVertical: 20, alignItems: 'center' }}>
          <Text
            style={{
              fontSize: 13,
              fontFamily: 'Nunito_600SemiBold',
              color: colors.textMuted,
              textAlign: 'center',
            }}
          >
            {t('mail.stats.empty_title')}
          </Text>
          <Text
            style={{
              fontSize: 12,
              fontFamily: 'Nunito_400Regular',
              color: colors.textMuted,
              textAlign: 'center',
              marginTop: 4,
            }}
          >
            {t('mail.stats.empty_body')}
          </Text>
        </View>
      ) : (
        <>
          {/* Bar chart */}
          <View style={{ flexDirection: 'row', alignItems: 'flex-end', height: BAR_AREA_HEIGHT, gap: 2 }}>
            {data.map((entry) => {
              const barH =
                entry.count > 0
                  ? Math.max(MIN_BAR_HEIGHT, Math.round((entry.count / maxCount) * BAR_AREA_HEIGHT))
                  : MIN_BAR_HEIGHT;
              return (
                <View
                  key={entry.date}
                  style={{
                    flex: 1,
                    height: barH,
                    borderRadius: 2,
                    backgroundColor: entry.count > 0 ? colors.error : colors.border,
                  }}
                />
              );
            })}
          </View>

          {/* Axis labels */}
          <View style={{ flexDirection: 'row', marginTop: 4, position: 'relative', height: 14 }}>
            {axisIndices.map((idx) => {
              const pct = data.length > 1 ? idx / (data.length - 1) : 0;
              return (
                <Text
                  key={idx}
                  style={{
                    position: 'absolute',
                    left: `${pct * 100}%` as any,
                    fontSize: 9,
                    fontFamily: 'Nunito_400Regular',
                    color: colors.textMuted,
                    transform: [{ translateX: idx === 0 ? 0 : idx === data.length - 1 ? -24 : -12 }],
                  }}
                >
                  {formatAxisLabel(data[idx].date)}
                </Text>
              );
            })}
          </View>

          {/* Summary line */}
          <Text
            style={{
              fontSize: 12,
              fontFamily: 'Nunito_400Regular',
              color: colors.textMuted,
              marginTop: 10,
            }}
          >
            {t('mail.stats.blocked_per_day_sublabel', { total, avg: weekAvg })}
          </Text>
        </>
      )}
    </View>
  );
}
