import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/theme/app_typography.dart';
import '../../../../app/theme/app_spacing.dart';
import '../../../../app/router.dart';

/// 融资效果分析页面
///
/// 展示融资总览统计、融资生命周期时间线、成本效益分析、
/// 流动性指标、风险指标、AI融资策略建议
class FinancingAnalysisPage extends StatelessWidget {
  const FinancingAnalysisPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('融资效果分析'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            onPressed: () {
              // TODO: Refresh financing analysis data
            },
            tooltip: '刷新数据',
          ),
          IconButton(
            icon: const Icon(Icons.download_rounded),
            onPressed: () {
              // TODO: Export financing analysis report
            },
            tooltip: '导出报告',
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Stats Cards
            _buildStatsCards(),
            const SizedBox(height: 24),

            // Financing Timeline
            _buildFinancingTimeline(),
            const SizedBox(height: 24),

            // Cost-Benefit Analysis
            _buildCostBenefitCard(),
            const SizedBox(height: 24),

            // Liquidity Metrics
            _buildLiquidityMetrics(),
            const SizedBox(height: 24),

            // Risk Indicators
            _buildRiskIndicators(),
            const SizedBox(height: 24),

            // AI Recommendation
            _buildAiRecommendation(context),
          ],
        ),
      ),
    );
  }

  // ============================================================
  // Stats Cards
  // ============================================================

  Widget _buildStatsCards() {
    final stats = [
      ('融资总额', '\$2,850,000', AppColors.primary, Icons.account_balance_rounded, '+12.5%'),
      ('平均利率', '4.2%', AppColors.info, Icons.percent_rounded, '-0.3%'),
      ('融资笔数', '18', AppColors.success, Icons.receipt_long_rounded, '+3'),
      ('资金利用率', '87.6%', AppColors.warning, Icons.pie_chart_rounded, '+5.2%'),
    ];

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 12,
        crossAxisSpacing: 12,
        childAspectRatio: 1.35,
      ),
      itemCount: stats.length,
      itemBuilder: (context, index) {
        final (label, value, color, icon, trend) = stats[index];
        final isPositiveTrend = trend.startsWith('+');
        return Container(
          padding: const EdgeInsets.all(14),
          decoration: BoxDecoration(
            color: AppColors.surface,
            borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
            border: Border.all(color: AppColors.borderLight),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    width: 32,
                    height: 32,
                    decoration: BoxDecoration(
                      color: color.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
                    ),
                    child: Icon(icon, color: color, size: 16),
                  ),
                  const Spacer(),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: isPositiveTrend ? AppColors.successLight : AppColors.errorLight,
                      borderRadius: BorderRadius.circular(AppSpacing.radiusFull),
                    ),
                    child: Text(
                      trend,
                      style: AppTypography.caption.copyWith(
                        color: isPositiveTrend ? AppColors.success : AppColors.error,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(value, style: AppTypography.h3.copyWith(color: color)),
                  const SizedBox(height: 2),
                  Text(label, style: AppTypography.caption),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  // ============================================================
  // Financing Timeline
  // ============================================================

  Widget _buildFinancingTimeline() {
    final stages = [
      ('申请提交', '2026-01-15', true, AppColors.success),
      ('审批通过', '2026-01-17', true, AppColors.success),
      ('资金到账', '2026-01-18', true, AppColors.success),
      ('使用中', '2026-01-18 ~', true, AppColors.primary),
      ('还款期', '2026-07-18', false, AppColors.textTertiary),
      ('结清', '待定', false, AppColors.textTertiary),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.timeline_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text('融资生命周期', style: AppTypography.h3),
            ],
          ),
          const SizedBox(height: 20),
          ...List.generate(stages.length, (index) {
            final (name, date, isCompleted, color) = stages[index];
            final isLast = index == stages.length - 1;
            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Timeline indicator
                Column(
                  children: [
                    Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: isCompleted ? color.withValues(alpha: 0.15) : AppColors.gray100,
                        shape: BoxShape.circle,
                        border: Border.all(color: color, width: 2),
                      ),
                      child: isCompleted
                          ? Icon(Icons.check_rounded, color: color, size: 14)
                          : null,
                    ),
                    if (!isLast)
                      Container(
                        width: 2,
                        height: 36,
                        color: isCompleted ? color.withValues(alpha: 0.3) : AppColors.gray200,
                      ),
                  ],
                ),
                const SizedBox(width: 14),
                // Content
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(bottom: isLast ? 0 : 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          name,
                          style: AppTypography.labelMedium.copyWith(
                            color: isCompleted ? AppColors.textPrimary : AppColors.textTertiary,
                          ),
                        ),
                        const SizedBox(height: 2),
                        Text(
                          date,
                          style: AppTypography.caption.copyWith(
                            color: isCompleted ? AppColors.textSecondary : AppColors.textTertiary,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          }),
        ],
      ),
    );
  }

  // ============================================================
  // Cost-Benefit Analysis
  // ============================================================

  Widget _buildCostBenefitCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.analytics_rounded, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text('成本效益分析', style: AppTypography.h3),
            ],
          ),
          const SizedBox(height: 20),

          // Interest cost vs revenue
          Row(
            children: [
              Expanded(
                child: _buildCostBenefitItem(
                  '利息成本',
                  '\$119,700',
                  '年化 4.2%',
                  AppColors.error,
                  Icons.trending_down_rounded,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildCostBenefitItem(
                  '产生收入',
                  '\$458,200',
                  '利用融资收入',
                  AppColors.success,
                  Icons.trending_up_rounded,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // Net benefit
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              gradient: AppColors.primaryGradient,
              borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '净收益',
                  style: AppTypography.labelMedium.copyWith(color: Colors.white),
                ),
                Text(
                  '\$338,500',
                  style: AppTypography.h2.copyWith(color: Colors.white),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // ROI
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('投资回报率 (ROI)', style: AppTypography.bodySmall),
              Text(
                '282.7%',
                style: AppTypography.labelLarge.copyWith(color: AppColors.success),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('收益/成本比', style: AppTypography.bodySmall),
              Text(
                '3.83x',
                style: AppTypography.labelLarge.copyWith(color: AppColors.primary),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCostBenefitItem(
    String label,
    String value,
    String subtitle,
    Color color,
    IconData icon,
  ) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.05),
        borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
        border: Border.all(color: color.withValues(alpha: 0.15)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: color, size: 16),
              const SizedBox(width: 6),
              Text(label, style: AppTypography.bodySmall.copyWith(color: color)),
            ],
          ),
          const SizedBox(height: 8),
          Text(value, style: AppTypography.h3.copyWith(color: color)),
          const SizedBox(height: 2),
          Text(subtitle, style: AppTypography.caption),
        ],
      ),
    );
  }

  // ============================================================
  // Liquidity Metrics
  // ============================================================

  Widget _buildLiquidityMetrics() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.water_drop_rounded, color: AppColors.info, size: 20),
              const SizedBox(width: 8),
              Text('流动性指标', style: AppTypography.h3),
            ],
          ),
          const SizedBox(height: 20),

          // Quick Ratio
          _buildMetricRow(
            '速动比率 (Quick Ratio)',
            '1.85',
            '健康',
            AppColors.success,
            0.85,
          ),
          const SizedBox(height: 16),

          // Current Ratio
          _buildMetricRow(
            '流动比率 (Current Ratio)',
            '2.34',
            '良好',
            AppColors.success,
            0.78,
          ),
          const SizedBox(height: 16),

          // Cash Flow Forecast
          _buildSectionTitle('现金流预测'),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: AppColors.gray50,
              borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
            ),
            child: Column(
              children: [
                _buildForecastRow('本月预计流入', '+\$85,200', AppColors.success),
                const SizedBox(height: 8),
                _buildForecastRow('本月预计流出', '-\$52,800', AppColors.error),
                const Divider(height: 16),
                _buildForecastRow('净现金流', '+\$32,400', AppColors.primary),
                const SizedBox(height: 12),
                _buildForecastRow('下月预计流入', '+\$92,500', AppColors.success),
                const SizedBox(height: 8),
                _buildForecastRow('下月预计流出', '-\$68,300', AppColors.error),
                const Divider(height: 16),
                _buildForecastRow('下月净现金流', '+\$24,200', AppColors.primary),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMetricRow(
    String label,
    String value,
    String status,
    Color statusColor,
    double progress,
  ) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(child: Text(label, style: AppTypography.bodySmall.copyWith(color: AppColors.textPrimary))),
            Row(
              children: [
                Text(value, style: AppTypography.labelLarge.copyWith(color: AppColors.textPrimary)),
                const SizedBox(width: 8),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(AppSpacing.radiusFull),
                  ),
                  child: Text(
                    status,
                    style: AppTypography.caption.copyWith(
                      color: statusColor,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
        const SizedBox(height: 8),
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: progress,
            backgroundColor: AppColors.gray100,
            valueColor: AlwaysStoppedAnimation(statusColor),
            minHeight: 6,
          ),
        ),
      ],
    );
  }

  Widget _buildForecastRow(String label, String value, Color color) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label, style: AppTypography.bodySmall),
        Text(value, style: AppTypography.labelMedium.copyWith(color: color)),
      ],
    );
  }

  // ============================================================
  // Risk Indicators
  // ============================================================

  Widget _buildRiskIndicators() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.shield_rounded, color: AppColors.warning, size: 20),
              const SizedBox(width: 8),
              Text('风险指标', style: AppTypography.h3),
            ],
          ),
          const SizedBox(height: 20),

          // Risk gauge cards
          Row(
            children: [
              Expanded(child: _buildRiskGauge('违约率', '0.8%', AppColors.success, 0.08)),
              const SizedBox(width: 12),
              Expanded(child: _buildRiskGauge('逾期率', '2.3%', AppColors.warning, 0.23)),
              const SizedBox(width: 12),
              Expanded(child: _buildRiskGauge('集中度', '35%', AppColors.info, 0.35)),
            ],
          ),
          const SizedBox(height: 20),

          // Risk detail rows
          _buildRiskDetailRow(
            '违约率 (Default Rate)',
            '0.8%',
            '低于行业平均 1.5%',
            AppColors.success,
            Icons.check_circle_rounded,
          ),
          const SizedBox(height: 12),
          _buildRiskDetailRow(
            '逾期率 (Overdue Rate)',
            '2.3%',
            '接近预警线 3.0%，需关注',
            AppColors.warning,
            Icons.warning_rounded,
          ),
          const SizedBox(height: 12),
          _buildRiskDetailRow(
            '集中度风险 (Concentration)',
            '35%',
            '最大单笔占比 35%，建议分散',
            AppColors.info,
            Icons.info_rounded,
          ),
        ],
      ),
    );
  }

  Widget _buildRiskGauge(String label, String value, Color color, double ratio) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.05),
        borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
      ),
      child: Column(
        children: [
          SizedBox(
            width: 48,
            height: 48,
            child: Stack(
              alignment: Alignment.center,
              children: [
                CircularProgressIndicator(
                  value: ratio,
                  strokeWidth: 4,
                  backgroundColor: AppColors.gray200,
                  valueColor: AlwaysStoppedAnimation(color),
                ),
                Text(
                  value,
                  style: TextStyle(fontSize: 11, fontWeight: FontWeight.w700, color: color),
                ),
              ],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: AppTypography.caption.copyWith(color: AppColors.textPrimary),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildRiskDetailRow(
    String label,
    String value,
    String description,
    Color color,
    IconData icon,
  ) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.04),
        borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
        border: Border.all(color: color.withValues(alpha: 0.12)),
      ),
      child: Row(
        children: [
          Icon(icon, color: color, size: 20),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(label, style: AppTypography.labelSmall.copyWith(color: AppColors.textPrimary)),
                    Text(
                      value,
                      style: AppTypography.labelMedium.copyWith(color: color),
                    ),
                  ],
                ),
                const SizedBox(height: 2),
                Text(description, style: AppTypography.caption),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // AI Recommendation
  // ============================================================

  Widget _buildAiRecommendation(BuildContext context) {
    final recommendations = [
      (
        '优化融资结构',
        '建议将短期融资占比从当前 60% 调整至 45%，增加中期融资比例，降低再融资风险。预计可节省利息成本 \$12,000/年。',
        Icons.account_tree_rounded,
        '高',
        AppColors.error,
      ),
      (
        '把握低利率窗口',
        '当前市场利率处于近12个月低位，建议在未来2周内锁定长期融资利率。预测下季度利率可能上行 0.3-0.5%。',
        Icons.access_time_rounded,
        '高',
        AppColors.error,
      ),
      (
        '提升资金利用率',
        '当前有 \$354,000 闲置资金，建议投入短期理财或增加券发行量，预计可增加收益 \$8,500/月。',
        Icons.rocket_launch_rounded,
        '中',
        AppColors.warning,
      ),
      (
        '分散集中度风险',
        '最大单笔融资占总额 35%，建议拆分为2-3笔，从不同渠道融资以降低单一来源依赖风险。',
        Icons.scatter_plot_rounded,
        '中',
        AppColors.warning,
      ),
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppSpacing.radiusMd),
        border: Border.all(color: AppColors.borderLight),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 32,
                height: 32,
                decoration: BoxDecoration(
                  gradient: AppColors.primaryGradient,
                  borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
                ),
                child: const Icon(Icons.auto_awesome_rounded, color: Colors.white, size: 16),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('AI 融资策略建议', style: AppTypography.h3),
                    Text('基于您的经营数据智能分析', style: AppTypography.caption),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          ...recommendations.map((r) {
            final (title, desc, icon, priority, priorityColor) = r;
            return Container(
              margin: const EdgeInsets.only(bottom: 12),
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: AppColors.primarySurface,
                borderRadius: BorderRadius.circular(AppSpacing.radiusSm),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(icon, color: AppColors.primary, size: 18),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(title, style: AppTypography.labelMedium.copyWith(color: AppColors.primary)),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: priorityColor.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(AppSpacing.radiusFull),
                        ),
                        child: Text(
                          '$priority优先',
                          style: AppTypography.caption.copyWith(
                            color: priorityColor,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Text(desc, style: AppTypography.bodySmall.copyWith(height: 1.6)),
                ],
              ),
            );
          }),

          const SizedBox(height: 8),
          SizedBox(
            width: double.infinity,
            child: OutlinedButton.icon(
              onPressed: () {
                Navigator.pushNamed(context, AppRouter.aiAgent);
              },
              icon: const Icon(Icons.auto_awesome_rounded, size: 18),
              label: const Text('获取详细融资方案'),
            ),
          ),
        ],
      ),
    );
  }

  // ============================================================
  // Shared Helpers
  // ============================================================

  Widget _buildSectionTitle(String title) {
    return Text(title, style: AppTypography.labelMedium);
  }
}
