import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../core/i18n/app_localizations.dart';
import '../../shared/widgets/nav_bar_config.dart';
import '../../core/theme/app_colors_extension.dart';
import '../expense_apply/expense_apply_api.dart';
import '../expense_apply/report_model.dart';

/// 事前申请明细报表 - 页面22

class ExpenseApplyDetailReportPage extends ConsumerStatefulWidget {
  const ExpenseApplyDetailReportPage({super.key});
  @override
  ConsumerState<ExpenseApplyDetailReportPage> createState() =>
      _ExpenseApplyDetailReportPageState();
}

class _ExpenseApplyDetailReportPageState
    extends ConsumerState<ExpenseApplyDetailReportPage> {
  final _startCtrl = TextEditingController();
  final _endCtrl = TextEditingController();
  bool _loading = true;
  String? _error;
  ReportData? _data;

  @override
  void initState() {
    super.initState();
    final now = DateTime.now();
    _startCtrl.text = '${now.year}-01-01';
    _endCtrl.text = '${now.year}-12-31';
    _loadData();
  }

  @override
  void dispose() {
    _startCtrl.dispose();
    _endCtrl.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final api = ref.read(expenseApplyApiProvider);
      final data = await api.getExpenseApplyReport(
        startDate: _startCtrl.text.isNotEmpty ? _startCtrl.text : null,
        endDate: _endCtrl.text.isNotEmpty ? _endCtrl.text : null,
      );
      if (mounted) setState(() { _data = data; _loading = false; });
    } catch (e) {
      if (mounted) setState(() { _error = e.toString(); _loading = false; });
    }
  }

  void _pickDate(TextEditingController ctrl) {
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final now = DateTime.now();
    TDPicker.showDatePicker(
      context,
      title: l10n.get('selectDate'),
      backgroundColor: colors.bgCard,
      useYear: true,
      useMonth: true,
      useDay: true,
      useHour: false,
      useMinute: false,
      useSecond: false,
      useWeekDay: false,
      dateStart: const [2020, 1, 1],
      dateEnd: [now.year + 1, 12, 31],
      initialDate: [now.year, now.month, now.day],
      onConfirm: (selected) {
        ctrl.text =
            '${selected['year']}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
        setState(() {});
        Navigator.of(context).pop();
      },
    );
  }

  void _applyFilter() {
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    setNavBarTitle(
      context,
      ref,
      NavBarConfig(
        title: l10n.get('reportExpenseApplyDetail'),
        showBack: true,
        onBack: () => context.pop(),
      ),
    );
    if (_loading) {
      return Scaffold(
        body: Center(child: CircularProgressIndicator(color: colors.primary)),
      );
    }
    if (_error != null) {
      return Scaffold(
        body: Center(
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Text(_error!, style: TextStyle(color: colors.textSecondary)),
            const SizedBox(height: 12),
            TDButton(text: l10n.get('retry'), theme: TDButtonTheme.primary, onTap: _loadData),
          ]),
        ),
      );
    }
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildDateFilter(),
            _buildStatCards(),
            _buildChartSection(),
            _buildDetailList(),
            const SizedBox(height: 80),
          ],
        ),
      ),
    );
  }

  // ── 日期筛选 ──
  Widget _buildDateFilter() {
    final tdTheme = TDTheme.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return Container(
      decoration: BoxDecoration(
        color: colors.bgCard,
        border: Border(bottom: BorderSide(color: tdTheme.componentStrokeColor)),
      ),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
        child: Row(children: [
          Expanded(child: GestureDetector(onTap: () => _pickDate(_startCtrl), child: _dateChip(_startCtrl, l10n.get('filterStartDate'), tdTheme, colors))),
          const SizedBox(width: 8),
          Text('—', style: TextStyle(fontSize: 14, color: colors.textSecondary)),
          const SizedBox(width: 8),
          Expanded(child: GestureDetector(onTap: () => _pickDate(_endCtrl), child: _dateChip(_endCtrl, l10n.get('filterEndDate'), tdTheme, colors))),
          const SizedBox(width: 8),
          GestureDetector(
            onTap: _applyFilter,
            child: Container(width: 40, height: 40, decoration: BoxDecoration(color: colors.primary, borderRadius: BorderRadius.circular(20)), child: const Icon(Icons.search, color: Colors.white, size: 22)),
          ),
        ]),
      ),
    );
  }

  Widget _dateChip(
      TextEditingController ctrl, String hint, TDThemeData tdTheme, AppColorsExtension colors) {
    final text = ctrl.text;
    return Container(
      height: 36, padding: const EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(color: colors.bgSecondaryContainer, borderRadius: BorderRadius.circular(18), border: Border.all(color: tdTheme.componentStrokeColor)),
      child: Row(children: [
        Icon(Icons.calendar_today, size: 14, color: colors.textSecondary), const SizedBox(width: 4),
        Expanded(child: Text(text.isNotEmpty ? text : hint, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: text.isNotEmpty ? colors.textPrimary : colors.textSecondary))),
        if (text.isNotEmpty) GestureDetector(onTap: () { ctrl.clear(); setState(() {}); }, child: Icon(Icons.close, size: 16, color: colors.textSecondary)),
      ]),
    );
  }

  // ── 4 张数值卡片 ──
  Widget _buildStatCards() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final summary = _data?.summary ?? const ReportSummary();
    return Padding(
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statTotalApply'),
                  '¥${summary.totalAmount.toStringAsFixed(2)}',
                  colors.amountPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statMonthCount'),
                  '${summary.totalCount} 笔',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statApprovedCount'),
                  '${summary.approvedCount} 笔',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statApprovedAmount'),
                  '¥${summary.approvedAmount.toStringAsFixed(2)}',
                  colors.amountPrimary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _statCard(String label, String value, Color valueColor) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 8),
      decoration: BoxDecoration(
        color: colors.bgCard,
        borderRadius: BorderRadius.circular(8),
        boxShadow: const [
          BoxShadow(
            color: Color(0x08000000),
            blurRadius: 4,
            offset: Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w700,
              color: valueColor,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(fontSize: 12, color: colors.textSecondary),
          ),
        ],
      ),
    );
  }

  // ── 图表区域 ──
  Widget _buildChartSection() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: colors.bgCard,
          borderRadius: BorderRadius.circular(8),
          boxShadow: const [
            BoxShadow(
              color: Color(0x08000000),
              blurRadius: 4,
              offset: Offset(0, 1),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              l10n.get('chartTitle4'),
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: colors.textPrimary,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                _legendDot(colors.primary, l10n.get('yearTotalApp')),
                const SizedBox(width: 16),
                _legendDot(colors.success, l10n.get('approvedAmount')),
              ],
            ),
            const SizedBox(height: 12),
            SizedBox(
              height: 200,
              child: _buildDualLineChart(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _legendDot(Color color, String label) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(color: color, shape: BoxShape.circle),
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: TextStyle(fontSize: 11, color: colors.textSecondary),
        ),
      ],
    );
  }

  // 双折线图
  Widget _buildDualLineChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;

    // 从 monthly 构建 12 个月的数据，无数据的月份默认为 0
    final monthlyMap = <int, ReportMonthlyItem>{};
    for (final item in (_data?.monthly ?? [])) {
      monthlyMap[item.month] = item;
    }
    final monthLabels = List.generate(12, (i) => '${i + 1}月');
    final amountData = List.generate(12, (i) {
      return monthlyMap[i + 1]?.amount ?? 0;
    });
    final approvedData = List.generate(12, (i) {
      return monthlyMap[i + 1]?.approvedAmount ?? 0;
    });

    // 计算 Y 轴最大值
    final allValues = [...amountData, ...approvedData];
    final maxVal = allValues.reduce((a, b) => a > b ? a : b);
    final maxY = (maxVal > 0 ? maxVal * 1.2 : 100).toDouble();

    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: maxY / 5,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 48,
              getTitlesWidget: (v, meta) => Text(
                '¥${v.toInt()}',
                style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
              ),
            ),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              interval: 1,
              reservedSize: 26,
              getTitlesWidget: (v, meta) {
                final i = v.toInt();
                if (i < 0 || i >= monthLabels.length) return const SizedBox();
                return Padding(
                  padding: const EdgeInsets.only(top: 4),
                  child: Text(
                    monthLabels[i],
                    style: TextStyle(
                      fontSize: 9,
                      color: colors.textPlaceholder,
                    ),
                  ),
                );
              },
            ),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
        ),
        borderData: FlBorderData(show: false),
        minY: 0,
        maxY: maxY,
        lineTouchData: LineTouchData(
          enabled: true,
          touchTooltipData: LineTouchTooltipData(
            getTooltipItems: (spots) => spots.map((s) {
              return LineTooltipItem(
                '${monthLabels[s.spotIndex]}\n¥${s.y.toStringAsFixed(0)}',
                const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              );
            }).toList(),
          ),
        ),
        lineBarsData: [
          LineChartBarData(
            spots: List.generate(
              12,
              (i) => FlSpot(i.toDouble(), amountData[i]),
            ),
            isCurved: true,
            color: colors.primary,
            barWidth: 2.5,
            dotData: FlDotData(
              show: true,
              getDotPainter: (spot, percent, barData, index) =>
                  FlDotCirclePainter(
                    radius: 3,
                    color: colors.primary,
                    strokeWidth: 0,
                  ),
            ),
            belowBarData: BarAreaData(
              show: true,
              color: colors.primary.withValues(alpha: 0.08),
            ),
          ),
          LineChartBarData(
            spots: List.generate(
              12,
              (i) => FlSpot(i.toDouble(), approvedData[i]),
            ),
            isCurved: true,
            color: colors.success,
            barWidth: 2.5,
            dotData: FlDotData(
              show: true,
              getDotPainter: (spot, percent, barData, index) =>
                  FlDotCirclePainter(
                    radius: 3,
                    color: colors.success,
                    strokeWidth: 0,
                  ),
            ),
            belowBarData: BarAreaData(
              show: true,
              color: colors.success.withValues(alpha: 0.08),
            ),
          ),
        ],
      ),
    );
  }

  // ── 明细列表 ──
  Widget _buildDetailList() {
    final details = _data?.details ?? [];
    if (details.isEmpty) return const SizedBox.shrink();
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final headerStyle = TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colors.textSecondary);
    final rowStyle = TextStyle(fontSize: 13, color: colors.textPrimary);
    final amountStyle = TextStyle(fontSize: 13, color: colors.amountPrimary, fontWeight: FontWeight.w600);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(color: colors.bgCard, borderRadius: BorderRadius.circular(8)),
        child: Column(children: [
          Padding(padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), child: Row(children: [
            Text(l10n.get('detailList'), style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: colors.textPrimary)),
            const Spacer(),
            Text('${details.length} ${l10n.get('items')}', style: TextStyle(fontSize: 12, color: colors.textSecondary)),
          ])),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            color: colors.bgDisabled,
            child: Row(children: [
              Expanded(flex: 3, child: Text(l10n.get('expenseApplyNo'), style: headerStyle)),
              const SizedBox(width: 8),
              SizedBox(width: 80, child: Text(l10n.get('date'), style: headerStyle)),
              const SizedBox(width: 8),
              SizedBox(width: 80, child: Text(l10n.get('estimatedAmount'), textAlign: TextAlign.right, style: headerStyle)),
              const SizedBox(width: 8),
              SizedBox(width: 60, child: Text(l10n.get('filterStatus'), textAlign: TextAlign.center, style: headerStyle)),
            ]),
          ),
          ...details.map((d) {
            final approved = d.isApproved;
            final chipColor = approved ? colors.success : colors.warning;
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                Expanded(flex: 3, child: Text(d.billNo, style: rowStyle, maxLines: 2, overflow: TextOverflow.ellipsis)),
                const SizedBox(width: 8),
                SizedBox(width: 80, child: Text(d.billDate != null && d.billDate!.length >= 10 ? d.billDate!.substring(0, 10) : '-', style: rowStyle, maxLines: 2)),
                const SizedBox(width: 8),
                SizedBox(width: 80, child: Text('¥${d.amount.toStringAsFixed(2)}', textAlign: TextAlign.right, style: amountStyle, maxLines: 1, overflow: TextOverflow.ellipsis)),
                const SizedBox(width: 8),
                SizedBox(width: 60, child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: chipColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: chipColor, width: 0.5),
                  ),
                  child: Text(
                    approved ? l10n.get('approved') : l10n.get('pending'),
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 11, color: chipColor, fontWeight: FontWeight.w500),
                  ),
                )),
              ]),
            );
          }),
          const SizedBox(height: 8),
        ]),
      ),
    );
  }
}
