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

import '../application/add_order_note.dart';
import '../application/get_orders.dart';
import '../application/orders_controller.dart';
import '../application/update_order_status.dart';
import '../domain/order_status.dart';
import '../domain/orders_repository.dart';
import 'orders_action_snack_bar.dart';
import 'widgets/add_note_dialog.dart';
import 'widgets/order_card.dart';
import 'widgets/order_detail_panel.dart';

/// The main Orders page.
///
/// Provides a search bar, status filter chips, a scrollable order list, and a
/// detail panel that appears when an order is selected. Status updates and note
/// additions are performed via the detail panel and confirmed with a SnackBar.
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;
  late final TextEditingController _searchController;

  @override
  void initState() {
    super.initState();
    _controller = OrdersController(
      GetOrders(widget.repository),
      updateOrderStatus: UpdateOrderStatus(widget.repository),
      addOrderNote: AddOrderNote(widget.repository),
    );
    _searchController = TextEditingController(text: widget.initialQuery ?? '');

    // 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.addListener(_onControllerChanged);

    _controller.load().then((_) {
      if (widget.initialSelectedId != null) {
        _controller.selectById(widget.initialSelectedId!);
      }
    });
  }

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

  void _onControllerChanged() {
    final result = _controller.lastActionResult;
    if (result != null && !_controller.isUpdating) {
      final message = result.success ? 'Order updated.' : 'Update failed.';
      showOrderActionSnackBar(context, result, successMessage: message);
      // Consume the result so it is not shown again on the next rebuild.
      _controller.lastActionResult = null;
    }
  }

  Future<void> _handleAddNote() async {
    final selected = _controller.selectedOrder;
    if (selected == null) return;
    final dialogResult = await showAddNoteDialog(context);
    if (dialogResult == null) return;
    await _controller.addOrderNote(selected.id, dialogResult.note);
  }

  Future<void> _handleUpdateStatus(OrderStatus newStatus) async {
    final selected = _controller.selectedOrder;
    if (selected == null) return;
    await _controller.updateOrderStatus(selected.id, newStatus);
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        if (_controller.isLoading) {
          return const KcLoadingState(message: 'Loading orders…');
        }

        if (_controller.error != null) {
          return KcErrorState(message: 'Failed to load orders.', onRetry: _controller.load);
        }

        return LayoutBuilder(
          builder: (context, constraints) {
            final isWide = constraints.maxWidth >= KcBreakpoints.medium;

            return Column(
              children: [
                _OrdersToolbar(
                  searchController: _searchController,
                  activeFilter: _controller.activeFilter,
                  orderCount: _controller.orders.length,
                  onSearchChanged: _controller.setSearchQuery,
                  onFilterChanged: _controller.setFilter,
                ),
                Expanded(
                  child: isWide
                      ? _WideLayout(
                          controller: _controller,
                          onUpdateStatus: _handleUpdateStatus,
                          onAddNote: _handleAddNote,
                          onViewProduct: widget.onViewProduct,
                          onViewInventory: widget.onViewInventory,
                        )
                      : _NarrowLayout(
                          controller: _controller,
                          onUpdateStatus: _handleUpdateStatus,
                          onAddNote: _handleAddNote,
                          onViewProduct: widget.onViewProduct,
                          onViewInventory: widget.onViewInventory,
                        ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}

// ── Toolbar ────────────────────────────────────────────────────────────────────

class _OrdersToolbar extends StatelessWidget {
  final TextEditingController searchController;
  final String? activeFilter;
  final int orderCount;
  final ValueChanged<String> onSearchChanged;
  final ValueChanged<String?> onFilterChanged;

  const _OrdersToolbar({
    required this.searchController,
    required this.activeFilter,
    required this.orderCount,
    required this.onSearchChanged,
    required this.onFilterChanged,
  });

  static const _filters = [
    (label: 'All', value: null),
    (label: 'Pending', value: 'pending'),
    (label: 'Processing', value: 'processing'),
    (label: 'Shipped', value: 'shipped'),
    (label: 'Delivered', value: 'delivered'),
    (label: 'Cancelled', value: 'cancelled'),
  ];

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(KcSpacing.md, KcSpacing.md, KcSpacing.md, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Search bar
          TextField(
            controller: searchController,
            onChanged: onSearchChanged,
            decoration: InputDecoration(
              hintText: 'Search by customer name or order ID…',
              prefixIcon: const Icon(Icons.search),
              suffixIcon: searchController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      tooltip: 'Clear search',
                      onPressed: () {
                        searchController.clear();
                        onSearchChanged('');
                      },
                    )
                  : null,
              border: const OutlineInputBorder(),
              isDense: true,
            ),
          ),
          const SizedBox(height: KcSpacing.sm),

          // Filter chips + order count
          Row(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: _filters.map((f) {
                      final isSelected = activeFilter == f.value;
                      return Padding(
                        padding: const EdgeInsets.only(right: KcSpacing.xs),
                        child: FilterChip(
                          label: Text(f.label),
                          selected: isSelected,
                          onSelected: (_) => onFilterChanged(f.value),
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
              const SizedBox(width: KcSpacing.sm),
              Text(
                '$orderCount order${orderCount == 1 ? '' : 's'}',
                style: Theme.of(context).textTheme.bodySmall?.copyWith(color: KcColors.neutral),
              ),
            ],
          ),
          const SizedBox(height: KcSpacing.sm),
        ],
      ),
    );
  }
}

// ── Wide layout (master + detail side-by-side) ─────────────────────────────────

class _WideLayout extends StatelessWidget {
  final OrdersController controller;
  final Future<void> Function(OrderStatus) onUpdateStatus;
  final Future<void> Function() onAddNote;
  final void Function(String sku)? onViewProduct;
  final void Function(String sku)? onViewInventory;

  const _WideLayout({
    required this.controller,
    required this.onUpdateStatus,
    required this.onAddNote,
    required this.onViewProduct,
    required this.onViewInventory,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Master list — fixed width
        SizedBox(width: 340, child: _OrderList(controller: controller)),
        const VerticalDivider(width: 1),
        // Detail panel — remaining width
        Expanded(
          child: controller.selectedOrder == null
              ? const KcEmptyState(
                  icon: Icons.receipt_long_outlined,
                  message: 'Select an order from the list to view details.',
                )
              : OrderDetailPanel(
                  order: controller.selectedOrder!,
                  isUpdating: controller.isUpdating,
                  onUpdateStatus: onUpdateStatus,
                  onAddNote: onAddNote,
                  onViewProduct: onViewProduct,
                  onViewInventory: onViewInventory,
                ),
        ),
      ],
    );
  }
}

// ── Narrow layout (list only; tap navigates to detail) ─────────────────────────

class _NarrowLayout extends StatelessWidget {
  final OrdersController controller;
  final Future<void> Function(OrderStatus) onUpdateStatus;
  final Future<void> Function() onAddNote;
  final void Function(String sku)? onViewProduct;
  final void Function(String sku)? onViewInventory;

  const _NarrowLayout({
    required this.controller,
    required this.onUpdateStatus,
    required this.onAddNote,
    required this.onViewProduct,
    required this.onViewInventory,
  });

  @override
  Widget build(BuildContext context) {
    return _OrderList(
      controller: controller,
      onTap: (order) {
        controller.selectOrder(order);
        Navigator.of(context).push(
          MaterialPageRoute<void>(
            builder: (_) => _OrderDetailPage(
              controller: controller,
              onUpdateStatus: onUpdateStatus,
              onAddNote: onAddNote,
              onViewProduct: onViewProduct,
              onViewInventory: onViewInventory,
            ),
          ),
        );
      },
    );
  }
}

// ── Shared order list ──────────────────────────────────────────────────────────

class _OrderList extends StatelessWidget {
  final OrdersController controller;
  final void Function(dynamic order)? onTap;

  const _OrderList({required this.controller, this.onTap});

  @override
  Widget build(BuildContext context) {
    if (controller.orders.isEmpty) {
      return const KcEmptyState(
        icon: Icons.receipt_long_outlined,
        message: 'No orders found. Try adjusting your search or filter.',
      );
    }

    return ListView.separated(
      padding: const EdgeInsets.all(KcSpacing.md),
      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);
              onTap?.call(order);
            },
          ),
        );
      },
    );
  }
}

// ── Narrow detail page (pushed on mobile) ─────────────────────────────────────

class _OrderDetailPage extends StatelessWidget {
  final OrdersController controller;
  final Future<void> Function(OrderStatus) onUpdateStatus;
  final Future<void> Function() onAddNote;
  final void Function(String sku)? onViewProduct;
  final void Function(String sku)? onViewInventory;

  const _OrderDetailPage({
    required this.controller,
    required this.onUpdateStatus,
    required this.onAddNote,
    required this.onViewProduct,
    required this.onViewInventory,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(controller.selectedOrder?.id ?? 'Order Details')),
      body: AnimatedBuilder(
        animation: controller,
        builder: (context, _) {
          final order = controller.selectedOrder;
          if (order == null) return const SizedBox.shrink();
          return OrderDetailPanel(
            order: order,
            isUpdating: controller.isUpdating,
            onUpdateStatus: onUpdateStatus,
            onAddNote: onAddNote,
            onViewProduct: onViewProduct,
            onViewInventory: onViewInventory,
          );
        },
      ),
    );
  }
}
