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

import '../application/get_orders.dart';
import '../application/orders_controller.dart';
import '../domain/orders_repository.dart';
import 'widgets/order_card.dart';
import 'widgets/order_detail_panel.dart';

/// The main Orders page.
///
/// Displays a list of orders on the left and a detail panel on the right.
/// Users can select an order to view its full details.
class OrdersPage extends StatefulWidget {
  final OrdersRepository repository;

  /// Optional callback to navigate to the Products page for a given SKU.
  final void Function(String sku)? onViewProduct;

  /// Optional callback to navigate to the Inventory page for a given SKU.
  final void Function(String sku)? onViewInventory;

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

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

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

  const OrdersPage({
    super.key,
    required this.repository,
    this.onViewProduct,
    this.onViewInventory,
    this.initialFilter,
    this.initialQuery,
    this.initialSelectedId,
  });

  @override
  State<OrdersPage> createState() => _OrdersPageState();
}

class _OrdersPageState extends State<OrdersPage> {
  late final OrdersController controller;

  @override
  void initState() {
    super.initState();
    controller = OrdersController(GetOrders(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 ID if requested.
      if (widget.initialSelectedId != null) {
        controller.selectById(widget.initialSelectedId!);
      }
    });
  }

  @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 orders.'));
        }

        return LayoutBuilder(
          builder: (context, constraints) {
            // On narrow screens show only the list; on wide screens show
            // a master-detail layout.
            if (constraints.maxWidth < 800) {
              return _buildOrderList();
            }
            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(width: 380, child: _buildOrderList()),
                const SizedBox(width: KcSpacing.md),
                Expanded(child: _buildDetail()),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildOrderList() {
    return ListView.separated(
      itemCount: controller.orders.length,
      separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.sm),
      itemBuilder: (context, index) {
        final order = controller.orders[index];
        return SizedBox(
          height: 160,
          child: OrderCard(
            order: order,
            isSelected: order.id == controller.selectedOrder?.id,
            onTap: () => controller.selectOrder(order),
          ),
        );
      },
    );
  }

  Widget _buildDetail() {
    final selected = controller.selectedOrder;
    if (selected == null) {
      return const Center(child: Text('Select an order to view details'));
    }
    return OrderDetailPanel(
      order: selected,
      onViewProduct: widget.onViewProduct,
      onViewInventory: widget.onViewInventory,
    );
  }
}
