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

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

class AdminPrivateProductsPanel extends ConsumerStatefulWidget {
  final bool embedded;

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

  @override
  ConsumerState<AdminPrivateProductsPanel> createState() =>
      _AdminPrivateProductsPanelState();
}

class _AdminPrivateProductsPanelState extends ConsumerState<AdminPrivateProductsPanel> {
  bool _isLoading = true;
  String? _error;
  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).listPrivateProducts();
      if (!mounted) return;
      setState(() => _products = products);
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = mapErrorToUserMessage(e, context));
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Future<void> _promote(PendingProduct product) async {
    try {
      await ref.read(adminRepositoryProvider).promotePrivateProduct(product.id);
      if (!mounted) return;
      await _load();
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Promoterade "${product.displayName}" till global produkt.')),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        buildCopyableErrorSnackBar(context, mapErrorToUserMessage(e, context)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    if (_isLoading) return const Center(child: CircularProgressIndicator());
    if (_error != null) {
      return buildCopyableErrorPanel(
        context: context,
        message: _error!,
        onRetry: _load,
        title: 'Kunde inte läsa privata produkter',
      );
    }

    if (_products.isEmpty) {
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Privata produkter', style: theme.textTheme.titleMedium),
              const SizedBox(height: 8),
              Text(
                'Privata produkter är användarägda poster som kan lyftas upp till globala produkter när de ska återanvändas brett.',
                style: theme.textTheme.bodyMedium,
              ),
              const SizedBox(height: 8),
              Text(
                'Inga aktiva privata produkter hittades.',
                style: theme.textTheme.bodyMedium,
              ),
            ],
          ),
        ),
      );
    }

    final list = ListView.separated(
      shrinkWrap: false,
      physics: null,
      itemCount: _products.length,
      separatorBuilder: (_, __) => const Divider(height: 1),
      itemBuilder: (context, index) {
        final product = _products[index];
        return Card(
          child: ListTile(
            leading: const Icon(Icons.publish_outlined),
            title: Row(
              children: [
                Expanded(child: Text(product.displayName)),
                buildCategoryPathChip(product.categoryPath),
              ],
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('Ägare: ${product.ownerUsername ?? '—'}'),
                Text('Skapad: ${product.createdAt == null ? '—' : MaterialLocalizations.of(context).formatShortDate(product.createdAt!)}'),
              ],
            ),
            trailing: FilledButton(
              onPressed: () => _promote(product),
              child: const Text('Promote'),
            ),
          ),
        );
      },
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Privata produkter', style: theme.textTheme.titleMedium),
                const SizedBox(height: 8),
                Text(
                  'Privata produkter kan promoveras till globala produkter utan att användarens privata kopia försvinner.',
                  style: theme.textTheme.bodyMedium,
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 12),
        Expanded(child: list),
      ],
    );
  }
}