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

import '../domain/product_category.dart';
import '../domain/product_publishing_repository.dart';

/// A page for managing product categories: view, create, and delete.
///
/// Accepts a [repository] directly so it can be used standalone or pushed
/// from the [ProductPublishingPage] toolbar.
class CategoryManagementPage extends StatefulWidget {
  final ProductPublishingRepository repository;

  const CategoryManagementPage({super.key, required this.repository});

  @override
  State<CategoryManagementPage> createState() => _CategoryManagementPageState();
}

class _CategoryManagementPageState extends State<CategoryManagementPage> {
  List<ProductCategory> _categories = [];
  bool _isLoading = true;
  Object? _error;

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

  Future<void> _load() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });
    try {
      final cats = await widget.repository.getCategories();
      if (mounted) setState(() => _categories = cats);
    } catch (e) {
      if (mounted) setState(() => _error = e);
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Future<void> _showCreateDialog() async {
    final result = await showDialog<String>(
      context: context,
      builder: (ctx) => const _CreateCategoryDialog(),
    );

    if (result != null && result.isNotEmpty && mounted) {
      try {
        await widget.repository.createCategory(name: result);
        await _load();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Category "$result" created.'),
              backgroundColor: KcColors.success,
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Failed to create category: $e'),
              backgroundColor: KcColors.danger,
            ),
          );
        }
      }
    }
  }

  Future<void> _confirmDelete(ProductCategory category) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Delete Category'),
        content: Text(
          'Delete "${category.name}"? This cannot be undone.\n\n'
          'Products in this category will become uncategorized.',
        ),
        actions: [
          TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: KcColors.danger),
            onPressed: () => Navigator.of(ctx).pop(true),
            child: const Text('Delete'),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      try {
        await widget.repository.deleteCategory(category.id);
        await _load();
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('Category "${category.name}" deleted.')));
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Failed to delete category: $e'),
              backgroundColor: KcColors.danger,
            ),
          );
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Categories'),
        actions: [
          IconButton(icon: const Icon(Icons.refresh), tooltip: 'Refresh', onPressed: _load),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _showCreateDialog,
        icon: const Icon(Icons.add),
        label: const Text('New Category'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: KcSpacing.md),
            Text('Loading categories…'),
          ],
        ),
      );
    }

    if (_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 categories.'),
            const SizedBox(height: KcSpacing.md),
            OutlinedButton.icon(
              onPressed: _load,
              icon: const Icon(Icons.refresh),
              label: const Text('Retry'),
            ),
          ],
        ),
      );
    }

    if (_categories.isEmpty) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.category_outlined, size: 48, color: KcColors.neutral),
            const SizedBox(height: KcSpacing.md),
            Text(
              'No categories yet.',
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: KcColors.neutral),
            ),
            const SizedBox(height: KcSpacing.sm),
            FilledButton.icon(
              onPressed: _showCreateDialog,
              icon: const Icon(Icons.add),
              label: const Text('Create First Category'),
            ),
          ],
        ),
      );
    }

    return ListView.separated(
      padding: const EdgeInsets.all(KcSpacing.md),
      itemCount: _categories.length,
      separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.xs),
      itemBuilder: (context, index) {
        final cat = _categories[index];
        return Card(
          margin: EdgeInsets.zero,
          child: ListTile(
            leading: const Icon(Icons.label_outline),
            title: Text(cat.name),
            subtitle: Text(
              '${cat.count} ${cat.count == 1 ? 'product' : 'products'} · /${cat.slug}',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(color: KcColors.neutral),
            ),
            trailing: IconButton(
              icon: const Icon(Icons.delete_outline),
              tooltip: 'Delete category',
              color: KcColors.danger,
              onPressed: () => _confirmDelete(cat),
            ),
          ),
        );
      },
    );
  }
}

// ── Create category dialog ────────────────────────────────────────────────────

/// A self-contained dialog for creating a new category.
/// Pops with the trimmed category name on success, or null on cancel.
class _CreateCategoryDialog extends StatefulWidget {
  const _CreateCategoryDialog();

  @override
  State<_CreateCategoryDialog> createState() => _CreateCategoryDialogState();
}

class _CreateCategoryDialogState extends State<_CreateCategoryDialog> {
  final _nameController = TextEditingController();
  String? _nameError;

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  void _submit() {
    final name = _nameController.text.trim();
    if (name.isEmpty) {
      setState(() => _nameError = 'Category name is required.');
      return;
    }
    Navigator.of(context).pop(name);
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('New Category'),
      content: TextField(
        controller: _nameController,
        autofocus: true,
        decoration: InputDecoration(
          labelText: 'Category Name *',
          hintText: 'e.g. Bowl Cozies',
          errorText: _nameError,
          border: const OutlineInputBorder(),
        ),
        onChanged: (_) {
          if (_nameError != null) setState(() => _nameError = null);
        },
        textInputAction: TextInputAction.done,
        onSubmitted: (_) => _submit(),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.of(context).pop(null), child: const Text('Cancel')),
        FilledButton(onPressed: _submit, child: const Text('Create')),
      ],
    );
  }
}
