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 '../../core/i18n/app_localizations.dart';
import '../../shared/widgets/nav_bar_config.dart';
import '../../core/theme/app_colors_extension.dart';
import '../../core/auth/role_provider.dart';

/// 费用报销明细报表 - 页面23

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

class _ExpenseDetailReportPageState
    extends ConsumerState<ExpenseDetailReportPage> {
  int _timeFilterIdx = 0;
  DateTime? _customStart;
  DateTime? _customEnd;
  int _statusFilterIdx = 0;
  int _payFilterIdx = 0;

  static const _months = [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月',
  ];
  static const _amountExpense = [
    85.0,
    120.0,
    65.0,
    150.0,
    140.0,
    180.0,
    110.0,
    72.0,
    130.0,
    155.0,
    90.0,
    200.0,
  ];
  static const _amountApproved = [
    72.0,
    105.0,
    55.0,
    135.0,
    120.0,
    160.0,
    95.0,
    60.0,
    115.0,
    140.0,
    78.0,
    178.0,
  ];

  final _deptList = [
    _DeptItem(name: '张三', expense: 200.0, approved: 178.0),
    _DeptItem(name: '李四', expense: 150.0, approved: 130.0),
    _DeptItem(name: '王五', expense: 280.0, approved: 250.0),
    _DeptItem(name: '赵六', expense: 120.0, approved: 105.0),
    _DeptItem(name: '钱七', expense: 185.0, approved: 165.0),
  ];

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final role = ref.watch(currentRoleProvider);
    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('reportExpenseDetail'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    final showDetail = role != 'employee';
    final showExport = role == 'finance' || role == 'admin';
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildTimeFilter(),
            _buildStatusFilters(),
            _buildStatCards(),
            _buildChartSection(),
            if (showDetail) _buildDeptListSection(),
            const SizedBox(height: 80),
          ],
        ),
      ),
      floatingActionButton: showExport
          ? FloatingActionButton.small(
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(l10n.get('exportPlaceholder')),
                    duration: const Duration(seconds: 2),
                  ),
                );
              },
              backgroundColor: colors.primary,
              child: const Icon(Icons.download, color: Colors.white),
            )
          : null,
    );
  }

  // ── 时间筛选 ──
  Widget _buildTimeFilter() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final timeLabels = [
      l10n.get('filterThisMonth'),
      l10n.get('filterThisQuarter'),
      l10n.get('filterThisYear'),
    ];
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
      color: colors.bgCard,
      child: Row(
        children: [
          ...List.generate(timeLabels.length, (i) {
            final sel = i == _timeFilterIdx;
            return Padding(
              padding: const EdgeInsets.only(right: 8),
              child: GestureDetector(
                onTap: () => setState(() => _timeFilterIdx = i),
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 14,
                    vertical: 6,
                  ),
                  decoration: BoxDecoration(
                    color: sel ? colors.primary : colors.bgPage,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    timeLabels[i],
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: sel ? FontWeight.w600 : FontWeight.normal,
                      color: sel ? Colors.white : colors.textSecondary,
                    ),
                  ),
                ),
              ),
            );
          }),
          const Spacer(),
          GestureDetector(
            onTap: _pickCustomDateRange,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                border: Border.all(color: colors.border),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.date_range, size: 14, color: colors.textSecondary),
                  const SizedBox(width: 4),
                  Text(
                    _customStart != null && _customEnd != null
                        ? '${_customStart!.month}/${_customStart!.day}-${_customEnd!.month}/${_customEnd!.day}'
                        : l10n.get('custom'),
                    style: TextStyle(fontSize: 14, color: colors.textSecondary),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _pickCustomDateRange() async {
    final range = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDateRange: _customStart != null && _customEnd != null
          ? DateTimeRange(start: _customStart!, end: _customEnd!)
          : null,
    );
    if (range != null) {
      setState(() {
        _customStart = range.start;
        _customEnd = range.end;
        _timeFilterIdx = -1;
      });
    }
  }

  // ── 审批状态 + 付款状态 ──
  Widget _buildStatusFilters() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final statusLabels = [
      l10n.get('filterAll'),
      l10n.get('approved'),
      l10n.get('rejected'),
    ];
    final payLabels = [
      l10n.get('filterAll'),
      l10n.get('statusWaitPay'),
      l10n.get('paid'),
    ];
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
      color: colors.bgCard,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '${l10n.get('filterStatus')}：',
                style: TextStyle(fontSize: 13, color: colors.textSecondary),
              ),
              const SizedBox(width: 4),
              ...List.generate(statusLabels.length, (i) {
                final sel = i == _statusFilterIdx;
                return Padding(
                  padding: const EdgeInsets.only(right: 6),
                  child: GestureDetector(
                    onTap: () => setState(() => _statusFilterIdx = i),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: sel ? colors.primaryLight : colors.bgPage,
                        borderRadius: BorderRadius.circular(12),
                        border: sel ? Border.all(color: colors.primary) : null,
                      ),
                      child: Text(
                        statusLabels[i],
                        style: TextStyle(
                          fontSize: 12,
                          color: sel ? colors.primary : colors.textSecondary,
                        ),
                      ),
                    ),
                  ),
                );
              }),
            ],
          ),
          const SizedBox(height: 6),
          Row(
            children: [
              Text(
                '${l10n.get('filterPayment')}：',
                style: TextStyle(fontSize: 13, color: colors.textSecondary),
              ),
              const SizedBox(width: 4),
              ...List.generate(payLabels.length, (i) {
                final sel = i == _payFilterIdx;
                return Padding(
                  padding: const EdgeInsets.only(right: 6),
                  child: GestureDetector(
                    onTap: () => setState(() => _payFilterIdx = i),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: sel ? colors.primaryLight : colors.bgPage,
                        borderRadius: BorderRadius.circular(12),
                        border: sel ? Border.all(color: colors.primary) : null,
                      ),
                      child: Text(
                        payLabels[i],
                        style: TextStyle(
                          fontSize: 12,
                          color: sel ? colors.primary : colors.textSecondary,
                        ),
                      ),
                    ),
                  ),
                );
              }),
            ],
          ),
        ],
      ),
    );
  }

  // ── 4 张数值卡片 ──
  Widget _buildStatCards() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return Padding(
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statTotalApproved'),
                  '¥1,497,000',
                  colors.amountPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statMonthCount'),
                  '32 笔',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statPendingApprove'),
                  '5 笔',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statPendingPayment'),
                  '8 笔',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  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);
    final role = ref.watch(currentRoleProvider);
    final isManager = role == 'manager';
    final title = isManager
        ? l10n.get('chartDeptExpenseCompare')
        : l10n.get('chartTitle1');
    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(
              title,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: colors.textPrimary,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                _legendDot(colors.primary, l10n.get('expenseAmount')),
                const SizedBox(width: 16),
                _legendDot(colors.success, l10n.get('approvedAmount')),
              ],
            ),
            const SizedBox(height: 12),
            SizedBox(
              height: 200,
              child: isManager ? _buildDeptBarChart() : _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>()!;
    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: 40,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 40,
              getTitlesWidget: (v, meta) => Text(
                '¥${v.toInt()}k',
                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 >= _months.length) return const SizedBox();
                return Padding(
                  padding: const EdgeInsets.only(top: 4),
                  child: Text(
                    _months[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: 240,
        lineTouchData: LineTouchData(
          enabled: true,
          touchTooltipData: LineTouchTooltipData(
            getTooltipItems: (spots) => spots.map((s) {
              return LineTooltipItem(
                '${_months[s.spotIndex]}\n¥${s.y.toInt()}k',
                const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              );
            }).toList(),
          ),
        ),
        lineBarsData: [
          LineChartBarData(
            spots: List.generate(
              12,
              (i) => FlSpot(i.toDouble(), _amountExpense[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(), _amountApproved[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 _buildDeptBarChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return BarChart(
      BarChartData(
        maxY: 350,
        barTouchData: BarTouchData(
          enabled: true,
          touchTooltipData: BarTouchTooltipData(
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final item = _deptList[group.x.toInt()];
              return BarTooltipItem(
                '${item.name}\n${rod.toY.toInt()}k',
                const TextStyle(color: Colors.white, fontSize: 12),
              );
            },
          ),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 36,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}k',
                style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
              ),
            ),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 28,
              getTitlesWidget: (v, meta) {
                final i = v.toInt();
                if (i < 0 || i >= _deptList.length) return const SizedBox();
                return Padding(
                  padding: const EdgeInsets.only(top: 4),
                  child: Text(
                    _deptList[i].name,
                    style: TextStyle(
                      fontSize: 10,
                      color: colors.textPlaceholder,
                    ),
                  ),
                );
              },
            ),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
        ),
        borderData: FlBorderData(show: false),
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: 100,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        barGroups: List.generate(_deptList.length, (i) {
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: _deptList[i].expense,
                color: colors.primary,
                width: 16,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(3),
                ),
              ),
              BarChartRodData(
                toY: _deptList[i].approved,
                color: colors.success,
                width: 16,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(3),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  // ── 部门明细列表 ──
  Widget _buildDeptListSection() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final role = ref.watch(currentRoleProvider);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      child: Container(
        width: double.infinity,
        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: [
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
              child: Row(
                children: [
                  Text(
                    l10n.get('deptDashboard'),
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colors.textPrimary,
                    ),
                  ),
                  if (role == 'manager')
                    Text(
                      l10n.get('clickChartToFilter'),
                      style: TextStyle(
                        fontSize: 11,
                        color: colors.textPlaceholder,
                      ),
                    ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: colors.bgDisabled,
              ),
              child: Row(
                children: [
                  SizedBox(
                    width: 100,
                    child: Text(
                      l10n.get('creator'),
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: colors.textSecondary,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Text(
                      l10n.get('expenseAmount'),
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: colors.textSecondary,
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      l10n.get('approvedAmount'),
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: colors.textSecondary,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            ..._deptList.map(
              (d) => Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 10,
                ),
                child: Row(
                  children: [
                    SizedBox(
                      width: 100,
                      child: Text(
                        d.name,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        '¥${d.expense.toStringAsFixed(1)}k',
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Text(
                        '¥${d.approved.toStringAsFixed(1)}k',
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}

class _DeptItem {
  final String name;
  final double expense;
  final double approved;
  const _DeptItem({
    required this.name,
    required this.expense,
    required this.approved,
  });
}
