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

import '../../../../core/di/providers.dart';
import '../../../../core/router/app_router.dart';
import '../widgets/product_list_item.dart';

/// Products list page
/// Displays products for a specific warehouse with import/export tabs
class ProductsPage extends ConsumerStatefulWidget {
  final int warehouseId;
  final String warehouseName;
  final String operationType;

  const ProductsPage({
    super.key,
    required this.warehouseId,
    required this.warehouseName,
    required this.operationType,
  });

  @override
  ConsumerState<ProductsPage> createState() => _ProductsPageState();
}

class _ProductsPageState extends ConsumerState<ProductsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String _currentOperationType = 'import';
  bool _isTabSwitching = false;

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

    // Initialize tab controller
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: widget.operationType == 'export' ? 1 : 0,
    );

    _currentOperationType = widget.operationType;

    // Listen to tab changes
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        return;
      }

      final newOperationType = _tabController.index == 0 ? 'import' : 'export';
      if (_currentOperationType != newOperationType) {
        setState(() {
          _currentOperationType = newOperationType;
          _isTabSwitching = true; // Mark that tab is switching
        });

        // Load products for new operation type from cache (forceRefresh: false)
        ref.read(productsProvider.notifier).loadProducts(
              widget.warehouseId,
              widget.warehouseName,
              _currentOperationType,
              forceRefresh: false, // Load from cache when switching tabs
            );
      }
    });

    // Load products from cache when page is initialized (forceRefresh: false)
    Future.microtask(() {
      ref.read(productsProvider.notifier).loadProducts(
            widget.warehouseId,
            widget.warehouseName,
            _currentOperationType,
            forceRefresh: false, // Load from cache on initial load
          );
    });
  }

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

  Future<void> _onRefresh() async {
    await ref.read(productsProvider.notifier).refreshProducts();
  }

  void _showBarcodeScanner() {
    final controller = MobileScannerController(
      formats: const [BarcodeFormat.code128],
      facing: CameraFacing.back,
    );

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            // Header
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade900,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(20),
                ),
              ),
              child: Row(
                children: [
                  const Icon(
                    Icons.qr_code_scanner,
                    color: Colors.white,
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      'Quét mã vạch',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white),
                    onPressed: () {
                      controller.dispose();
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
            ),
            // Scanner
            Expanded(
              child: MobileScanner(
                controller: controller,
                onDetect: (capture) {
                  final List<Barcode> barcodes = capture.barcodes;
                  if (barcodes.isNotEmpty) {
                    final barcode = barcodes.first.rawValue;
                    if (barcode != null) {
                      controller.dispose();
                      Navigator.pop(context);
                      _handleScannedBarcode(barcode);
                    }
                  }
                },
              ),
            ),
            // Instructions
            Container(
              padding: const EdgeInsets.all(16),
              color: Colors.grey.shade900,
              child: const Text(
                'Đặt mã vạch Code 128 vào khung để quét',
                style: TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    ).whenComplete(() => controller.dispose());
  }

  void _handleScannedBarcode(String barcode) {
    // Parse barcode to extract productId and optional stageId
    // Format 1: "123" (only productId)
    // Format 2: "123-456" (productId-stageId)

    int? productId;
    int? stageId;

    if (barcode.contains('-')) {
      // Format: productId-stageId
      final parts = barcode.split('-');
      if (parts.length == 2) {
        productId = int.tryParse(parts[0]);
        stageId = int.tryParse(parts[1]);
      }
    } else {
      // Format: productId only
      productId = int.tryParse(barcode);
    }

    if (productId == null) {
      // Invalid barcode format
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Định dạng mã vạch không hợp lệ: "$barcode"'),
          backgroundColor: Colors.red,
          action: SnackBarAction(
            label: 'OK',
            textColor: Colors.white,
            onPressed: () {},
          ),
        ),
      );
      return;
    }

    // Navigate to product detail with productId and optional stageId
    // Use the currently selected tab's operation type
    context.goToProductDetail(
      warehouseId: widget.warehouseId,
      productId: productId,
      warehouseName: widget.warehouseName,
      operationType: _currentOperationType,
      stageId: stageId,
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final textTheme = theme.textTheme;

    // Watch the products state
    final productsState = ref.watch(productsProvider);
    final products = productsState.products;
    final isLoading = productsState.isLoading;
    final error = productsState.error;

    // Listen to products state changes to clear tab switching flag
    ref.listen(productsProvider, (previous, next) {
      // Clear tab switching flag when loading completes
      if (previous?.isLoading == true && next.isLoading == false) {
        if (_isTabSwitching) {
          setState(() {
            _isTabSwitching = false;
          });
        }
      }
    });

    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Sản phẩm',
              style: textTheme.titleMedium,
            ),
            Text(
              widget.warehouseName,
              style: textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _onRefresh,
            tooltip: 'Làm mới',
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(
              icon: Icon(Icons.arrow_downward),
              text: 'Nhập kho',
            ),
            Tab(
              icon: Icon(Icons.arrow_upward),
              text: 'Xuất kho',
            ),
          ],
        ),
      ),
      body: _buildBody(
        isLoading: isLoading,
        error: error,
        products: products,
        theme: theme,
      ),
      floatingActionButton: products.isNotEmpty
          ? FloatingActionButton(
              onPressed: _showBarcodeScanner,
              tooltip: 'Quét mã vạch',
              child: const Icon(Icons.qr_code_scanner),
            )
          : null,
    );
  }

  /// Build the body based on the current state
  Widget _buildBody({
    required bool isLoading,
    required String? error,
    required List products,
    required ThemeData theme,
  }) {
    return Column(
      children: [
        // Info header
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: theme.colorScheme.primaryContainer.withValues(alpha: 0.3),
            border: Border(
              bottom: BorderSide(
                color: theme.colorScheme.outline.withValues(alpha: 0.2),
              ),
            ),
          ),
          child: Row(
            children: [
              Icon(
                _currentOperationType == 'import'
                    ? Icons.arrow_downward
                    : Icons.arrow_upward,
                color: _currentOperationType == 'import'
                    ? Colors.green
                    : Colors.orange,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _currentOperationType == 'import'
                          ? 'Nhập kho'
                          : 'Xuất kho',
                      style: theme.textTheme.titleSmall?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      'Kho: ${widget.warehouseName}',
                      style: theme.textTheme.bodySmall?.copyWith(
                        color: theme.colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),

        // Content area
        Expanded(
          child: _buildContent(
            isLoading: isLoading,
            error: error,
            products: products,
            theme: theme,
          ),
        ),
      ],
    );
  }

  /// Build content based on state
  Widget _buildContent({
    required bool isLoading,
    required String? error,
    required List products,
    required ThemeData theme,
  }) {
    // Loading state - show when:
    // 1. Loading and no products, OR
    // 2. Tab is switching (loading new products for different operation type)
    if (isLoading && (products.isEmpty || _isTabSwitching)) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('Đang tải sản phẩm...'),
          ],
        ),
      );
    }

    // Error state
    if (error != null && products.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64,
                color: theme.colorScheme.error,
              ),
              const SizedBox(height: 16),
              Text(
                'Lỗi',
                style: theme.textTheme.titleLarge?.copyWith(
                  color: theme.colorScheme.error,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                error,
                textAlign: TextAlign.center,
                style: theme.textTheme.bodyMedium,
              ),
              const SizedBox(height: 24),
              FilledButton.icon(
                onPressed: _onRefresh,
                icon: const Icon(Icons.refresh),
                label: const Text('Thử lại'),
              ),
            ],
          ),
        ),
      );
    }

    // Empty state
    if (products.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.inventory_2_outlined,
                size: 64,
                color: theme.colorScheme.onSurfaceVariant,
              ),
              const SizedBox(height: 16),
              Text(
                'Không có sản phẩm',
                style: theme.textTheme.titleLarge,
              ),
              const SizedBox(height: 8),
              Text(
                'Không tìm thấy sản phẩm nào cho kho và loại thao tác này.',
                textAlign: TextAlign.center,
                style: theme.textTheme.bodyMedium?.copyWith(
                  color: theme.colorScheme.onSurfaceVariant,
                ),
              ),
              const SizedBox(height: 24),
              FilledButton.icon(
                onPressed: _onRefresh,
                icon: const Icon(Icons.refresh),
                label: const Text('Làm mới'),
              ),
            ],
          ),
        ),
      );
    }

    // Success state - show products list
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 8),
        itemCount: products.length,
        itemBuilder: (context, index) {
          final product = products[index];
          return ProductListItem(
            product: product,
            onTap: () {
              // Navigate to product detail page with current tab's operation type
              context.goToProductDetail(
                warehouseId: widget.warehouseId,
                productId: product.id,
                warehouseName: widget.warehouseName,
                operationType: _currentOperationType,
              );
            },
          );
        },
      ),
    );
  }
}
