import 'package:flutter/material.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';
import 'package:marquee/marquee.dart';
import '../../core/utils/amount_utils.dart';

/// 用车明细报表 - 页面25

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

class _VehicleDetailReportPageState
    extends ConsumerState<VehicleDetailReportPage> {
  int _timeFilterIdx = 0;
  DateTime? _customStart;
  DateTime? _customEnd;
  int _vehicleFilterIdx = 0;
  // 车牌号为 mock 数据，不需要翻译
  static const _vehiclePlateFilters = ['京A·88888', '京B·66666', '京C·12345'];
  int _usageFilterIdx = 0;

  static const _months = [
    '1月',
    '2月',
    '3月',
    '4月',
    '5月',
    '6月',
    '7月',
    '8月',
    '9月',
    '10月',
    '11月',
    '12月',
  ];
  // 左轴：次数
  static const _tripCounts = [
    4.0,
    6.0,
    3.0,
    8.0,
    7.0,
    9.0,
    5.0,
    4.0,
    6.0,
    8.0,
    5.0,
    10.0,
  ];
  // 右轴：费用（元）
  static const _tripCosts = [
    800.0,
    1200.0,
    600.0,
    1600.0,
    1400.0,
    2000.0,
    1000.0,
    750.0,
    1300.0,
    1700.0,
    900.0,
    2200.0,
  ];

  final _deptList = [
    _DeptItem(name: '张三', trips: 10, cost: 2200),
    _DeptItem(name: '李四', trips: 7, cost: 1500),
    _DeptItem(name: '王五', trips: 12, cost: 2800),
    _DeptItem(name: '赵六', trips: 5, cost: 1100),
    _DeptItem(name: '钱七', trips: 8, cost: 1800),
  ];

  @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(),
              _buildExtraFilters(),
              _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 _buildExtraFilters() {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final vehicleLabels = [l10n.get('filterAll'), ..._vehiclePlateFilters];
    final usageLabels = [
      l10n.get('filterAll'),
      l10n.get('filterReception'),
      l10n.get('businessShort'),
      l10n.get('official'),
    ];
    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('filterVehicle')}：',
                style: TextStyle(fontSize: 13, color: colors.textSecondary),
              ),
              const SizedBox(width: 4),
              ...List.generate(
                vehicleLabels.length > 3 ? 3 : vehicleLabels.length,
                (i) {
                  final sel = i == _vehicleFilterIdx;
                  return Padding(
                    padding: const EdgeInsets.only(right: 6),
                    child: GestureDetector(
                      onTap: () => setState(() => _vehicleFilterIdx = 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(
                          vehicleLabels[i],
                          style: TextStyle(
                            fontSize: 12,
                            color: sel ? colors.primary : colors.textSecondary,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
          const SizedBox(height: 6),
          Row(
            children: [
              Text(
                '${l10n.get('filterUsage')}：',
                style: TextStyle(fontSize: 13, color: colors.textSecondary),
              ),
              const SizedBox(width: 4),
              ...List.generate(usageLabels.length, (i) {
                final sel = i == _usageFilterIdx;
                return Padding(
                  padding: const EdgeInsets.only(right: 6),
                  child: GestureDetector(
                    onTap: () => setState(() => _usageFilterIdx = 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(
                        usageLabels[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('statMonthTrips'),
                  '75 次',
                  colors.textPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statTotalMileage'),
                  '18,560km',
                  colors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _statCard(
                  l10n.get('statTotalCost'),
                  formatAmount(16450.0),
                  colors.amountPrimary,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _statCard(
                  l10n.get('statNotReturned'),
                  '2 辆',
                  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: [
          _buildValue(value, valueColor),
          const SizedBox(height: 4),
          Text(
            label,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 12, color: colors.textSecondary),
          ),
        ],
      ),
    );
  }

  // ── 图表：双轴折线 ──
  Widget _buildValue(String value, Color valueColor) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final style = TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w700,
          color: valueColor,
        );
        final tp = TextPainter(
          text: TextSpan(text: value, style: style),
          textDirection: TextDirection.ltr,
          textScaler: MediaQuery.textScalerOf(context),
          maxLines: 1,
        )..layout();
        if (tp.width > constraints.maxWidth) {
          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 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('chartDeptVehicleCompare')
        : l10n.get('chartTitle3');
    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('statMonthTrips')),
                const SizedBox(width: 16),
                _legendDot(colors.warning, l10n.get('totalCost')),
              ],
            ),
            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: 2,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        titlesData: FlTitlesData(
          leftTitles: AxisTitles(
            axisNameWidget: Text(
              l10n.get('statMonthTrips'),
              style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
            ),
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 32,
              interval: 2,
              getTitlesWidget: (v, meta) => Text(
                '${v.toInt()}',
                style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
              ),
            ),
          ),
          rightTitles: AxisTitles(
            axisNameWidget: Text(
              l10n.get('totalCost'),
              style: TextStyle(fontSize: 10, color: colors.textPlaceholder),
            ),
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 40,
              interval: 500,
              getTitlesWidget: (v, meta) => Text(
                formatAmount(v.toDouble()),
                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: 12,
        clipData: const FlClipData.all(),
        lineTouchData: LineTouchData(
          enabled: true,
          touchTooltipData: LineTouchTooltipData(
            getTooltipItems: (spots) => spots.map((s) {
              final label = s.barIndex == 0
                  ? '${s.y.toInt()}次'
                  : '${formatAmount(s.y)}';
              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(), _tripCounts[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(), _tripCosts[i] / 500),
            ),
            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: 15,
        barTouchData: BarTouchData(
          enabled: true,
          touchTooltipData: BarTouchTooltipData(
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              final item = _deptList[group.x.toInt()];
              final prefix = rodIndex == 0
                  ? '${rod.toY.toInt()}次'
                  : '${formatAmount(rod.toY)}';
              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: 5,
          getDrawingHorizontalLine: (v) =>
              FlLine(color: colors.border, strokeWidth: 0.5),
        ),
        barGroups: List.generate(_deptList.length, (i) {
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: _deptList[i].trips.toDouble(),
                color: colors.primary,
                width: 12,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(3),
                ),
              ),
              BarChartRodData(
                toY: _deptList[i].cost.toDouble() / 500,
                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('statMonthTrips'),
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: colors.textSecondary,
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      l10n.get('totalCost'),
                      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.trips} 次',
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Text(
                        formatAmount(d.cost.toDouble()),
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          fontSize: 13,
                          color: colors.textPrimary,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}

class _DeptItem {
  final String name;
  final int trips;
  final int cost;
  const _DeptItem({
    required this.name,
    required this.trips,
    required this.cost,
  });
}
