import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:inventory_system/services/product_service.dart';

class ProductFormScreen extends StatefulWidget {
  final Map<String, dynamic>? product;

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

  @override
  State<ProductFormScreen> createState() => _ProductFormScreenState();
}

class _ProductFormScreenState extends State<ProductFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _productService = ProductService();
  bool _isLoading = false;

  late TextEditingController _nameController;
  late TextEditingController _shortNameController;
  late TextEditingController _modelNoController;

  String? _selectedCategory;
  final List<String> _categories = ['Asset', 'Disposable', 'Part'];

  List<dynamic> _manufacturers = [];
  dynamic _selectedManufacturer;

  File? _imageFile;
  String? _base64Image;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.product?['productName']?.toString());
    _shortNameController = TextEditingController(text: widget.product?['productShortName']?.toString());
    _modelNoController = TextEditingController(text: widget.product?['modelNo']?.toString());
    _selectedCategory = widget.product?['category'];

    _fetchDropdownData();
  }

  Future<void> _fetchDropdownData() async {
    try {
      final manufacturers = await _productService.fetchManufacturers();
      if (!mounted) return;
      setState(() {
        _manufacturers = manufacturers;
        if (widget.product != null) {
          final manufacturerId = widget.product!['manufacturerId'];
          _selectedManufacturer = _manufacturers.firstWhere((m) => m['manufacturerId'] == manufacturerId, orElse: () => null);
        }
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load manufacturers: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery, imageQuality: 70, maxWidth: 800);

    if (pickedFile != null) {
      final bytes = await pickedFile.readAsBytes();
      setState(() {
        _imageFile = File(pickedFile.path);
        _base64Image = base64Encode(bytes);
      });
    }
  }

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

  Future<void> _submitForm() async {
    final isEdit = widget.product != null;
    
    // Check if the form is valid
    if (!_formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please correct the errors in the form'), backgroundColor: Colors.red),
      );
      return;
    }
    
    // Check if an image is selected for a new product
    if (!isEdit && _imageFile == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please select an image for the new product'), backgroundColor: Colors.red),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    String imagePayload = '';
    if (_base64Image != null) {
      imagePayload = _base64Image!;
    } else if (isEdit && widget.product?['imageProduct'] != null) {
      imagePayload = widget.product!['imageProduct'];
    }

    final productData = {
      'ProductName': _nameController.text,
      'ProductShortName': _shortNameController.text,
      'ManufacturerId': _selectedManufacturer['manufacturerId'],
      'Category': _selectedCategory,
      'ModelNo': _modelNoController.text,
      'ImageProduct': imagePayload,
    };

    if (isEdit) {
      productData['ProductId'] = widget.product!['productId'];
    }

    try {
      if (isEdit) {
        await _productService.updateProduct(productData);
      } else {
        await _productService.addProduct(productData);
      }

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text('Product ${isEdit ? 'updated' : 'added'} successfully'),
            backgroundColor: Colors.green),
      );
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to save product: $e'), backgroundColor: Colors.red),
      );
    }

    if (mounted) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEdit = widget.product != null;

    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(isEdit ? 'Edit Product' : 'Add Product'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildLabel('Product Name'),
                const SizedBox(height: 8),
              _buildTextField(
                controller: _nameController, 
                hintText: 'Enter product name',
                validator: (value) => (value == null || value.isEmpty) ? 'Product name is required' : null,
              ),
                const SizedBox(height: 20),
              _buildLabel('Product Short Name'),
                const SizedBox(height: 8),
              _buildTextField(
                controller: _shortNameController,
                hintText: 'Enter a short name',
                helperText: '*Product short name limited to 13 characters',
                validator: (value) => (value == null || value.isEmpty) ? 'Short name is required' : null,
              ),
              const SizedBox(height: 20),
                _buildLabel('Model No'),
              const SizedBox(height: 8),
                _buildTextField(
                  controller: _modelNoController, 
                  hintText: 'Enter model number',
                  validator: (value) => (value == null || value.isEmpty) ? 'Model number is required' : null,
                ),
              const SizedBox(height: 20),
                _buildLabel('Manufacturer'),
              const SizedBox(height: 8),
                _buildDropdown(_manufacturers, _selectedManufacturer, 'Select Manufacturer', (val) {
                setState(() => _selectedManufacturer = val);
              },  (item) => item['manufacturerName']),
                const SizedBox(height: 20),
                  _buildLabel('Category'),
                const SizedBox(height: 8),
                  _buildDropdown(_categories, _selectedCategory, 'Select Category', (val) {
                  setState(() => _selectedCategory = val);
              }, (item) => item.toString()),
              const SizedBox(height: 20),
              _buildLabel('Image'),
              const SizedBox(height: 8),
              _buildImagePicker(),
              const SizedBox(height: 40),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _isLoading ? null : _submitForm,
                  icon: _isLoading ? Container() : const Icon(Icons.save, color: Colors.white),
                  label: _isLoading
                      ? const CircularProgressIndicator(color: Colors.white)
                      : Text(
                          isEdit ? 'Update' : 'Submit',
                          style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600),
                        ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple.shade300,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    elevation: 0,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  Widget _buildImagePicker() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 180,
          width: double.infinity,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            color: Colors.grey.shade200,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: Center(
            child: _buildImagePreview(),
          ),
        ),
        const SizedBox(height: 8),
        TextButton.icon(
          onPressed: _pickImage,
          icon: const Icon(Icons.image_outlined),
          label: const Text('Select Image'),
        ),
      ],
    );
  }

  Widget _buildImagePreview() {
    if (_imageFile != null) {
      return Image.file(_imageFile!, fit: BoxFit.cover, width: double.infinity);
    } else if (widget.product?['imageProduct'] != null && widget.product!['imageProduct'].isNotEmpty) {
      const String baseUrl = 'https://dev9.pstw.com.my';
      final String fullImageUrl = baseUrl + widget.product!['imageProduct'];
      return Image.network(
        fullImageUrl,
        fit: BoxFit.cover,
        width: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          return const Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.broken_image_outlined, color: Colors.grey, size: 48),
              SizedBox(height: 8),
              Text('Could not load image', style: TextStyle(color: Colors.grey)),
            ],
          );
        },
      );
    } else {
      return const Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.camera_alt_outlined, color: Colors.grey, size: 48),
          SizedBox(height: 8),
          Text('No image selected', style: TextStyle(color: Colors.grey)),
        ],
      );
    }
  }

  Widget _buildLabel(String text) {
    return Text(text, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500));
  }

  Widget _buildTextField({
    required TextEditingController controller,
    String? hintText,
    TextInputType? keyboardType,
    String? helperText,
    List<TextInputFormatter>? inputFormatters,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      validator: validator,
      decoration: InputDecoration(
        labelText: hintText,
        labelStyle: TextStyle(color: Colors.grey.shade600),
        helperText: helperText,
        helperStyle: const TextStyle(fontStyle: FontStyle.italic, color: Colors.grey),
        border: const OutlineInputBorder(),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.purple.shade200, width: 2),
        ),
      ),
    );
  }

  Widget _buildDropdown(
    List<dynamic> items,
    dynamic selectedItem,
    String hint,
    void Function(dynamic) onChanged,
    String Function(dynamic) displayField,
  ) {
    return DropdownButtonFormField<dynamic>(
      value: selectedItem,
      hint: Text(hint, style: TextStyle(color: Colors.grey.shade600)),
      isExpanded: true,
      items: items.map<DropdownMenuItem<dynamic>>((item) {
        return DropdownMenuItem<dynamic>(
          value: item,
          child: Text(displayField(item)),
        );
      }).toList(),
      onChanged: (val) => onChanged(val),
      validator: (value) => value == null ? 'This field is required' : null,
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.grey.shade300),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(color: Colors.purple.shade200, width: 2),
        ),
      ),
    );
  }
}
