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/theme/app_colors.dart';
import '../../core/i18n/app_localizations.dart';
import '../shell/nav_bar_config.dart';
import '../../core/theme/app_colors_extension.dart';

/// 事前申请明细报表 - 页面22
enum _Role { employee, manager, finance, admin }

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

class _ExpenseApplyDetailReportPageState
    extends ConsumerState<ExpenseApplyDetailReportPage> {
  int _timeFilterIdx = 0;
  final _timeFilters = ['本月', '本季', '本年'];
  DateTime? _customStart;
  DateTime? _customEnd;
  int _statusFilterIdx = 0;
  final _statusFilters = ['全部', '已通过', '已拒绝', '已撤回'];
  final _role = _Role.admin;

  // Mock 近12月数据（单位：k）
  static const _months = [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月',
  ];
  static const _amountApply = [
    128.5,
    152.0,
    83.0,
    201.0,
    186.0,
    224.0,
    147.0,
    98.0,
    165.0,
    192.0,
    113.0,
    250.0,
  ];
  static const _amountApproved = [
    102.0,
    128.0,
    65.0,
    173.0,
    151.0,
    196.0,
    112.0,
    75.0,
    138.0,
    160.0,
    92.0,
    215.0,
  ];

  // 部门明细
  final _deptList = [
    _DeptItem(name: '张三', apply: 250.0, approved: 215.0),
    _DeptItem(name: '李四', apply: 182.0, approved: 150.0),
    _DeptItem(name: '王五', apply: 325.0, approved: 283.0),
    _DeptItem(name: '赵六', apply: 148.0, approved: 120.0),
    _DeptItem(name: '钱七', apply: 221.0, approved: 196.0),
  ];

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

  // ── 时间筛选 ──
  Widget _buildTimeFilter() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
      color: colors.bgCard,
      child: Row(
        children: [
          ...List.generate(_timeFilters.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(
                    _timeFilters[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}'
                        : '自定义',
                    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 _buildStatusFilter() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
      color: colors.bgCard,
      child: Row(
        children: [
          Text(
            '${l10n.get('filterStatus')}：',
            style: TextStyle(fontSize: 13, color: colors.textSecondary),
          ),
          const SizedBox(width: 4),
          ...List.generate(_statusFilters.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(
                    _statusFilters[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('statTotalApply'),
                  '¥1,939,500',
                  colors.amountPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statMonthCount'),
                  '25 笔',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statApprovedCount'),
                  '18 笔',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statApprovedAmount'),
                  '¥1,607,000',
                  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);
    final isManager = _role == _Role.manager;
    final title = isManager
        ? l10n.get('chartDeptApplyCompare')
        : l10n.get('chartTitle4');
    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('yearTotalApp')),
                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: 50,
          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: 300,
        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(), _amountApply[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: 400,
        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].apply,
                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);
    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 == _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.bgPage,
                border: Border(bottom: BorderSide(color: colors.border)),
              ),
              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('yearTotalApp'),
                      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,
                ),
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: colors.border)),
                ),
                child: Row(
                  children: [
                    SizedBox(
                      width: 100,
                      child: Text(
                        d.name,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        '¥${d.apply.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 apply;
  final double approved;
  const _DeptItem({
    required this.name,
    required this.apply,
    required this.approved,
  });
}
