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

import '../../application/product_publishing_controller.dart';
import '../../domain/publish_status.dart';

/// Truncates [text] to [maxLength] characters, appending '…' if truncated.
String _truncate(String text, {int maxLength = 60}) {
  if (text.length <= maxLength) return text;
  return '${text.substring(0, maxLength)}…';
}

/// Shows a [SnackBar] for the given [StatusActionResult].
///
/// Uses [KcColors.success] / [KcColors.danger] to match the design system.
/// This is a plain function — no broad notification infrastructure required.
void showStatusActionSnackBar(BuildContext context, StatusActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  if (result.success) {
    final verb = _pastVerbForStatus(result.targetStatus);
    message = '${result.productName} $verb successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else {
    final verb = _infinitiveVerbForStatus(result.targetStatus);
    final detail = result.errorMessage != null ? ' ${_truncate(result.errorMessage!)}' : '';
    message = 'Failed to $verb ${result.productName}.$detail';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.success ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}

/// Shows a [SnackBar] for the given [DescriptionActionResult].
void showDescriptionActionSnackBar(BuildContext context, DescriptionActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  if (result.success) {
    message = '${result.productName} description updated successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else {
    final detail = result.errorMessage != null ? ' ${_truncate(result.errorMessage!)}' : '';
    message = 'Failed to update description for ${result.productName}.$detail';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.success ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}

/// Past-tense verb for success messages (e.g. "X published successfully").
String _pastVerbForStatus(PublishStatus status) {
  switch (status) {
    case PublishStatus.published:
      return 'published';
    case PublishStatus.draft:
      return 'moved to draft';
    case PublishStatus.pendingReview:
      return 'submitted for review';
    case PublishStatus.unpublished:
      return 'unpublished';
  }
}

/// Infinitive verb for failure messages (e.g. "Failed to publish X").
String _infinitiveVerbForStatus(PublishStatus status) {
  switch (status) {
    case PublishStatus.published:
      return 'publish';
    case PublishStatus.draft:
      return 'move to draft';
    case PublishStatus.pendingReview:
      return 'submit for review';
    case PublishStatus.unpublished:
      return 'unpublish';
  }
}

/// Shows a [SnackBar] for the given [PriceActionResult].
void showPriceActionSnackBar(BuildContext context, PriceActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  if (result.success) {
    message =
        '${result.productName} price updated to \$${result.newPrice.toStringAsFixed(2)} successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else {
    final detail = result.errorMessage != null ? ' ${_truncate(result.errorMessage!)}' : '';
    message = 'Failed to update price for ${result.productName}.$detail';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.success ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}

/// Shows a [SnackBar] for the given [CategoryActionResult].
void showCategoryActionSnackBar(BuildContext context, CategoryActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  if (result.success) {
    message = '${result.productName} category updated to ${result.newCategory} successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else {
    final detail = result.errorMessage != null ? ' ${_truncate(result.errorMessage!)}' : '';
    message = 'Failed to update category for ${result.productName}.$detail';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.success ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}

/// Shows a [SnackBar] for the given [BulkActionResult].
///
/// Displays success count and, on partial failure, lists the names of
/// products that failed to update.
void showBulkActionSnackBar(BuildContext context, BulkActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  final verb = _pastVerbForStatus(result.targetStatus);

  if (result.allSucceeded) {
    message =
        '${result.successCount} ${result.successCount == 1 ? 'product' : 'products'} $verb successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else if (result.successCount == 0) {
    message =
        'Failed to ${_infinitiveVerbForStatus(result.targetStatus)} all ${result.failureCount} products.';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  } else {
    final failedList = result.failedProductNames.take(3).join(', ');
    final extra = result.failedProductNames.length > 3
        ? ' and ${result.failedProductNames.length - 3} more'
        : '';
    message = '${result.successCount} $verb, ${result.failureCount} failed ($failedList$extra).';
    backgroundColor = KcColors.warning;
    icon = Icons.warning_amber_outlined;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.allSucceeded ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}

/// Shows a [SnackBar] for the given [NameActionResult].
void showNameActionSnackBar(BuildContext context, NameActionResult result) {
  final messenger = ScaffoldMessenger.maybeOf(context);
  if (messenger == null) return;

  final String message;
  final Color backgroundColor;
  final IconData icon;

  if (result.success) {
    message = '${result.productName} renamed to ${result.newName} successfully.';
    backgroundColor = KcColors.success;
    icon = Icons.check_circle_outline;
  } else {
    final detail = result.errorMessage != null ? ' ${_truncate(result.errorMessage!)}' : '';
    message = 'Failed to rename ${result.productName}.$detail';
    backgroundColor = KcColors.danger;
    icon = Icons.error_outline;
  }

  messenger.hideCurrentSnackBar();
  messenger.showSnackBar(
    SnackBar(
      content: Row(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
      backgroundColor: backgroundColor,
      behavior: SnackBarBehavior.floating,
      duration: result.success ? const Duration(seconds: 3) : const Duration(seconds: 5),
    ),
  );
}
