/**
 * 趋势折线图（plan.md「5.2 图表与可视化」）。
 * 采用 react-native-svg 绘制三次贝塞尔曲线及渐变填充区域。
 */
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Animated, Dimensions, StyleSheet, Text, View } from 'react-native';
import Svg, { Path, Circle, Defs, LinearGradient, Stop } from 'react-native-svg';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import type { Transaction } from '../../domain/core/types';
import { groupByMonth } from '../../domain/stats/chartStats';

export function TrendLine({ transactions }: { transactions: Transaction[] }) {
  const { theme } = useTheme();
  const t = useT();
  const fade = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(fade, { toValue: 1, duration: 500, useNativeDriver: true }).start();
  }, [fade]);
  const data = useMemo(() => groupByMonth(transactions).slice(-6), [transactions]);

  // 1. 数据配置 —— 自适应宽度：初始取屏幕宽减去页面 padding，onLayout 后更新为容器实际宽度
  const [chartWidth, setChartWidth] = useState(() => Dimensions.get('window').width - 64);
  const height = 120;
  const paddingX = 20;
  const paddingY = 15;

  const maxVal = Math.max(...data.flatMap(d => [d.income, d.expense]), 1);

  // 2. 坐标转换计算
  const pointsIncome = data.map((d, i) => {
    const x = data.length > 1
      ? paddingX + (i * (chartWidth - 2 * paddingX)) / (data.length - 1)
      : chartWidth / 2;
    const y = height - paddingY - (d.income / maxVal) * (height - 2 * paddingY);
    return { x, y };
  });

  const pointsExpense = data.map((d, i) => {
    const x = data.length > 1
      ? paddingX + (i * (chartWidth - 2 * paddingX)) / (data.length - 1)
      : chartWidth / 2;
    const y = height - paddingY - (d.expense / maxVal) * (height - 2 * paddingY);
    return { x, y };
  });

  // 3. 贝塞尔曲线生成算法
  const getBezierPath = (points: { x: number; y: number }[]) => {
    if (points.length === 0) return '';
    if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
    let path = `M ${points[0].x} ${points[0].y}`;
    for (let i = 0; i < points.length - 1; i++) {
      const p0 = points[i];
      const p1 = points[i + 1];
      const cp1x = p0.x + (p1.x - p0.x) / 2;
      const cp1y = p0.y;
      const cp2x = p0.x + (p1.x - p0.x) / 2;
      const cp2y = p1.y;
      path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${p1.x} ${p1.y}`;
    }
    return path;
  };

  const getClosedBezierPath = (points: { x: number; y: number }[]) => {
    if (points.length === 0) return '';
    const linePath = getBezierPath(points);
    const first = points[0];
    const last = points[points.length - 1];
    return `${linePath} L ${last.x} ${height - paddingY} L ${first.x} ${height - paddingY} Z`;
  };

  const incomePath = getBezierPath(pointsIncome);
  const incomeClosedPath = getClosedBezierPath(pointsIncome);

  const expensePath = getBezierPath(pointsExpense);
  const expenseClosedPath = getClosedBezierPath(pointsExpense);

  return (
    <Animated.View style={[styles.container, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.lg, padding: theme.spacing.md, opacity: fade }]}>
      <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary }]}>
        {t('report.trendTitle')}
      </Text>
      
      {data.length > 0 ? (
        <View style={styles.chartWrapper} onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>
          <Svg width="100%" height={height} viewBox={`0 0 ${chartWidth} ${height}`}>
            <Defs>
              <LinearGradient id="incomeGrad" x1="0" y1="0" x2="0" y2="1">
                <Stop offset="0%" stopColor={theme.colors.financial.income} stopOpacity={0.25} />
                <Stop offset="100%" stopColor={theme.colors.financial.income} stopOpacity={0.0} />
              </LinearGradient>
              <LinearGradient id="expenseGrad" x1="0" y1="0" x2="0" y2="1">
                <Stop offset="0%" stopColor={theme.colors.financial.expense} stopOpacity={0.25} />
                <Stop offset="100%" stopColor={theme.colors.financial.expense} stopOpacity={0.0} />
              </LinearGradient>
            </Defs>

            {/* 网格线（只绘制一条底线和中线） */}
            <Path
              d={`M ${paddingX} ${height / 2} L ${chartWidth - paddingX} ${height / 2} M ${paddingX} ${height - paddingY} L ${chartWidth - paddingX} ${height - paddingY}`}
              stroke={theme.colors.divider}
              strokeWidth={1}
              strokeDasharray="4 4"
            />

            {/* 收入填充与折线 */}
            {incomeClosedPath ? <Path d={incomeClosedPath} fill="url(#incomeGrad)" /> : null}
            {incomePath ? (
              <Path
                d={incomePath}
                fill="none"
                stroke={theme.colors.financial.income}
                strokeWidth={2.5}
                strokeLinecap="round"
              />
            ) : null}

            {/* 支出填充与折线 */}
            {expenseClosedPath ? <Path d={expenseClosedPath} fill="url(#expenseGrad)" /> : null}
            {expensePath ? (
              <Path
                d={expensePath}
                fill="none"
                stroke={theme.colors.financial.expense}
                strokeWidth={2.5}
                strokeLinecap="round"
              />
            ) : null}

            {/* 数据点标记 */}
            {pointsIncome.map((p, i) => (
              <Circle
                key={`income-dot-${i}`}
                cx={p.x}
                cy={p.y}
                r={3.5}
                fill={theme.colors.bgSecondary}
                stroke={theme.colors.financial.income}
                strokeWidth={2}
              />
            ))}
            {pointsExpense.map((p, i) => (
              <Circle
                key={`expense-dot-${i}`}
                cx={p.x}
                cy={p.y}
                r={3.5}
                fill={theme.colors.bgSecondary}
                stroke={theme.colors.financial.expense}
                strokeWidth={2}
              />
            ))}
          </Svg>
          
          {/* 月度文本 X 轴 */}
          <View style={styles.xAxis}>
            {data.map((d, i) => (
              <Text
                key={`x-label-${i}`}
                style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontSize: theme.typography.caption.fontSize - 2 }]}
              >
                {d.month.slice(5)}
              </Text>
            ))}
          </View>
        </View>
      ) : (
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center', marginVertical: 20 }]}>
          {t('common.noData')}
        </Text>
      )}

      <View style={styles.legend}>
        <View style={[styles.legendDot, { backgroundColor: theme.colors.financial.income }]} />
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
          {t('home.income')}
        </Text>
        <View style={[styles.legendDot, { backgroundColor: theme.colors.financial.expense }]} />
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
          {t('home.expense')}
        </Text>
      </View>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 10 },
  chartWrapper: { marginTop: 6 },
  xAxis: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 12, marginTop: 4 },
  legend: { flexDirection: 'row', alignItems: 'center', gap: 4, marginTop: 4 },
  legendDot: { width: 8, height: 8, borderRadius: 4, marginLeft: 8 },
});