import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';

import '../application/get_inventory_items.dart';
import '../application/inventory_controller.dart';
import '../domain/inventory_repository.dart';
import 'widgets/inventory_item_card.dart';

class InventoryPage extends StatefulWidget {
  final InventoryRepository repository;

  /// Optional callback to navigate to the Products page for a given SKU.
  /// Provided by the app layer to enable cross-feature handoffs.
  final void Function(String sku)? onViewProduct;

  /// Optional initial status filter to apply on first load (e.g. `'lowStock'`).
  final String? initialFilter;

  /// Optional initial search query to apply on first load.
  final String? initialQuery;

  /// Optional SKU to pre-select on first load (from a navigation handoff).
  final String? initialSelectedSku;

  const InventoryPage({
    super.key,
    required this.repository,
    this.onViewProduct,
    this.initialFilter,
    this.initialQuery,
    this.initialSelectedSku,
  });

  @override
  State<InventoryPage> createState() => _InventoryPageState();
}

class _InventoryPageState extends State<InventoryPage> {
  late final InventoryController controller;

  @override
  void initState() {
    super.initState();
    controller = InventoryController(GetInventoryItems(widget.repository));

    // Apply any initial filter / query before loading.
    if (widget.initialFilter != null) {
      controller.activeFilter = widget.initialFilter;
    }
    if (widget.initialQuery != null && widget.initialQuery!.isNotEmpty) {
      controller.searchQuery = widget.initialQuery!;
    }

    controller.load().then((_) {
      // After data is loaded, try to pre-select by SKU if requested.
      if (widget.initialSelectedSku != null) {
        controller.selectBySku(widget.initialSelectedSku!);
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, _) {
        if (controller.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.error != null) {
          return const Center(child: Text('Failed to load inventory data.'));
        }

        return LayoutBuilder(
          builder: (context, constraints) {
            final width = constraints.maxWidth;

            int crossAxisCount = 1;
            if (width >= 1200) {
              crossAxisCount = 3;
            } else if (width >= 700) {
              crossAxisCount = 2;
            }

            return GridView.builder(
              itemCount: controller.items.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: crossAxisCount,
                crossAxisSpacing: KcSpacing.md,
                mainAxisSpacing: KcSpacing.md,
                childAspectRatio: 1.5,
              ),
              itemBuilder: (context, index) {
                final item = controller.items[index];
                return InventoryItemCard(
                  item: item,
                  onViewProduct: widget.onViewProduct != null
                      ? () => widget.onViewProduct!(item.sku)
                      : null,
                );
              },
            );
          },
        );
      },
    );
  }
}
