import 'package:flutter/material.dart';
import 'package:marquee/marquee.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../core/i18n/app_localizations.dart';
import '../../core/theme/app_colors_extension.dart';
import '../../core/auth/role_provider.dart';

/// 外勤日志明细报表 - 页面26

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

class _OutingLogDetailReportPageState
    extends ConsumerState<OutingLogDetailReportPage> {
  int _timeFilterIdx = 0;
  DateTime? _customStart;
  DateTime? _customEnd;
  final _customerSearchCtrl = TextEditingController();

  static const _months = [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月',
  ];
  // 左轴：拜访次数
  static const _visitCounts = [
    12.0,
    15.0,
    10.0,
    18.0,
    16.0,
    20.0,
    14.0,
    9.0,
    13.0,
    17.0,
    11.0,
    22.0,
  ];
  // 右轴：平均评分
  static const _avgRatings = [
    4.2,
    3.8,
    4.5,
    4.0,
    4.3,
    3.9,
    4.1,
    4.6,
    4.0,
    4.4,
    4.2,
    3.7,
  ];

  final _deptList = [
    _DeptItem(name: '张三', visits: 22, rating: 4.2),
    _DeptItem(name: '李四', visits: 16, rating: 3.9),
    _DeptItem(name: '王五', visits: 28, rating: 4.5),
    _DeptItem(name: '赵六', visits: 12, rating: 4.0),
    _DeptItem(name: '钱七', visits: 19, rating: 4.3),
  ];

  @override
  void dispose() {
    _customerSearchCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final role = ref.watch(currentRoleProvider);
    final showDetail = role != 'employee';
    final showExport = role == 'finance' || role == 'admin';
    return Stack(
      children: [
        SingleChildScrollView(
          child: Column(
            children: [
              _buildTimeFilter(),
              _buildCustomerSearch(),
              _buildStatCards(),
              _buildChartSection(),
              if (showDetail) _buildDeptListSection(),
              const SizedBox(height: 80),
            ],
          ),
        ),
        if (showExport)
          Positioned(
            right: 16,
            bottom: 16,
            child: 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),
            ),
          ),
      ],
    );
  }

  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 _buildCustomerSearch() {
    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: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        decoration: BoxDecoration(
          color: colors.bgPage,
          borderRadius: BorderRadius.circular(18),
          border: Border.all(color: colors.border),
        ),
        child: Row(
          children: [
            Icon(Icons.search, size: 18, color: colors.textPlaceholder),
            const SizedBox(width: 6),
            Expanded(
              child: TextField(
                controller: _customerSearchCtrl,
                decoration: InputDecoration(
                  hintText: '${l10n.get('searchByNameOrId')}...',
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: colors.textPlaceholder,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 10),
                  isDense: true,
                ),
                style: TextStyle(fontSize: 14, color: colors.textPrimary),
                onChanged: (v) => setState(() {}),
              ),
            ),
            if (_customerSearchCtrl.text.isNotEmpty)
              GestureDetector(
                onTap: () {
                  _customerSearchCtrl.clear();
                  setState(() {});
                },
                child: Icon(
                  Icons.clear,
                  size: 16,
                  color: colors.textPlaceholder,
                ),
              ),
          ],
        ),
      ),
    );
  }

  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('statMonthVisits'),
                  '177 次',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statVisitedCustomers'),
                  '38 家',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statAvgRating'),
                  '4.2',
                  colors.warning,
                  showStar: true,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statNotReviewed'),
                  '15 篇',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _statCard(
    String label,
    String value,
    Color valueColor, {
    bool showStar = false,
  }) {
    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: [
          _buildValueWithStar(value, valueColor, showStar),
          const SizedBox(height: 4),
          Text(
            label,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 12, color: colors.textSecondary),
          ),
        ],
      ),
    );
  }

  // ── 图表 ──
  Widget _buildValueWithStar(String value, Color valueColor, bool showStar) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return LayoutBuilder(
      builder: (context, constraints) {
        final style = TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w700,
          color: valueColor,
        );
        // 计算星标占用宽度
        const starWidth = 16.0 + 2.0; // icon + SizedBox
        final availableWidth = constraints.maxWidth;
        final tp = TextPainter(
          text: TextSpan(text: value, style: style),
          textDirection: TextDirection.ltr,
          textScaler: MediaQuery.textScalerOf(context),
          maxLines: 1,
        )..layout();
        final totalWidth = tp.width + (showStar ? starWidth : 0);
        if (totalWidth > availableWidth) {
          return SizedBox(
            height: tp.height,
            child: Marquee(
              text: value,
              style: style,
              scrollAxis: Axis.horizontal,
              blankSpace: 40,
              velocity: 30,
              pauseAfterRound: const Duration(seconds: 1),
              startPadding: 0,
            ),
          );
        }
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (showStar) ...[
              Icon(Icons.star, size: 16, color: colors.warning),
              const SizedBox(width: 2),
            ],
            Text(value, softWrap: false, style: style),
          ],
        );
      },
    );
  }

  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('chartDeptOutingCompare')
        : l10n.get('chartTitle5');
    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('statMonthVisits')),
                const SizedBox(width: 16),
                _legendDot(colors.warning, l10n.get('statAvgRating')),
              ],
            ),
            const SizedBox(height: 12),
            SizedBox(
              height: 200,
              child: isManager ? _buildDeptBarChart() : _buildDualAxisChart(),
            ),
          ],
        ),
      ),
    );
  }

  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 _buildDualAxisChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: false,
          horizontalInterval: 5,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            axisNameWidget: Text(
              l10n.get('statMonthVisits'),
              style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
            ),
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 32,
              interval: 5,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}',
                style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
              ),
            ),
          ),
          rightTitles: AxisTitles(
            axisNameWidget: Text(
              l10n.get('statAvgRating'),
              style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
            ),
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 32,
              getTitlesWidget: (v, meta) => Text(
                v.toStringAsFixed(1),
                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),
          ),
        ),
        borderData: FlBorderData(show: false),
        minY: 0,
        maxY: 25,
        clipData: const FlClipData.all(),
        lineTouchData: LineTouchData(
          enabled: true,
          touchTooltipData: LineTouchTooltipData(
            getTooltipItems: (spots) => spots.map((s) {
              final label = s.barIndex == 0
                  ? '${s.y.toInt()}次'
                  : '${s.y.toStringAsFixed(1)}分';
              return LineTooltipItem(
                '${_months[s.spotIndex]} $label',
                const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              );
            }).toList(),
          ),
        ),
        lineBarsData: [
          // 拜访次数 - 左轴
          LineChartBarData(
            spots: List.generate(
              12,
              (i) => FlSpot(i.toDouble(), _visitCounts[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(), _avgRatings[i] * 5),
            ),
            isCurved: true,
            color: colors.warning,
            barWidth: 2.5,
            dotData: FlDotData(
              show: true,
              getDotPainter: (spot, percent, barData, index) =>
                  FlDotCirclePainter(
                    radius: 3,
                    color: colors.warning,
                    strokeWidth: 0,
                  ),
            ),
            belowBarData: BarAreaData(
              show: true,
              color: colors.warning.withValues(alpha: 0.08),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeptBarChart() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return BarChart(
      BarChartData(
        maxY: 35,
        barTouchData: BarTouchData(
          enabled: true,
          touchTooltipData: BarTouchTooltipData(
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final item = _deptList[group.x.toInt()];
              final prefix = rodIndex == 0
                  ? '${rod.toY.toInt()}次'
                  : '${rod.toY.toStringAsFixed(1)}分';
              return BarTooltipItem(
                '${item.name}\n$prefix',
                const TextStyle(color: Colors.white, fontSize: 12),
              );
            },
          ),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 36,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}',
                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: 10,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        barGroups: List.generate(_deptList.length, (i) {
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: _deptList[i].visits.toDouble(),
                color: colors.primary,
                width: 12,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(3),
                ),
              ),
              BarChartRodData(
                toY: _deptList[i].rating * 5,
                color: colors.warning,
                width: 12,
                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('statMonthVisits'),
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: colors.textSecondary,
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      l10n.get('statAvgRating'),
                      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.visits} 次',
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.star, size: 12, color: colors.warning),
                          const SizedBox(width: 2),
                          Text(
                            d.rating.toStringAsFixed(1),
                            style: TextStyle(
                              fontSize: 13,
                              color: colors.textPrimary,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}

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