import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart'; import '../../../app/app_services.dart'; import '../../../app/router/app_router.dart'; import '../../../core/utils/currency_formatter.dart'; import '../../../core/widgets/empty_view.dart'; import '../../../core/widgets/error_view.dart'; import '../../../core/widgets/loading_view.dart'; import '../../../domain/entities/department.dart'; import '../../../domain/entities/product.dart'; import '../../../domain/entities/sale_view_mode.dart'; import '../../../domain/repositories/catalog_repository.dart'; class SaleScreen extends StatefulWidget { const SaleScreen({required this.services, super.key}); final AppServices services; @override State createState() => _SaleScreenState(); } class _SaleScreenState extends State { final Map> _productsByDepartment = {}; List _departments = []; int? _selectedDepartmentId; bool _loadingDepartments = true; bool _loadingProducts = false; bool _showKanban = true; bool _scanningBarcode = false; String? _departmentError; String? _productError; int _productRequest = 0; @override void initState() { super.initState(); _initialize(); } Future _initialize() async { final userId = widget.services.authRepository.currentSession?.userId; if (userId != null) { try { final viewMode = await widget.services.saleViewPreferenceRepository .loadForUser(userId); if (mounted) { setState(() => _showKanban = viewMode == SaleViewMode.kanban); } } catch (_) { // Use Kanban as the default if preference storage is unavailable. } } if (mounted) await _loadDepartments(); } Future _setViewMode(bool showKanban) async { setState(() => _showKanban = showKanban); final userId = widget.services.authRepository.currentSession?.userId; if (userId == null) return; try { await widget.services.saleViewPreferenceRepository.saveForUser( userId, showKanban ? SaleViewMode.kanban : SaleViewMode.list, ); } catch (_) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Não foi possível salvar a visualização.')), ); } } } Future _loadDepartments() async { setState(() { _loadingDepartments = true; _departmentError = null; }); try { final departments = await widget.services.catalogRepository.fetchDepartments(); if (!mounted) return; setState(() { _departments = departments; _selectedDepartmentId = departments.isEmpty ? null : departments.first.id; _loadingDepartments = false; }); if (departments.isNotEmpty) { await _selectDepartment(departments.first); } } on CatalogException catch (error) { if (mounted) { setState(() { _departmentError = error.message; _loadingDepartments = false; }); } } catch (_) { if (mounted) { setState(() { _departmentError = 'Não foi possível carregar os departamentos.'; _loadingDepartments = false; }); } } } Future _selectDepartment(Department department) async { setState(() { _selectedDepartmentId = department.id; _productError = null; _loadingProducts = !_productsByDepartment.containsKey(department.id); }); if (_productsByDepartment.containsKey(department.id)) return; final requestId = ++_productRequest; try { final products = await widget.services.catalogRepository .fetchProductsByDepartment(department.id); if (!mounted || requestId != _productRequest) return; setState(() { _productsByDepartment[department.id] = products; _loadingProducts = false; }); } on CatalogException catch (error) { if (mounted && requestId == _productRequest) { setState(() { _productError = error.message; _loadingProducts = false; }); } } catch (_) { if (mounted && requestId == _productRequest) { setState(() { _productError = 'Não foi possível carregar os produtos.'; _loadingProducts = false; }); } } } Future _retryProducts() async { final selectedId = _selectedDepartmentId; if (selectedId == null) return; _productsByDepartment.remove(selectedId); final department = _departments.firstWhere((item) => item.id == selectedId); await _selectDepartment(department); } void _addProduct(Product product) { widget.services.cartRepository.addProduct(product); ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar(SnackBar(content: Text('${product.name} adicionado.'))); } Future _scanProductBarcode() async { if (_scanningBarcode) return; setState(() => _scanningBarcode = true); try { final barcode = await FlutterBarcodeScanner.scanBarcode( '#ff6666', 'Cancelar', true, ScanMode.BARCODE, ); if (!mounted || barcode == '-1' || barcode.trim().isEmpty) return; final product = await widget.services.catalogRepository .fetchProductByBarcode(barcode.trim()); if (!mounted) return; if (product == null) { await showDialog( context: context, builder: (dialogContext) => AlertDialog( title: const Text('Produto não encontrado'), content: Text('O código "$barcode" não foi encontrado.'), actions: [ TextButton( onPressed: () => Navigator.of(dialogContext).pop(), child: const Text('Ok'), ), ], ), ); return; } _addProduct(product); } on PlatformException { if (mounted) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( const SnackBar(content: Text('Não foi possível abrir a câmera.')), ); } } on CatalogException catch (error) { if (mounted) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar(SnackBar(content: Text(error.message))); } } catch (_) { if (mounted) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( const SnackBar( content: Text('Não foi possível consultar o código lido.'), ), ); } } finally { if (mounted) setState(() => _scanningBarcode = false); } } String get _selectedDepartmentName { for (final department in _departments) { if (department.id == _selectedDepartmentId) return department.name; } return ''; } Widget _productImage( Product product, { double? width, double? height, BoxFit fit = BoxFit.cover, }) { final encodedImage = product.imageBase64; if (encodedImage == null) return _imagePlaceholder(width, height); try { return Image.memory( base64Decode(encodedImage), width: width, height: height, fit: fit, errorBuilder: (_, __, ___) => _imagePlaceholder(width, height), ); } on FormatException { return _imagePlaceholder(width, height); } } Widget _imagePlaceholder(double? width, double? height) { return Container( width: width, height: height, color: Theme.of(context).colorScheme.surfaceVariant, alignment: Alignment.center, child: const Icon(Icons.image_outlined, size: 36), ); } Widget _buildProductCard(Product product, {required bool grid}) { if (grid) { return Card( clipBehavior: Clip.antiAlias, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: ColoredBox( color: Theme.of(context).colorScheme.surfaceVariant, child: _productImage(product, fit: BoxFit.contain), ), ), Padding( padding: const EdgeInsets.fromLTRB(6, 6, 6, 2), child: Text( product.name, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 6), child: Text( product.code, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall, ), ), Padding( padding: const EdgeInsets.fromLTRB(4, 2, 4, 0), child: FittedBox( fit: BoxFit.scaleDown, child: Text( CurrencyFormatter.formatBrl(product.priceMinorUnits), style: Theme.of(context) .textTheme .labelLarge ?.copyWith(fontWeight: FontWeight.bold), ), ), ), Align( alignment: Alignment.center, child: IconButton.filledTonal( constraints: const BoxConstraints.tightFor(width: 38, height: 38), padding: EdgeInsets.zero, tooltip: 'Adicionar ${product.name}', onPressed: () => _addProduct(product), icon: const Icon(Icons.add_shopping_cart, size: 18), ), ), ], ), ); } return Card( clipBehavior: Clip.antiAlias, child: ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), leading: SizedBox.square( dimension: 64, child: ClipRRect( borderRadius: BorderRadius.circular(8), child: _productImage(product), ), ), title: Text( product.name, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall, ), subtitle: Text( 'Código ${product.code} · ' '${CurrencyFormatter.formatBrl(product.priceMinorUnits)}', style: Theme.of(context) .textTheme .bodySmall ?.copyWith(fontWeight: FontWeight.bold), ), trailing: IconButton.filledTonal( tooltip: 'Adicionar ${product.name}', onPressed: () => _addProduct(product), icon: const Icon(Icons.add_shopping_cart), ), ), ); } Widget _buildProducts() { if (_loadingProducts) { return const LoadingView(message: 'Carregando produtos...'); } if (_productError != null) { return ErrorView(message: _productError!, onRetry: _retryProducts); } final products = _productsByDepartment[_selectedDepartmentId] ?? []; if (products.isEmpty) { return const EmptyView( title: 'Nenhum produto', message: 'Não há produtos neste departamento.', icon: Icons.inventory_2_outlined, ); } if (!_showKanban) { return ListView.builder( padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), itemCount: products.length, itemBuilder: (_, index) => _buildProductCard(products[index], grid: false), ); } return LayoutBuilder( builder: (context, constraints) { final tileWidth = (constraints.maxWidth - 44) / 3; // Reserve at least 64 px for the image, matching the list thumbnail. final tileHeight = math.max(196.0, tileWidth / 0.9); return GridView.builder( padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, crossAxisSpacing: 10, mainAxisSpacing: 10, childAspectRatio: tileWidth / tileHeight, ), itemCount: products.length, itemBuilder: (_, index) => _buildProductCard(products[index], grid: true), ); }, ); } Widget _buildCartBar() { return AnimatedBuilder( animation: widget.services.cartRepository, builder: (context, _) { final itemCount = widget.services.cartRepository.itemCount; final totalMinorUnits = widget.services.cartRepository.totalMinorUnits; return Material( elevation: 4, color: Theme.of(context).colorScheme.surface, child: SafeArea( top: false, child: Padding( padding: const EdgeInsets.all(12), child: Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( 'Total do carrinho', style: Theme.of(context).textTheme.bodySmall, ), Text( totalMinorUnits == null ? 'Total indisponível' : CurrencyFormatter.formatBrl(totalMinorUnits), style: Theme.of(context) .textTheme .titleMedium ?.copyWith(fontWeight: FontWeight.bold), ), ], ), ), SizedBox.square( dimension: 56, child: Stack( clipBehavior: Clip.none, children: [ Positioned.fill( child: IconButton.filledTonal( tooltip: 'Carrinho', onPressed: itemCount == 0 ? null : () => Navigator.of(context) .pushNamed(AppRoutes.cart), icon: const Icon(Icons.shopping_cart_outlined), ), ), if (itemCount > 0) Positioned( top: -2, right: -2, child: Container( constraints: const BoxConstraints( minWidth: 20, minHeight: 20, ), padding: const EdgeInsets.symmetric(horizontal: 5), decoration: BoxDecoration( color: Theme.of(context).colorScheme.error, borderRadius: BorderRadius.circular(10), ), alignment: Alignment.center, child: Text( itemCount > 99 ? '99+' : '$itemCount', style: TextStyle( color: Theme.of(context).colorScheme.onError, fontSize: 11, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Venda'), actions: [ IconButton( key: const Key('refresh-products-button'), tooltip: 'Atualizar produtos', onPressed: _loadingProducts || _selectedDepartmentId == null ? null : _retryProducts, icon: const Icon(Icons.refresh), ), ], ), body: SafeArea( child: Column( children: [ if (_loadingDepartments) const Expanded( child: LoadingView(message: 'Carregando departamentos...'), ) else if (_departmentError != null) Expanded( child: ErrorView( message: _departmentError!, onRetry: _loadDepartments, ), ) else if (_departments.isEmpty) const Expanded( child: EmptyView( title: 'Nenhum departamento', message: 'O servidor não retornou departamentos para venda.', icon: Icons.category_outlined, ), ) else ...[ SizedBox( height: 58, child: ListView.separated( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), scrollDirection: Axis.horizontal, itemCount: _departments.length, separatorBuilder: (_, __) => const SizedBox(width: 8), itemBuilder: (context, index) { final department = _departments[index]; return ChoiceChip( label: Text(department.name), selected: department.id == _selectedDepartmentId, onSelected: (_) => _selectDepartment(department), ); }, ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 0, 8, 8), child: Row( children: [ Expanded( child: Text( _selectedDepartmentName, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleMedium, ), ), IconButton.filledTonal( tooltip: 'Ler código de barras', onPressed: _scanningBarcode ? null : _scanProductBarcode, icon: _scanningBarcode ? SizedBox.square( dimension: 20, child: CircularProgressIndicator( strokeWidth: 2, color: Theme.of(context) .colorScheme .onSecondaryContainer, ), ) : const Icon(Icons.camera_alt_outlined), ), const SizedBox(width: 20), IconButton( tooltip: _showKanban ? 'Visualizar em lista' : 'Visualizar em Kanban', onPressed: () => _setViewMode(!_showKanban), icon: Icon( _showKanban ? Icons.view_list : Icons.grid_view, ), ), ], ), ), Expanded(child: _buildProducts()), ], ], ), ), bottomNavigationBar: _buildCartBar(), ); } }