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

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

/// The result returned when the operator submits the Create Product dialog.
class CreateProductDialogResult {
  final String name;
  final double price;
  final String description;
  final String sku;
  final int? categoryId;
  final PublishStatus status;

  const CreateProductDialogResult({
    required this.name,
    required this.price,
    required this.description,
    required this.sku,
    required this.categoryId,
    required this.status,
  });
}

/// A dialog for creating a new product.
///
/// Collects name (required), price (required), description, SKU, and category
/// from a dropdown populated with [availableCategories].
///
/// Returns a [CreateProductDialogResult] when the operator taps "Create", or
/// `null` when they cancel.
class CreateProductDialog extends StatefulWidget {
  /// The list of categories to show in the category dropdown.
  final List<ProductCategory> availableCategories;

  const CreateProductDialog({super.key, required this.availableCategories});

  @override
  State<CreateProductDialog> createState() => _CreateProductDialogState();
}

class _CreateProductDialogState extends State<CreateProductDialog> {
  final _formKey = GlobalKey<FormState>();

  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _skuController = TextEditingController();

  int? _selectedCategoryId;
  PublishStatus _selectedStatus = PublishStatus.draft;

  String? _nameError;
  String? _priceError;

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

  void _submit() {
    // Validate name
    final name = _nameController.text.trim();
    if (name.isEmpty) {
      setState(() => _nameError = 'Product name is required.');
      return;
    }

    // Validate price
    final price = double.tryParse(_priceController.text);
    if (price == null || price < 0) {
      setState(() => _priceError = 'Enter a valid price (e.g. 12.99).');
      return;
    }

    Navigator.of(context).pop(
      CreateProductDialogResult(
        name: name,
        price: price,
        description: _descriptionController.text.trim(),
        sku: _skuController.text.trim(),
        categoryId: _selectedCategoryId,
        status: _selectedStatus,
      ),
    );
  }

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

    return AlertDialog(
      title: const Text('New Product'),
      content: SizedBox(
        width: 480,
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // ── Name ──────────────────────────────────────────────────
                TextField(
                  controller: _nameController,
                  autofocus: true,
                  decoration: InputDecoration(
                    labelText: 'Product Name *',
                    hintText: 'e.g. Floral Bowl Cozy',
                    errorText: _nameError,
                    border: const OutlineInputBorder(),
                  ),
                  onChanged: (_) {
                    if (_nameError != null) setState(() => _nameError = null);
                  },
                  textInputAction: TextInputAction.next,
                ),
                const SizedBox(height: KcSpacing.md),

                // ── Price ─────────────────────────────────────────────────
                TextField(
                  controller: _priceController,
                  keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[\d.]'))],
                  decoration: InputDecoration(
                    labelText: 'Price *',
                    hintText: '0.00',
                    prefixText: '\$ ',
                    errorText: _priceError,
                    border: const OutlineInputBorder(),
                  ),
                  onChanged: (_) {
                    if (_priceError != null) setState(() => _priceError = null);
                  },
                  textInputAction: TextInputAction.next,
                ),
                const SizedBox(height: KcSpacing.md),

                // ── SKU ───────────────────────────────────────────────────
                TextField(
                  controller: _skuController,
                  decoration: const InputDecoration(
                    labelText: 'SKU',
                    hintText: 'e.g. BC-FLR-001',
                    border: OutlineInputBorder(),
                  ),
                  textInputAction: TextInputAction.next,
                ),
                const SizedBox(height: KcSpacing.md),

                // ── Category ──────────────────────────────────────────────
                if (widget.availableCategories.isNotEmpty) ...[
                  DropdownButtonFormField<int?>(
                    initialValue: _selectedCategoryId,
                    decoration: const InputDecoration(
                      labelText: 'Category',
                      border: OutlineInputBorder(),
                    ),
                    items: [
                      const DropdownMenuItem<int?>(value: null, child: Text('— None —')),
                      ...widget.availableCategories.map(
                        (cat) => DropdownMenuItem<int?>(value: cat.id, child: Text(cat.name)),
                      ),
                    ],
                    onChanged: (value) => setState(() => _selectedCategoryId = value),
                  ),
                  const SizedBox(height: KcSpacing.md),
                ],

                // ── Description ───────────────────────────────────────────
                TextField(
                  controller: _descriptionController,
                  maxLines: 3,
                  minLines: 2,
                  decoration: const InputDecoration(
                    labelText: 'Description',
                    hintText: 'Optional product description…',
                    border: OutlineInputBorder(),
                    alignLabelWithHint: true,
                  ),
                  textInputAction: TextInputAction.newline,
                ),
                const SizedBox(height: KcSpacing.md),

                // ── Initial status ────────────────────────────────────────
                Row(
                  children: [
                    Text(
                      'Initial Status:',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: KcColors.neutral,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(width: KcSpacing.sm),
                    Expanded(
                      child: SegmentedButton<PublishStatus>(
                        segments: const [
                          ButtonSegment(
                            value: PublishStatus.draft,
                            label: Text('Draft'),
                            icon: Icon(Icons.drafts_outlined, size: 16),
                          ),
                          ButtonSegment(
                            value: PublishStatus.pendingReview,
                            label: Text('Review'),
                            icon: Icon(Icons.rate_review_outlined, size: 16),
                          ),
                        ],
                        selected: {_selectedStatus},
                        onSelectionChanged: (selection) {
                          setState(() => _selectedStatus = selection.first);
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.of(context).pop(null), child: const Text('Cancel')),
        FilledButton.icon(
          onPressed: _submit,
          icon: const Icon(Icons.add, size: 18),
          label: const Text('Create Product'),
        ),
      ],
    );
  }
}

/// Shows the [CreateProductDialog] and returns the result, or `null` if
/// the operator cancelled.
Future<CreateProductDialogResult?> showCreateProductDialog(
  BuildContext context, {
  required List<ProductCategory> categories,
}) {
  return showDialog<CreateProductDialogResult>(
    context: context,
    builder: (context) => CreateProductDialog(availableCategories: categories),
  );
}
