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';

/// 加班明细报表 - 页面24

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

class _OvertimeDetailReportPageState
    extends ConsumerState<OvertimeDetailReportPage> {
  int _timeFilterIdx = 0;
  DateTime? _customStart;
  DateTime? _customEnd;
  int _typeFilterIdx = 0;

  // 堆叠柱状图数据：各月 工作日/休息日/节假日 工时
  static const _months = [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月',
  ];
  static const _workdayHours = [
    32.0,
    28.0,
    35.0,
    40.0,
    38.0,
    42.0,
    30.0,
    25.0,
    36.0,
    41.0,
    33.0,
    45.0,
  ];
  static const _restdayHours = [
    8.0,
    12.0,
    6.0,
    10.0,
    14.0,
    8.0,
    16.0,
    10.0,
    7.0,
    12.0,
    9.0,
    15.0,
  ];
  static const _holidayHours = [
    4.0,
    0.0,
    8.0,
    0.0,
    0.0,
    6.0,
    0.0,
    12.0,
    0.0,
    0.0,
    4.0,
    0.0,
  ];

  final _deptList = [
    _DeptItem(name: '张三', totalHours: 60.0),
    _DeptItem(name: '李四', totalHours: 45.0),
    _DeptItem(name: '王五', totalHours: 72.0),
    _DeptItem(name: '赵六', totalHours: 38.0),
    _DeptItem(name: '钱七', totalHours: 55.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('reportOvertimeDetail'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    final showDetail = role != 'employee';
    final showExport = role == 'finance' || role == 'admin';
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildTimeFilter(),
            _buildTypeFilter(),
            _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 _buildTypeFilter() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final typeLabels = [
      l10n.get('filterAll'),
      l10n.get('workday'),
      l10n.get('weekend'),
      l10n.get('holiday'),
    ];
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
      color: colors.bgCard,
      child: Row(
        children: [
          Text(
            '${l10n.get('overtimeType')}：',
            style: TextStyle(fontSize: 13, color: colors.textSecondary),
          ),
          const SizedBox(width: 4),
          ...List.generate(typeLabels.length, (i) {
            final sel = i == _typeFilterIdx;
            return Padding(
              padding: const EdgeInsets.only(right: 6),
              child: GestureDetector(
                onTap: () => setState(() => _typeFilterIdx = 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(
                    typeLabels[i],
                    style: TextStyle(
                      fontSize: 12,
                      color: sel ? colors.primary : colors.textSecondary,
                    ),
                  ),
                ),
              ),
            );
          }),
        ],
      ),
    );
  }

  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('statMonthHours'),
                  '420.5h',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statMonthTrips'),
                  '38 次',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('compHours'),
                  '168.0h',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('settleCount'),
                  '12 次',
                  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('chartDeptOvertimeCompare')
        : l10n.get('chartTitle2');
    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('workdayOvertime')),
                const SizedBox(width: 12),
                _legendDot(colors.warning, l10n.get('weekendOvertime')),
                const SizedBox(width: 12),
                _legendDot(colors.danger, l10n.get('holidayOvertime')),
              ],
            ),
            const SizedBox(height: 12),
            SizedBox(
              height: 200,
              child: isManager ? _buildDeptBarChart() : _buildStackedBarChart(),
            ),
          ],
        ),
      ),
    );
  }

  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 _buildStackedBarChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return BarChart(
      BarChartData(
        maxY: 70,
        barTouchData: BarTouchData(
          enabled: true,
          touchTooltipData: BarTouchTooltipData(
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final labels = [
                l10n.get('workdayOvertime'),
                l10n.get('weekendOvertime'),
                l10n.get('holidayOvertime'),
              ];
              return BarTooltipItem(
                '${_months[group.x.toInt()]} · ${labels[rodIndex]} ${rod.toY - rod.fromY}h',
                const TextStyle(color: Colors.white, fontSize: 12),
              );
            },
          ),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 36,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}h',
                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),
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: 20,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        barGroups: List.generate(12, (i) {
          double wd = _workdayHours[i];
          double rd = _restdayHours[i];
          double hd = _holidayHours[i];
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: wd,
                color: colors.primary,
                width: 18,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(2),
                ),
              ),
              BarChartRodData(
                fromY: wd,
                toY: wd + rd,
                color: colors.warning,
                width: 18,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(2),
                ),
              ),
              BarChartRodData(
                fromY: wd + rd,
                toY: wd + rd + hd,
                color: colors.danger,
                width: 18,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(2),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  // 部门柱状图
  Widget _buildDeptBarChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return BarChart(
      BarChartData(
        maxY: 90,
        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()}h',
                const TextStyle(color: Colors.white, fontSize: 12),
              );
            },
          ),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 36,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}h',
                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: 20,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        barGroups: List.generate(_deptList.length, (i) {
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: _deptList[i].totalHours,
                color: colors.primary,
                width: 24,
                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('overtimeInfo'),
                      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.totalHours.toStringAsFixed(1)}h',
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}

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