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

import '../application/get_product_drafts.dart';
import '../application/product_publishing_controller.dart';
import '../application/publish_product.dart';
import '../application/update_product_name.dart';
import '../application/update_product_price.dart';
import '../application/update_product_status.dart';
import '../domain/product_publishing_repository.dart';
import '../domain/publish_status.dart';
import 'widgets/product_draft_card.dart';
import 'widgets/product_preview_panel.dart';
import 'widgets/status_action_snack_bar.dart';

/// The main Product Publishing Workspace page.
///
/// Displays a list of product drafts on the left and a preview panel on the
/// right. Users can select a draft to preview and publish it to the store.
class ProductPublishingPage extends StatefulWidget {
  final ProductPublishingRepository repository;

  /// Optional callback to navigate to the Policy page.
  /// Provided by the app layer to enable cross-feature handoffs.
  final VoidCallback? onViewPolicy;

  /// Optional initial status filter to apply on first load (e.g. `'draft'`).
  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 ProductPublishingPage({
    super.key,
    required this.repository,
    this.onViewPolicy,
    this.initialFilter,
    this.initialQuery,
    this.initialSelectedSku,
  });

  @override
  State<ProductPublishingPage> createState() => _ProductPublishingPageState();
}

class _ProductPublishingPageState extends State<ProductPublishingPage> {
  late final ProductPublishingController controller;

  @override
  void initState() {
    super.initState();
    final repo = widget.repository;
    controller = ProductPublishingController(
      GetProductDrafts(repo),
      PublishProduct(repo),
      UpdateProductStatus(repo),
      UpdateProductPrice(repo),
      UpdateProductName(repo),
    );

    controller.addListener(_onControllerChanged);

    // 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.removeListener(_onControllerChanged);
    controller.dispose();
    super.dispose();
  }

  void _onControllerChanged() {
    final result = controller.lastActionResult;
    if (result != null) {
      controller.consumeActionResult();
      showStatusActionSnackBar(context, result);
    }

    final priceResult = controller.lastPriceResult;
    if (priceResult != null) {
      controller.consumePriceResult();
      showPriceActionSnackBar(context, priceResult);
    }

    final nameResult = controller.lastNameResult;
    if (nameResult != null) {
      controller.consumeNameResult();
      showNameActionSnackBar(context, nameResult);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, _) {
        if (controller.isLoading) {
          return const Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: KcSpacing.md),
                Text('Loading products…'),
              ],
            ),
          );
        }

        if (controller.error != null) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.error_outline, size: 48, color: KcColors.neutral),
                const SizedBox(height: KcSpacing.md),
                const Text('Failed to load product drafts.'),
                const SizedBox(height: KcSpacing.md),
                OutlinedButton.icon(
                  onPressed: controller.load,
                  icon: const Icon(Icons.refresh),
                  label: const Text('Retry'),
                ),
              ],
            ),
          );
        }

        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 _buildDraftList();
            }
            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(width: 380, child: _buildDraftList()),
                const SizedBox(width: KcSpacing.md),
                Expanded(child: _buildPreview()),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildDraftList() {
    final count = controller.drafts.length;

    if (count == 0) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.search_off, size: 48, color: KcColors.neutral),
            const SizedBox(height: KcSpacing.md),
            Text(
              controller.searchQuery.isNotEmpty || controller.activeFilter != null
                  ? 'No products match your criteria.'
                  : 'No product drafts available.',
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: KcColors.neutral),
            ),
          ],
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: KcSpacing.xs, bottom: KcSpacing.sm),
          child: Text(
            '$count ${count == 1 ? 'product' : 'products'}',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(color: KcColors.neutral),
          ),
        ),
        Expanded(
          child: ListView.separated(
            itemCount: count,
            separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.sm),
            itemBuilder: (context, index) {
              final draft = controller.drafts[index];
              return SizedBox(
                height: 160,
                child: ProductDraftCard(
                  draft: draft,
                  isSelected: draft.id == controller.selectedDraft?.id,
                  onTap: () => controller.selectDraft(draft),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildPreview() {
    final selected = controller.selectedDraft;
    if (selected == null) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.touch_app_outlined, size: 48, color: KcColors.neutral),
            const SizedBox(height: KcSpacing.md),
            Text(
              'Select a product to preview',
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: KcColors.neutral),
            ),
          ],
        ),
      );
    }
    return ProductPreviewPanel(
      draft: selected,
      isUpdating: controller.isUpdating(selected.id),
      onPublish: () => controller.updateStatus(selected.id, PublishStatus.published),
      onMoveToDraft: () => controller.updateStatus(selected.id, PublishStatus.draft),
      onPriceChanged: (price) => controller.updatePrice(selected.id, price),
      onNameChanged: (name) => controller.updateName(selected.id, name),
      onViewPolicy: widget.onViewPolicy,
    );
  }
}
