import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../router/router.dart';
import 'scanner_cubit.dart';
import 'scanner_state.dart';

class ScannerScreen extends StatefulWidget {
  const ScannerScreen({super.key});

  @override
  State<ScannerScreen> createState() => _ScannerScreenState();
}

class _ScannerScreenState extends State<ScannerScreen> {
  final MobileScannerController _controller = MobileScannerController();
  bool _isProcessing = false;

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

  void _onBarcodeDetected(BarcodeCapture capture) {
    if (_isProcessing) return;
    final barcode = capture.barcodes.firstOrNull;
    if (barcode == null || barcode.rawValue == null) return;

    _isProcessing = true;
    _controller.stop();
    context.read<ScannerCubit>().scanBarcode(barcode.rawValue!);
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<ScannerCubit, ScannerState>(
      listener: (context, state) {
        if (state.item != null && !state.isLoading) {
          ItemDetailRouteData(barcode: state.item!.barcode).push(context);
          context.read<ScannerCubit>().reset();
          _isProcessing = false;
          _controller.start();
        } else if (state.errorMessage != null && !state.isLoading) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(state.errorMessage!)),
          );
          context.read<ScannerCubit>().reset();
          _isProcessing = false;
          _controller.start();
        }
      },
      child: Scaffold(
        appBar: AppBar(title: const Text('Scan Barcode')),
        body: Stack(
          children: [
            MobileScanner(
              controller: _controller,
              onDetect: _onBarcodeDetected,
            ),
            Center(
              child: Container(
                width: 280,
                height: 160,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: _isProcessing ? Colors.orange : Colors.white,
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
            BlocBuilder<ScannerCubit, ScannerState>(
              builder: (context, state) {
                if (state.isLoading) {
                  return const Center(child: CircularProgressIndicator());
                }
                return const SizedBox.shrink();
              },
            ),
            Positioned(
              bottom: 40,
              left: 0,
              right: 0,
              child: BlocBuilder<ScannerCubit, ScannerState>(
                builder: (context, state) {
                  return Text(
                    state.isLoading
                        ? 'Looking up product...'
                        : 'Point camera at a barcode',
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      shadows: [Shadow(blurRadius: 8, color: Colors.black)],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}