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

class VariationEditorScreen extends StatefulWidget {
  final int productId;
  final Variation? variation;

  const VariationEditorScreen({super.key, required this.productId, this.variation});

  @override
  State<VariationEditorScreen> createState() => _VariationEditorScreenState();
}

class _VariationEditorScreenState extends State<VariationEditorScreen> {
  final _formKey = GlobalKey<FormState>();
  bool _isSaving = false;

  final _skuController = TextEditingController();
  final _priceController = TextEditingController(); // Regular price usually
  final _salePriceController = TextEditingController();
  final _stockController = TextEditingController();
  
  bool _manageStock = false;
  String _stockStatus = 'instock';
  List<Map<String, dynamic>> _attributes = [];
  
  ProductImage? _image;
  bool _isUploadingImage = false;

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

  @override
  void initState() {
    super.initState();
    if (widget.variation != null) {
      final v = widget.variation!;
      _skuController.text = v.sku;
      
      var price = v.regularPrice ?? v.price ?? '';
      if (double.tryParse(price) != null) {
         price = double.parse(price).toStringAsFixed(2);
      }
      _priceController.text = price;
      
      var salePrice = v.salePrice ?? '';
       if (double.tryParse(salePrice) != null) {
         salePrice = double.parse(salePrice).toStringAsFixed(2);
      }
      _salePriceController.text = salePrice;
      
      _manageStock = v.manageStock;
      _stockController.text = (v.stockQuantity ?? 0).toString();
      _stockStatus = v.stockStatus;
      

      _attributes = List.from(v.attributes);
      _image = v.image;
    }
  }
  
  @override
  void dispose() {
    _skuController.dispose();
    _priceController.dispose();
    _salePriceController.dispose();
    _stockController.dispose();
    super.dispose();
  }

  Future<void> _save() async {
      if (!_formKey.currentState!.validate()) return;
      setState(() => _isSaving = true);
      
      try {
          final api = Provider.of<ApiService>(context, listen: false);
          
          final data = {
              'sku': _skuController.text,
              'regular_price': _priceController.text,
              'sale_price': _salePriceController.text,
              'manage_stock': _manageStock,
              'stock_quantity': int.tryParse(_stockController.text) ?? 0,
              'stock_status': _stockStatus,

              'attributes': _attributes,
              'image': _image != null ? {'id': _image!.id} : null,
          };
          
          if (_isNew) {
              await api.createVariation(widget.productId, data);
          } else {
              await api.updateVariation(widget.productId, widget.variation!.id, data);
          }
           if (mounted) {
            Navigator.pop(context, true); // Return true to indicate refresh needed
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Variation saved successfully')),
            );
          }
      } catch (e) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Error saving: $e'), backgroundColor: Colors.red),
            );
          }
      } finally {
          if (mounted) setState(() => _isSaving = false);
      }
  }

  void _addAttribute() {
      setState(() {
          _attributes.add({'id': 0, 'name': '', 'option': ''});
      });
  }
  
  void _removeAttribute(int index) {
      setState(() {
          _attributes.removeAt(index);
      });
  }
  
  Future<void> _deleteVariation() async {
      final confirm = await showDialog<bool>(
          context: context,
          builder: (ctx) => AlertDialog(
              title: const Text('Delete Variation'),
              content: const Text('Are you sure? This cannot be undone.'),
              actions: [
                  TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),
                  TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Delete', style: TextStyle(color: Colors.red))),
              ],
          )
      );
      
      if (confirm == true) {
           setState(() => _isSaving = true);
           try {
               final api = Provider.of<ApiService>(context, listen: false);
               await api.deleteVariation(widget.productId, widget.variation!.id);
               if (mounted) Navigator.pop(context, true);
           } catch (e) {
               if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error deleting: $e')));
               setState(() => _isSaving = false);
           }
      }

  }

  Future<void> _pickImage() async {
    final result = await FilePicker.platform.pickFiles(type: FileType.image);
    if (result == null || result.files.single.bytes == null) return;

    setState(() => _isUploadingImage = true);

    try {
      final file = result.files.single;
      final api = Provider.of<ApiService>(context, listen: false);
      final response = await api.uploadImage(file.bytes!, file.name);

      setState(() {
        _image = ProductImage(
          id: response['id'],
          src: response['source_url'] ?? response['guid']['rendered'],
          name: response['slug'] ?? file.name,
          alt: response['alt_text'] ?? '',
        );
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Image upload failed: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _isUploadingImage = false);
    }
  }

  void _removeImage() {
    setState(() {
      _image = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text(_isNew ? 'New Variation' : 'Variation #${widget.variation!.id}'),
            actions: [
                if (!_isNew)
                    IconButton(icon: const Icon(Icons.delete), onPressed: _deleteVariation),
                IconButton(icon: const Icon(Icons.check), onPressed: _isSaving ? null : _save),
            ],
        ),
        body: Form(
            key: _formKey,
            child: ListView(
                padding: const EdgeInsets.all(16),
                children: [
                    // SKU
                    TextFormField(
                        controller: _skuController,
                        decoration: const InputDecoration(labelText: 'SKU'),
                    ),
                    const SizedBox(height: 16),
                    
                    // Pricing
                    Row(children: [
                        Expanded(child: TextFormField(
                            controller: _priceController,
                            decoration: const InputDecoration(labelText: 'Regular Price'),
                            keyboardType: const TextInputType.numberWithOptions(decimal: true),
                        )),
                        const SizedBox(width: 16),
                        Expanded(child: TextFormField(
                            controller: _salePriceController,
                            decoration: const InputDecoration(labelText: 'Sale Price'),
                             keyboardType: const TextInputType.numberWithOptions(decimal: true),
                        )),
                    ]),
                    const SizedBox(height: 16),
                    
                    // Inventory
                     SwitchListTile(
                        title: const Text('Manage Stock'),
                        value: _manageStock,
                        onChanged: (v) => setState(() => _manageStock = v),
                        contentPadding: EdgeInsets.zero,
                    ),
                    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!),
                    ),

                    
                    const Divider(height: 32),
                    
                    // Image
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                             const Text('Variation Image', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                             if (_image != null)
                                TextButton.icon(
                                    icon: const Icon(Icons.close, color: Colors.red),
                                    label: const Text('Remove', style: TextStyle(color: Colors.red)),
                                    onPressed: _removeImage,
                                )
                        ],
                    ),
                    const SizedBox(height: 8),
                    InkWell(
                        onTap: _isUploadingImage ? null : _pickImage,
                        child: Container(
                            height: 150,
                            width: double.infinity,
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.grey),
                                borderRadius: BorderRadius.circular(8),
                                color: Colors.grey[800],
                            ),
                            child: _isUploadingImage
                                ? const Center(child: CircularProgressIndicator())
                                : _image != null
                                    ? Image.network(_image!.src, fit: BoxFit.cover)
                                    : const Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                            Icon(Icons.add_a_photo, size: 40, color: Colors.grey),
                                            SizedBox(height: 8),
                                            Text('Tap to add image', style: TextStyle(color: Colors.grey)),
                                        ],
                                    ),
                        ),
                    ),
                    
                    const Divider(height: 32),
                    
                    // Attributes
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                            const Text('Attributes', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                            IconButton(icon: const Icon(Icons.add), onPressed: _addAttribute),
                        ]
                    ),
                    ..._attributes.asMap().entries.map((entry) {
                        final index = entry.key;
                        final attr = entry.value;
                        return Card(
                            margin: const EdgeInsets.only(bottom: 8),
                            child: Padding(
                                padding: const EdgeInsets.all(8),
                                child: Row(
                                    children: [
                                        Expanded(
                                            child: TextFormField(
                                                initialValue: attr['name'],
                                                decoration: const InputDecoration(labelText: 'Name', hintText: 'Color'),
                                                onChanged: (v) => attr['name'] = v,
                                            ),
                                        ),
                                        const SizedBox(width: 8),
                                        Expanded(
                                            child: TextFormField(
                                                initialValue: attr['option'],
                                                decoration: const InputDecoration(labelText: 'Option', hintText: 'Blue'),
                                                onChanged: (v) => attr['option'] = v,
                                            ),
                                        ),
                                        IconButton(
                                            icon: const Icon(Icons.close, color: Colors.red),
                                            onPressed: () => _removeAttribute(index),
                                        )
                                    ],
                                ),
                            ),
                        );
                    }),
                ],
            ),
        ),
    );
  }
}
