import React, { useCallback, useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../theme';
import { useT } from '../i18n';
import { getMonthGrid, type DayCell } from '../domain/calendarGrid';
import { dailyExpenseMap } from '../domain/chartStats';
import type { Transaction } from '../domain/types';

interface CalendarViewProps {
  transactions: Transaction[];
  /** 当前展示的年份。 */
  year: number;
  /** 当前展示的月份（1-12）。 */
  month: number;
  /** 选中日期变化回调（YYYY-MM-DD）。 */
  onDayPress?: (date: string) => void;
}

export function CalendarView({ transactions, year, month, onDayPress }: CalendarViewProps) {
  const { theme } = useTheme();
  const t = useT();
  // 星期头周日起（与 getMonthGrid 网格一致），文案走 i18n
  const weekdays = useMemo(() => t('calendar.weekdays').split(','), [t]);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  const weeks = useMemo(() => getMonthGrid(year, month, transactions), [year, month, transactions]);
  const dailyMap = useMemo(() => dailyExpenseMap(transactions), [transactions]);
  const maxDaily = useMemo(() => Math.max(...dailyMap.values(), 1), [dailyMap]);

  const handlePress = useCallback((cell: DayCell) => {
    if (!cell.isCurrentMonth) return;
    setSelectedDate(cell.date);
    onDayPress?.(cell.date);
  }, [onDayPress]);

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.md, padding: theme.spacing.sm }]}>
      {/* 星期表头 */}
      <View style={styles.weekdayRow}>
        {weekdays.map(d => (
          <Text key={d} style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center', flex: 1 }]}>
            {d}
          </Text>
        ))}
      </View>
      {/* 日期网格 */}
      {weeks.map((week, wi) => (
        <View key={wi} style={styles.weekRow}>
          {week.map(cell => {
            const isSelected = cell.date === selectedDate;
            const expense = dailyMap.get(cell.date) ?? 0;
            const intensity = expense / maxDaily;

            return (
              <Pressable
                key={cell.date}
                onPress={() => handlePress(cell)}
                disabled={!cell.isCurrentMonth}
                style={[
                  styles.dayCell,
                  {
                    backgroundColor: isSelected ? theme.colors.accent : 'transparent',
                    borderRadius: theme.radii.sm,
                  },
                ]}
              >
                {/* 消费热力图背景叠加层（未选中、当前月且有支出时显示） */}
                {cell.isCurrentMonth && expense > 0 && !isSelected && (
                  <View
                    style={{
                      position: 'absolute',
                      top: 2,
                      bottom: 2,
                      left: 2,
                      right: 2,
                      borderRadius: theme.radii.sm,
                      backgroundColor: theme.colors.financial.expense,
                      opacity: 0.12 + intensity * 0.68, // 12% 浅红 ~ 80% 深红
                    }}
                  />
                )}

                <Text style={[
                  theme.typography.bodySmall,
                  {
                    color: !cell.isCurrentMonth
                      ? theme.colors.border
                      : isSelected
                      ? theme.colors.fgInverse
                      : theme.colors.fgPrimary,
                    textAlign: 'center',
                    zIndex: 1,
                  },
                ]}>
                  {cell.day}
                </Text>

                {/* 交易标记圆点 */}
                {cell.count > 0 && cell.isCurrentMonth && (
                  <View style={[styles.dots, { zIndex: 1 }]}>
                    {cell.hasIncome && (
                      <View style={[styles.dot, { backgroundColor: isSelected ? theme.colors.fgInverse : theme.colors.financial.income }]} />
                    )}
                    {/* 如果没有支出热力图背景，或者选中了，才渲染支出的点，防止视觉元素重复 */}
                    {cell.hasExpense && (expense === 0 || isSelected) && (
                      <View style={[styles.dot, { backgroundColor: isSelected ? theme.colors.fgInverse : theme.colors.financial.expense }]} />
                    )}
                  </View>
                )}
              </Pressable>
            );
          })}
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 4 },
  weekdayRow: { flexDirection: 'row', marginBottom: 4 },
  weekRow: { flexDirection: 'row' },
  dayCell: { flex: 1, aspectRatio: 1, alignItems: 'center', justifyContent: 'center', paddingVertical: 4, position: 'relative' },
  dots: { flexDirection: 'row', gap: 3, marginTop: 2 },
  dot: { width: 5, height: 5, borderRadius: 2.5 },
});
