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

/// A full-screen mobile page for creating a new product.
///
/// Collects name (required), price (required), SKU, category, and description.
/// On submit, calls [onCreateProduct] and pops on success.
class MobileCreateProductPage extends StatefulWidget {
  /// Available categories for the category dropdown.
  final List<ProductCategory> availableCategories;

  /// Callback invoked when the operator submits the form.
  final Future<void> Function({
    required String name,
    required double price,
    String description,
    String sku,
    int? categoryId,
    PublishStatus status,
  })
  onCreateProduct;

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

  @override
  State<MobileCreateProductPage> createState() => _MobileCreateProductPageState();
}

class _MobileCreateProductPageState extends State<MobileCreateProductPage> {
  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _skuController = TextEditingController();
  final _descriptionController = TextEditingController();

  int? _selectedCategoryId;
  PublishStatus _selectedStatus = PublishStatus.draft;
  bool _isSubmitting = false;

  String? _nameError;
  String? _priceError;

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

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

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

    setState(() => _isSubmitting = true);

    try {
      await widget.onCreateProduct(
        name: name,
        price: price,
        description: _descriptionController.text.trim(),
        sku: _skuController.text.trim(),
        categoryId: _selectedCategoryId,
        status: _selectedStatus,
      );
      if (mounted) {
        HapticFeedback.mediumImpact();
        Navigator.of(context).pop();
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isSubmitting = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to create product: $e'), backgroundColor: KcColors.danger),
        );
      }
    }
  }

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('New Product'),
        actions: [
          if (_isSubmitting)
            const Padding(
              padding: EdgeInsets.all(16),
              child: SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              ),
            )
          else
            TextButton(
              onPressed: _submit,
              child: const Text('Create', style: TextStyle(fontWeight: FontWeight.w700)),
            ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(KcSpacing.md),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // ── Name ────────────────────────────────────────────────
              TextField(
                controller: _nameController,
                autofocus: true,
                enabled: !_isSubmitting,
                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,
                enabled: !_isSubmitting,
                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,
                enabled: !_isSubmitting,
                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: _isSubmitting
                      ? null
                      : (value) => setState(() => _selectedCategoryId = value),
                ),
                const SizedBox(height: KcSpacing.md),
              ],

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

              // ── Initial status ────────────────────────────────────────
              Text(
                'Initial Status',
                style: theme.textTheme.bodyMedium?.copyWith(
                  color: KcColors.neutral,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: KcSpacing.xs),
              SegmentedButton<PublishStatus>(
                segments: const [
                  ButtonSegment(
                    value: PublishStatus.draft,
                    label: Text('Draft'),
                    icon: Icon(Icons.drafts_outlined, size: 16),
                  ),
                  ButtonSegment(
                    value: PublishStatus.pendingReview,
                    label: Text('Submit for Review'),
                    icon: Icon(Icons.rate_review_outlined, size: 16),
                  ),
                ],
                selected: {_selectedStatus},
                onSelectionChanged: _isSubmitting
                    ? null
                    : (selection) => setState(() => _selectedStatus = selection.first),
              ),
              const SizedBox(height: KcSpacing.xl),

              // ── Submit button ─────────────────────────────────────────
              SizedBox(
                width: double.infinity,
                child: FilledButton.icon(
                  onPressed: _isSubmitting ? null : _submit,
                  icon: _isSubmitting
                      ? const SizedBox(
                          width: 18,
                          height: 18,
                          child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                        )
                      : const Icon(Icons.add),
                  label: Text(_isSubmitting ? 'Creating…' : 'Create Product'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
