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

/// VS Page - Verwahrungsstelle
/// Entspricht Lua: ShowVsScreen + CreateLoadingVsView
/// Spezial: Container-Handling für SB (Safebag) und ABS (Abfallbehälter)
class VsPage extends StatefulWidget {
  final Tour tour;

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

  @override
  State<VsPage> createState() => _VsPageState();
}

class _VsPageState extends State<VsPage> {
  String? selectedContainerId;
  String? selectedContainerType; // 'a' = GI, 'b' = DS

  @override
  void initState() {
    super.initState();
    context.read<ScanBloc>().add(InitializeScan(widget.tour));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(widget.tour.locationName ?? 'Verwahrungsstelle'),
            const Text(
              'Container-Annahme',
              style: TextStyle(fontSize: 14, color: Colors.white70),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.qr_code_scanner),
            onPressed: () => _openScanner(context),
          ),
        ],
      ),
      body: Column(
        children: [
          // Header
          _buildHeader(context),
          
          // Container-Auswahl
          _buildContainerSelection(context),
          
          // Aktueller Container Status
          if (selectedContainerId != null)
            _buildContainerStatus(context),
          
          const Spacer(),
          
          // Scan Button
          _buildScanButton(context),
        ],
      ),
    );
  }

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

  Widget _buildContainerSelection(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Container auswählen',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          
          // Container A - Geldinstitut
          _buildContainerOption(
            context,
            id: 'CONT_A',
            type: 'a',
            title: 'Container A',
            subtitle: 'Für Geldinstitut (GI)',
            icon: Icons.account_balance,
            color: Colors.blue,
          ),
          
          const SizedBox(height: 8),
          
          // Container B - Dienststelle
          _buildContainerOption(
            context,
            id: 'CONT_B',
            type: 'b',
            title: 'Container B',
            subtitle: 'Für Dienststelle (DS)',
            icon: Icons.business,
            color: Colors.orange,
          ),
        ],
      ),
    );
  }

  Widget _buildContainerOption(
    BuildContext context, {
    required String id,
    required String type,
    required String title,
    required String subtitle,
    required IconData icon,
    required Color color,
  }) {
    final isSelected = selectedContainerId == id;
    
    return InkWell(
      onTap: () {
        setState(() {
          selectedContainerId = id;
          selectedContainerType = type;
        });
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isSelected ? color.withValues(alpha: 20) : Colors.white,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected ? color : Colors.grey.shade300,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: color.withValues(alpha: 26),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(icon, color: color),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                    ),
                  ),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            if (isSelected)
              Icon(Icons.check_circle, color: color),
          ],
        ),
      ),
    );
  }

  Widget _buildContainerStatus(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: selectedContainerType == 'a' 
            ? Colors.blue.shade50 
            : Colors.orange.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: selectedContainerType == 'a' 
              ? Colors.blue 
              : Colors.orange,
        ),
      ),
      child: Column(
        children: [
          Text(
            'Ausgewählt: ${selectedContainerType == 'a' ? 'Container A (GI)' : 'Container B (DS)'}',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: selectedContainerType == 'a' 
                  ? Colors.blue 
                  : Colors.orange,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            'Scannen Sie jetzt SB (Safebag) oder ABS (Abfallbehälter)',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 13),
          ),
        ],
      ),
    );
  }

  Widget _buildScanButton(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          if (selectedContainerId == null)
            const Padding(
              padding: EdgeInsets.only(bottom: 8),
              child: Text(
                'Bitte zuerst einen Container auswählen',
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: 13,
                ),
              ),
            ),
          ElevatedButton.icon(
            onPressed: selectedContainerId != null 
                ? () => _openScanner(context) 
                : null,
            icon: const Icon(Icons.qr_code_scanner),
            label: const Text('Barcode scannen'),
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(double.infinity, 56),
            ),
          ),
        ],
      ),
    );
  }

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