
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import '../api_service.dart';
import '../models/product.dart';
import '../utils/metadata_helper.dart';
import 'variation_editor_screen.dart';

class ProductEditorScreen extends StatefulWidget {
  final Product? product;

  const ProductEditorScreen({super.key, this.product});

  @override
  State<ProductEditorScreen> createState() => _ProductEditorScreenState();
}

class _ProductEditorScreenState extends State<ProductEditorScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final _formKey = GlobalKey<FormState>();
  bool _isSaving = false;

  // Controllers
  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _skuController = TextEditingController();
  final _descController = TextEditingController();
  final _shortDescController = TextEditingController();
  final _stockController = TextEditingController();

  bool _manageStock = false;
  String _stockStatus = 'instock';
  List<dynamic> _metaData = [];
  List<dynamic> _images = [];
  
  // Variations
  bool _isVariable = false;
  List<Variation> _variations = [];
  bool _loadingVariations = false;

  
  bool get _isNew => widget.product == null;

  @override
  void initState() {
    super.initState();
    _isVariable = widget.product?.type == ProductType.variable;
    _tabController = TabController(length: _isVariable ? 5 : 4, vsync: this); // +1 for Variations
    _initializeData();
  }

  void _initializeData() {
    if (widget.product != null) {
      final p = widget.product!;
      _nameController.text = p.name;
      
      // Format Price
      var price = p.regularPrice ?? '';
      if (double.tryParse(price) != null) {
          price = double.parse(price).toStringAsFixed(2);
      }
      _priceController.text = price;
      
      _skuController.text = p.sku ?? '';
      _descController.text = p.description.replaceAll(RegExp(r'<[^>]*>'), ''); 
      _shortDescController.text = p.shortDescription.replaceAll(RegExp(r'<[^>]*>'), '');
      _stockController.text = (p.stockQuantity ?? 0).toString();
      _manageStock = p.manageStock;
      _stockStatus = p.stockStatus;
      
      // Format Meta Prices
      _metaData = List.from(p.metaData);
      for (var meta in _metaData) {
          final key = meta['key']?.toString() ?? '';
          if (key.contains('price') && meta['value'] != null) {
              final val = meta['value'].toString();
              if (double.tryParse(val) != null) {
                  meta['value'] = double.parse(val).toStringAsFixed(2);
              }
          }
      }
      
      
      _images = p.images.map((img) => img.toJson()).toList();
      
      if (_isVariable) {
          _fetchVariations();
      }
    }
  }

  Future<void> _fetchVariations() async {
      setState(() => _loadingVariations = true);
      try {
          final api = Provider.of<ApiService>(context, listen: false);
          final vars = await api.fetchVariations(widget.product!.id);
          if (mounted) setState(() => _variations = vars);
      } catch (e) {
          if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error loading variations: $e')));
      } finally {
          if (mounted) setState(() => _loadingVariations = false);
      }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _nameController.dispose();
    _priceController.dispose();
    _skuController.dispose();
    _descController.dispose();
    _shortDescController.dispose();
    _stockController.dispose();
    super.dispose();
  }

  Future<void> _saveProduct() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isSaving = true);

    final api = Provider.of<ApiService>(context, listen: false);
    final productData = {
      'name': _nameController.text,
      'regular_price': _priceController.text,
      'sku': _skuController.text,
      'description': _descController.text,
      'short_description': _shortDescController.text,
      'manage_stock': _manageStock,
      'stock_quantity': int.tryParse(_stockController.text) ?? 0,
      'stock_status': _stockStatus,
      'meta_data': _metaData,
      'images': _images,
    };

    try {
      if (_isNew) {
        await api.createProduct(productData);
      } else {
        await api.updateProduct(widget.product!.id, productData);
      }
      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Product saved successfully')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(e.toString()), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isSaving = false);
    }
  }

  void _addMetaField() {
    setState(() {
      _metaData.add({'key': '', 'value': ''});
    });
  }

  void _removeMetaField(int index) {
    setState(() {
      _metaData.removeAt(index);
    });
  }

  void _updateMetaField(int index, String key, String value) {
    setState(() {
        // We modify the map in place or create new
        _metaData[index] = {'key': key, 'value': value}; 
    });
  }

  Future<void> _uploadImage() async {
    final result = await FilePicker.platform.pickFiles(
        type: FileType.image,
        allowMultiple: false,
    );

    if (result != null && result.files.isNotEmpty) {
        setState(() => _isSaving = true);
        try {
            final file = result.files.first;
            List<int> bytes;
            if (file.bytes != null) {
                bytes = file.bytes!;
            } else if (file.path != null) {
                bytes = File(file.path!).readAsBytesSync();
            } else {
                throw Exception('No file data');
            }
            
            final api = Provider.of<ApiService>(context, listen: false);
            final uploadedMedia = await api.uploadImage(bytes, file.name);
            
            setState(() {
                if (uploadedMedia['source_url'] != null) {
                    uploadedMedia['src'] = uploadedMedia['source_url'];
                }
                _images.add(uploadedMedia);
            });
        } catch (e) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString())));
        } finally {
            setState(() => _isSaving = false);
        }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isNew ? 'New Product' : 'Edit Product'),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: _isSaving ? null : _saveProduct,
          )
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            const Tab(text: 'General'),
            const Tab(text: 'Inventory'),
            if (_isVariable) const Tab(text: 'Variations'),
            const Tab(text: 'Plugins'),
            const Tab(text: 'Images'),
          ],
        ),
      ),
      body: Form(
        key: _formKey,
        child: TabBarView(
          controller: _tabController,
          children: [
            // General Tab
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                    TextFormField(
                        controller: _nameController,
                        decoration: const InputDecoration(labelText: 'Product Name'),
                        validator: (v) => v!.isEmpty ? 'Required' : null,
                    ),
                    const SizedBox(height: 16),
                    Row(
                        children: [
                            Expanded(child: TextFormField(
                                controller: _priceController,
                                decoration: const InputDecoration(labelText: 'Price'),
                                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                                inputFormatters: [
                                  FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
                                ],
                            )),
                            const SizedBox(width: 16),
                            Expanded(child: TextFormField(
                                controller: _skuController,
                                decoration: const InputDecoration(labelText: 'SKU'),
                            )),
                        ],
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                        controller: _shortDescController,
                        decoration: const InputDecoration(labelText: 'Short Description'),
                        maxLines: 2,
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                        controller: _descController,
                        decoration: const InputDecoration(labelText: 'Description'),
                        maxLines: 5,
                    ),
                ],
              ),
            ),

            // Inventory Tab
            SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                    children: [
                        SwitchListTile(
                            title: const Text('Manage Stock'),
                            value: _manageStock,
                            onChanged: (v) => setState(() => _manageStock = v),
                        ),
                        if (_manageStock)
                            TextFormField(
                                controller: _stockController,
                                decoration: const InputDecoration(labelText: 'Stock Quantity'),
                                keyboardType: TextInputType.number,
                            ),
                        const SizedBox(height: 16),
                        DropdownButtonFormField<String>(
                            value: _stockStatus,
                            decoration: const InputDecoration(labelText: 'Stock Status'),
                            items: const [
                                DropdownMenuItem(value: 'instock', child: Text('In Stock')),
                                DropdownMenuItem(value: 'outofstock', child: Text('Out of Stock')),
                                DropdownMenuItem(value: 'onbackorder', child: Text('On Backorder')),
                            ],
                            onChanged: (v) => setState(() => _stockStatus = v!),
                        ),
                    ],
                ),
            ),

            // Variations Tab
            if (_isVariable)
                Stack(
                    children: [
                        _loadingVariations 
                            ? const Center(child: CircularProgressIndicator())
                            : ListView.builder(
                                padding: const EdgeInsets.all(16),
                                itemCount: _variations.length,
                                itemBuilder: (context, index) {
                                    final v = _variations[index];
                                    final attrs = v.attributes.map((a) => "${a['name']}: ${a['option']}").join(', ');
                                    return Card(
                                        child: ListTile(
                                            leading: v.image != null 
                                                ? Image.network(v.image!.src, width: 40, height: 40, fit: BoxFit.cover)
                                                : const Icon(Icons.style),
                                            title: Text(attrs.isEmpty ? 'Variation #${v.id}' : attrs),
                                            subtitle: Text('SKU: ${v.sku} - Stock: ${v.stockQuantity}'),
                                            trailing: Text('\$${v.price ?? v.regularPrice ?? ''}'),
                                            onTap: () async {
                                                final result = await Navigator.push(
                                                    context,
                                                    MaterialPageRoute(
                                                        builder: (_) => VariationEditorScreen(
                                                            productId: widget.product!.id,
                                                            variation: v,
                                                        ),
                                                    ),
                                                );
                                                if (result == true) _fetchVariations();
                                            },
                                        ),
                                    );
                                },
                            ),
                        Positioned(
                            bottom: 16,
                            right: 16,
                            child: FloatingActionButton(
                                onPressed: () async {
                                      final result = await Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (_) => VariationEditorScreen(productId: widget.product!.id),
                                          ),
                                      );
                                      if (result == true) _fetchVariations();
                                },
                                child: const Icon(Icons.add),
                            ),
                        ),
                    ],
                ),

            // Plugins / Meta Tab
            ListView(
                padding: const EdgeInsets.all(16),
                children: [
                    ...MetadataHelper.groupMetadata(_metaData).entries.map((entry) {
                        final groupName = entry.key;
                        final items = entry.value;
                        
                        return Card(
                            margin: const EdgeInsets.only(bottom: 12),
                            color: const Color(0xFF1F2937),
                            child: ExpansionTile(
                                title: Text(groupName, style: const TextStyle(fontWeight: FontWeight.bold)),
                                children: items.map((meta) {
                                    final index = _metaData.indexOf(meta);
                                    final key = meta['key']?.toString() ?? '';
                                    final value = meta['value']?.toString() ?? '';
                                    
                                    return Padding(
                                        padding: const EdgeInsets.all(12),
                                        child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                                Row(
                                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                    children: [
                                                        Text(MetadataHelper.getFieldTitle(key), style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                                        IconButton(
                                                            icon: const Icon(Icons.close, color: Colors.red, size: 16),
                                                            onPressed: () => _removeMetaField(index),
                                                            padding: EdgeInsets.zero,
                                                            constraints: const BoxConstraints(),
                                                        ),
                                                    ],
                                                ),
                                                const SizedBox(height: 4),
                                                TextFormField(
                                                    initialValue: value,
                                                    decoration: InputDecoration(
                                                        labelText: key, // Keep original key as label for reference or edit? Let's use clean title as label? no, key is important ref.
                                                        // Actually user asked for friendly title.
                                                        hintText: 'Value',
                                                        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                                                    ),
                                                    maxLines: null,
                                                    keyboardType: key.contains('price') ? const TextInputType.numberWithOptions(decimal: true) : null,
                                                    inputFormatters: key.contains('price') ? [
                                                        FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
                                                    ] : null,
                                                    onChanged: (v) => _updateMetaField(index, key, v),
                                                ),
                                            ],
                                        ),
                                    );
                                }).toList(),
                            ),
                        );
                    }),
                    
                    const SizedBox(height: 16),
                    ElevatedButton.icon(
                        icon: const Icon(Icons.add),
                        label: const Text('Add Custom Meta'),
                        onPressed: _addMetaField,
                    ),
                ],
            ),

            // Images Tab
            Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                    children: [
                        ElevatedButton.icon(
                            icon: const Icon(Icons.upload),
                            label: const Text('Upload Image'),
                            onPressed: _uploadImage,
                        ),
                        const SizedBox(height: 16),
                        Expanded(
                            child: GridView.builder(
                                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 3,
                                    crossAxisSpacing: 8,
                                    mainAxisSpacing: 8,
                                ),
                                itemCount: _images.length,
                                itemBuilder: (context, index) {
                                  final img = _images[index];
                                  return Stack(
                                      children: [
                                          Positioned.fill(
                                              child: Image.network(
                                                  img['src'] ?? '', 
                                                  fit: BoxFit.cover,
                                                  errorBuilder: (_,__,___) => const Icon(Icons.broken_image),
                                              ),
                                          ),
                                          Positioned(
                                              top: 0,
                                              right: 0,
                                              child: IconButton(
                                                  icon: const Icon(Icons.delete, color: Colors.red),
                                                  onPressed: () {
                                                      setState(() => _images.removeAt(index));
                                                  },
                                              ),
                                          )
                                      ],
                                  );
                                },
                            ),
                        ),
                    ],
                ),
            ),
          ],
        ),
      ),
    );
  }
}
