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

import '../../../core/api/api_error_mapper.dart';
import '../../../core/api/api_paths.dart';
import '../../../core/api/api_providers.dart';
import '../../../core/ui/product_picker_field.dart' show ProductOption;
import '../../auth/data/auth_providers.dart';

Future<void> syncSelectedProductCategory({
  required WidgetRef ref,
  required String? token,
  required int? selectedProductId,
  required int? selectedCategoryId,
  required List<Map<String, dynamic>> products,
  required int? Function(dynamic) tryParseDynamicInt,
  required void Function(List<Map<String, dynamic>>) setProducts,
}) async {
  final productId = selectedProductId;
  final categoryId = selectedCategoryId;
  if (productId == null || categoryId == null || token == null || token.isEmpty) return;

  final current = products.cast<Map<String, dynamic>?>().firstWhere(
        (p) => tryParseDynamicInt(p?['id']) == productId,
        orElse: () => null,
      );
  final currentCategoryId = tryParseDynamicInt(current?['categoryId']);
  if (currentCategoryId == categoryId) return;

  final api = ref.read(apiClientProvider);
  await api.patchJson(
    ProductApiPaths.updateMineCategory(productId),
    body: {'categoryId': categoryId},
    token: token,
  );

  final updatedProducts = products
      .map(
        (p) => tryParseDynamicInt(p['id']) == productId
            ? {...p, 'categoryId': categoryId}
            : p,
      )
      .toList();
  setProducts(updatedProducts);
}

Future<ProductOption?> createProductInSelectedCategory({
  required WidgetRef ref,
  required BuildContext context,
  required String rawName,
  required int? selectedCategoryId,
  required List<Map<String, dynamic>> products,
  required int? Function(dynamic) tryParseDynamicInt,
  required void Function(List<Map<String, dynamic>>) setProducts,
}) async {
  final name = rawName.trim();
  final categoryId = selectedCategoryId;
  if (name.isEmpty || categoryId == null) return null;

  try {
    final token = await ref.read(authStateProvider.future);
    final api = ref.read(apiClientProvider);
    final data = await api.postJson(
      ProductApiPaths.createPrivate,
      body: {
        'name': name,
        'categoryId': categoryId,
      },
      token: token,
    );

    final created = Map<String, dynamic>.from(data as Map);
    final createdId = tryParseDynamicInt(created['id']);
    if (createdId == null) return null;

    setProducts([...products, created]);

    return (
      id: createdId,
      name: (created['canonicalName'] ?? created['name'] ?? '').toString(),
      categoryId: tryParseDynamicInt(created['categoryId']),
    );
  } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(
      buildCopyableErrorSnackBar(context, mapErrorToUserMessage(e, context)),
    );
    return null;
  }
}
