import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../domain/entities/tour.dart';
import '../../blocs/scan/scan_bloc.dart';
import '../../widgets/recent_scans_list.dart';
import '../scan/scan_page.dart';

/// Stock Start Page - Lager Beladung
/// Entspricht Lua: ShowStockStartScreen + CreateLoadingStockStartView
class StockStartPage extends StatefulWidget {
  final Tour tour;

  const StockStartPage({
    super.key,
    required this.tour,
  });

  @override
  State<StockStartPage> createState() => _StockStartPageState();
}

class _StockStartPageState extends State<StockStartPage> {
  @override
  void initState() {
    super.initState();
    // Initialize scan bloc with tour
    context.read<ScanBloc>().add(InitializeScan(widget.tour));
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(widget.tour.locationName ?? 'Lager'),
            Text(
              'Beladung',
              style: theme.textTheme.bodySmall?.copyWith(
                color: Colors.white70,
              ),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.qr_code_scanner),
            onPressed: () => _openScanner(context),
          ),
        ],
      ),
      body: Column(
        children: [
          // Header mit Lager-Icon
          _buildHeader(context),
          
          // Zähler-Übersicht (wie in Lua CreateLoadingStockStartView)
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // Bestand Fzg (aktueller Bestand im Fahrzeug)
                  _buildCounterSection(
                    context,
                    title: 'Bestand Fzg',
                    counters: const [
                      CounterItem('MEK', 0),
                      CounterItem('BEK', 0),
                      CounterItem('H1', 0),
                      CounterItem('H2', 0),
                      CounterItem('H3', 0),
                      CounterItem('P', 0),
                    ],
                    backgroundColor: const Color(0xFFA4D4F0), // Lua-Farbe
                  ),
                  
                  // Beladezähler (Soll-Zahlen)
                  _buildCounterSection(
                    context,
                    title: 'Beladezähler',
                    counters: const [
                      CounterItem('MEK', 0),
                      CounterItem('BEK', 0),
                      CounterItem('H1', 0),
                      CounterItem('H2', 0),
                      CounterItem('H3', 0),
                      CounterItem('P', 0),
                    ],
                    backgroundColor: Colors.grey.shade200,
                  ),
                  
                  // HADAG
                  _buildCounterSection(
                    context,
                    title: 'HADAG',
                    counters: const [
                      CounterItem('', null),
                      CounterItem('BEK-B', 0),
                      CounterItem('H1-B', 0),
                      CounterItem('H2-B', 0),
                      CounterItem('', null),
                      CounterItem('', null),
                    ],
                    backgroundColor: Colors.grey.shade200,
                  ),
                  
                  // SST (Schnellbahn)
                  _buildCounterSection(
                    context,
                    title: 'SST',
                    counters: const [
                      CounterItem('MEK-SST', 0),
                      CounterItem('BEK-SST', 0),
                      CounterItem('H1-SST', 0),
                      CounterItem('H2-SST', 0),
                      CounterItem('', null),
                      CounterItem('', null),
                    ],
                    backgroundColor: Colors.grey.shade200,
                  ),
                  
                  // CR (CityRail)
                  _buildCounterSection(
                    context,
                    title: 'CR',
                    counters: const [
                      CounterItem('MEK-CR', 0),
                      CounterItem('BEK-CR', 0),
                      CounterItem('', null),
                      CounterItem('', null),
                      CounterItem('', null),
                      CounterItem('', null),
                    ],
                    backgroundColor: Colors.grey.shade200,
                  ),
                  
                  // Zuletzt gescannte Objekte
                  const Padding(
                    padding: EdgeInsets.all(16),
                    child: RecentScansList(),
                  ),
                ],
              ),
            ),
          ),
          
          // Scan Button
          _buildScanButton(context),
        ],
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      color: const Color(0xFFA4D4F0), // Hellblau wie in Lua
      child: Row(
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(
              Icons.warehouse,
              size: 48,
              color: Colors.blue,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Lager Beladung',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  widget.tour.locationName ?? 'Hauptlager',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCounterSection(
    BuildContext context, {
    required String title,
    required List<CounterItem> counters,
    required Color backgroundColor,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          // Titel
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Text(
              title,
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ),
          
          // Zähler-Grid
          Container(
            padding: const EdgeInsets.all(8),
            child: Row(
              children: counters.map((counter) {
                return Expanded(
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 2),
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    decoration: BoxDecoration(
                      color: counter.value == null ? Colors.transparent : Colors.white,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Column(
                      children: [
                        Text(
                          counter.label,
                          style: TextStyle(
                            fontSize: 11,
                            fontWeight: FontWeight.w500,
                            color: counter.value == null ? Colors.transparent : Colors.black87,
                          ),
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        if (counter.value != null) ...[
                          const SizedBox(height: 4),
                          Text(
                            '${counter.value}',
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildScanButton(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 10),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: ElevatedButton.icon(
          onPressed: () => _openScanner(context),
          icon: const Icon(Icons.qr_code_scanner),
          label: const Text(
            'Barcode scannen',
            style: TextStyle(fontSize: 16),
          ),
          style: ElevatedButton.styleFrom(
            minimumSize: const Size(double.infinity, 56),
          ),
        ),
      ),
    );
  }

  void _openScanner(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => ScanPage(tour: widget.tour),
      ),
    );
  }
}

/// Hilfsklasse für Zähler-Darstellung
class CounterItem {
  final String label;
  final int? value;

  const CounterItem(this.label, this.value);
}
