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

import '../../../core/api/api_error_mapper.dart';
import '../../../core/l10n/l10n.dart';
import '../data/admin_repository.dart';
import '../domain/pending_product.dart';

class AdminPendingProductsPanel extends ConsumerStatefulWidget {
  final bool embedded;

  const AdminPendingProductsPanel({super.key, this.embedded = false});

  @override
  ConsumerState<AdminPendingProductsPanel> createState() =>
      _AdminPendingProductsPanelState();
}

class _AdminPendingProductsPanelState
    extends ConsumerState<AdminPendingProductsPanel> {
  bool _isLoading = true;
  String? _error;
  int? _processingId;
  List<PendingProduct> _products = [];

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });
    try {
      final products = await ref.read(adminRepositoryProvider).listPendingProducts();
      if (!mounted) return;
      setState(() => _products = products);
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = mapErrorToUserMessage(e, context));
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Future<void> _handleAction(PendingProduct product, String status) async {
    setState(() => _processingId = product.id);
    try {
      await ref.read(adminRepositoryProvider).setProductStatus(product.id, status);
      if (!mounted) return;
      setState(() {
        _products = _products.where((p) => p.id != product.id).toList();
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(mapErrorToUserMessage(e, context))),
      );
    } finally {
      if (mounted) setState(() => _processingId = null);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    if (_isLoading) return const Center(child: CircularProgressIndicator());
    if (_error != null) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(_error!, style: TextStyle(color: theme.colorScheme.error)),
            const SizedBox(height: 16),
            FilledButton(onPressed: _load, child: Text(context.l10n.retryAction)),
          ],
        ),
      );
    }
    if (_products.isEmpty) {
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            context.l10n.adminNoPendingProducts,
            style: theme.textTheme.bodyMedium,
          ),
        ),
      );
    }

    final content = ListView.builder(
      shrinkWrap: widget.embedded,
      physics: widget.embedded ? const NeverScrollableScrollPhysics() : null,
      itemCount: _products.length,
      itemBuilder: (context, index) {
        final product = _products[index];
        final isProcessing = _processingId == product.id;
        return Card(
          child: ListTile(
            title: Text(product.displayName),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (product.displayName != product.name)
                  Text(product.name, style: theme.textTheme.bodySmall),
                Text('${context.l10n.adminCategoryPrefix}${product.categoryPath ?? '—'}'),
                Text('${context.l10n.adminSuggestedByPrefix}${product.ownerUsername ?? '—'}'),
                Text(
                  '${context.l10n.adminDatePrefix}${product.createdAt == null ? '—' : MaterialLocalizations.of(context).formatShortDate(product.createdAt!)}',
                  style: theme.textTheme.bodySmall,
                ),
              ],
            ),
            isThreeLine: true,
            trailing: Wrap(
              spacing: 8,
              children: [
                FilledButton(
                  onPressed: isProcessing
                      ? null
                      : () => _handleAction(product, 'active'),
                  child: Text(context.l10n.adminApproveAction),
                ),
                OutlinedButton(
                  onPressed: isProcessing
                      ? null
                      : () => _handleAction(product, 'rejected'),
                  child: Text(context.l10n.adminRejectAction),
                ),
              ],
            ),
          ),
        );
      },
    );

    if (!widget.embedded) return content;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          context.l10n.adminPendingDescription,
          style: theme.textTheme.bodyMedium,
        ),
        const SizedBox(height: 12),
        content,
      ],
    );
  }
}