import 'dart:io';
import 'package:flutter/material.dart';
import '../services/database_helper.dart';
import '../models/palm_record.dart';
import '../models/palm_correction.dart';
import '../constants/mpob_colors.dart';
import '../theme/app_theme.dart';
import '../services/app_strings.dart';
import '../theme/locale_controller.dart';
import 'record_detail_screen.dart';

class BatchReportScreen extends StatefulWidget {
  final String batchId;
  const BatchReportScreen({super.key, required this.batchId});

  @override
  State<BatchReportScreen> createState() => _BatchReportScreenState();
}

class _BatchReportScreenState extends State<BatchReportScreen> {
  final DatabaseHelper _dbHelper = DatabaseHelper();
  List<PalmRecord> _records = [];
  Map<int, PalmCorrection> _latestCorrections = {};
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    final records = await _dbHelper.getRecordsByBatch(widget.batchId);
    final corrections = <int, PalmCorrection>{};
    for (final record in records) {
      if (record.id == null) continue;
      final correction = await _dbHelper.getLatestCorrection(record.id!);
      if (correction != null) corrections[record.id!] = correction;
    }
    setState(() {
      _records = records;
      _latestCorrections = corrections;
      _isLoading = false;
    });
  }

  /// Per photo: use the harvester's correction if one exists, else fall
  /// back to the AI's own detections. Never mutates either source list.
  List<Map<String, dynamic>> _detectionsFor(PalmRecord record) {
    final correction = record.id == null ? null : _latestCorrections[record.id];
    return correction?.correctedDetections ?? record.detections;
  }

  int get _correctedFrameCount => _records.where((r) => r.id != null && _latestCorrections.containsKey(r.id)).length;

  Map<String, int> get _correctedClassTally {
    final tally = <String, int>{};
    for (final record in _records) {
      for (final d in _detectionsFor(record)) {
        final className = (d['className'] ?? d['class'] ?? 'Unknown').toString();
        tally[className] = (tally[className] ?? 0) + 1;
      }
    }
    return tally;
  }

  int get _totalDetections => _records.fold(0, (sum, r) => sum + r.detections.length);

  double get _avgConfidence =>
      _records.isEmpty ? 0 : _records.map((r) => r.confidence).reduce((a, b) => a + b) / _records.length;

  double? get _avgInferenceMs {
    final withTiming = _records.where((r) => r.inferenceMs != null).toList();
    if (withTiming.isEmpty) return null;
    return withTiming.map((r) => r.inferenceMs!).reduce((a, b) => a + b) / withTiming.length;
  }

  Map<String, int> get _classTally {
    final tally = <String, int>{};
    for (final record in _records) {
      for (final d in record.detections) {
        final className = (d['className'] ?? d['class'] ?? 'Unknown').toString();
        tally[className] = (tally[className] ?? 0) + 1;
      }
    }
    return tally;
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<String>(
      valueListenable: LocaleController.localeCode,
      builder: (context, _, _) => _buildScaffold(context),
    );
  }

  Widget _buildScaffold(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    if (_isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    if (_records.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: Text(AppStrings.t('batch_report_title'))),
        body: Center(child: Text(AppStrings.t('batch_no_records'))),
      );
    }

    final start = _records.first.timestamp;
    final end = _records.last.timestamp;
    final tally = _classTally;
    final totalTally = tally.values.fold(0, (a, b) => a + b);

    return Scaffold(
      appBar: AppBar(title: Text(AppStrings.t('batch_report_title'))),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          _buildKpiGrid(start, end, colorScheme),
          const SizedBox(height: 24),
          Text(AppStrings.t('mpob_class_distribution_title'), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface)),
          const SizedBox(height: 4),
          Text(AppStrings.t('ai_result_label'), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colorScheme.onSurface.withValues(alpha: 0.6))),
          const SizedBox(height: 8),
          if (totalTally == 0)
            Text(AppStrings.t('no_detections_in_batch'), style: TextStyle(color: colorScheme.onSurface.withValues(alpha: 0.6)))
          else ...[
            _buildTallyBar(tally, totalTally),
            const SizedBox(height: 12),
            _buildTallyLegend(tally, totalTally),
          ],
          if (_correctedFrameCount > 0) ...[
            const SizedBox(height: 24),
            Row(
              children: [
                Text(AppStrings.t('batch_corrected_label'), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colorScheme.onSurface.withValues(alpha: 0.6))),
                const SizedBox(width: 8),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: colorScheme.primary.withValues(alpha: 0.12),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    AppStrings.tp('frames_corrected_pill', {'count': '$_correctedFrameCount', 'total': '${_records.length}'}),
                    style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: colorScheme.primary),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Builder(builder: (context) {
              final correctedTally = _correctedClassTally;
              final correctedTotal = correctedTally.values.fold(0, (a, b) => a + b);
              if (correctedTotal == 0) {
                return Text(AppStrings.t('no_detections_in_batch'), style: TextStyle(color: colorScheme.onSurface.withValues(alpha: 0.6)));
              }
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildTallyBar(correctedTally, correctedTotal),
                  const SizedBox(height: 12),
                  _buildTallyLegend(correctedTally, correctedTotal),
                ],
              );
            }),
          ],
          const SizedBox(height: 24),
          Text(AppStrings.tp('frames_section_title', {'count': '${_records.length}'}), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface)),
          const SizedBox(height: 12),
          _buildFrameGrid(),
        ],
      ),
    );
  }

  Widget _buildKpiGrid(DateTime start, DateTime end, ColorScheme colorScheme) {
    final avgInference = _avgInferenceMs;
    final accents = AppTheme.chartAccents;
    return GridView.count(
      crossAxisCount: 2,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      mainAxisSpacing: 12,
      crossAxisSpacing: 12,
      childAspectRatio: 2.2,
      children: [
        _kpiCard(AppStrings.t('kpi_frames'), "${_records.length}", Icons.photo_library, accents[0], colorScheme),
        _kpiCard(AppStrings.t('kpi_total_detections'), "$_totalDetections", Icons.center_focus_strong, accents[1], colorScheme),
        _kpiCard(AppStrings.t('kpi_avg_confidence'), "${(_avgConfidence * 100).toStringAsFixed(1)}%", Icons.verified, accents[2], colorScheme),
        _kpiCard(
          AppStrings.t('kpi_avg_inference'),
          avgInference == null ? AppStrings.t('na_label') : "${avgInference.toStringAsFixed(0)} ms",
          Icons.speed,
          accents[3],
          colorScheme,
        ),
        _kpiCard(AppStrings.t('kpi_start'), _formatTime(start), Icons.play_circle_outline, accents[4], colorScheme),
        _kpiCard(AppStrings.t('kpi_end'), _formatTime(end), Icons.stop_circle_outlined, accents[4], colorScheme),
      ],
    );
  }

  Widget _kpiCard(String label, String value, IconData icon, Color color, ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: colorScheme.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.2)),
        boxShadow: [BoxShadow(color: color.withValues(alpha: 0.08), blurRadius: 8, offset: const Offset(0, 4))],
      ),
      child: Row(
        children: [
          Icon(icon, color: color, size: 28),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(value, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: colorScheme.onSurface), overflow: TextOverflow.ellipsis),
                Text(label, style: TextStyle(fontSize: 11, color: colorScheme.onSurface.withValues(alpha: 0.6))),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTallyBar(Map<String, int> tally, int total) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8),
      child: SizedBox(
        height: 24,
        child: Row(
          children: mpobClasses.where((c) => (tally[c] ?? 0) > 0).map((className) {
            final count = tally[className]!;
            return Expanded(
              flex: count,
              child: Container(color: getMPOBColor(className)),
            );
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildTallyLegend(Map<String, int> tally, int total) {
    final colorScheme = Theme.of(context).colorScheme;
    return Wrap(
      spacing: 16,
      runSpacing: 8,
      children: mpobClasses.where((c) => (tally[c] ?? 0) > 0).map((className) {
        final count = tally[className]!;
        final pct = (count / total * 100).toStringAsFixed(1);
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(width: 12, height: 12, decoration: BoxDecoration(color: getMPOBColor(className), shape: BoxShape.circle)),
            const SizedBox(width: 6),
            Text("${AppStrings.className(className)}: $count ($pct%)", style: TextStyle(fontSize: 13, color: colorScheme.onSurface)),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildFrameGrid() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
      ),
      itemCount: _records.length,
      itemBuilder: (context, index) {
        final record = _records[index];
        final color = getStatusColor(record.ripenessClass);
        final hasImage = record.imagePath.isNotEmpty && File(record.imagePath).existsSync();

        return GestureDetector(
          onTap: () => Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => RecordDetailScreen(frames: _records, initialIndex: index)),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Stack(
              fit: StackFit.expand,
              children: [
                hasImage
                    ? Image.file(File(record.imagePath), fit: BoxFit.cover)
                    : Container(color: Colors.grey.shade200, child: const Icon(Icons.image, color: Colors.grey)),
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                    color: color.withValues(alpha: 0.85),
                    child: Text(
                      AppStrings.className(record.ripenessClass),
                      style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  String _formatTime(DateTime t) {
    final h = t.hour.toString().padLeft(2, '0');
    final m = t.minute.toString().padLeft(2, '0');
    final s = t.second.toString().padLeft(2, '0');
    return "$h:$m:$s";
  }
}
