import 'dart:async';
import 'dart:convert'; // Added this import
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:inventory_system/services/department_service.dart';
import 'package:inventory_system/services/item_service.dart';
import 'package:inventory_system/services/product_service.dart';
import 'package:inventory_system/services/supplier_service.dart';
import 'package:inventory_system/services/currency_service.dart';
import 'package:inventory_system/services/session_manager.dart';
import 'package:inventory_system/services/api_service.dart';
import 'package:intl/intl.dart';

class ItemFormScreen extends StatefulWidget {
  final Map<String, dynamic>? item;

  const ItemFormScreen({super.key, this.item});

  @override
  State<ItemFormScreen> createState() => _ItemFormScreenState();
}

class _ItemFormScreenState extends State<ItemFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _itemService = ItemService();
  final _productService = ProductService();
  final _supplierService = SupplierService();
  final _currencyService = CurrencyService();
  final _departmentService = DepartmentService();

  bool _isLoading = false;

  // Controllers
  final _companyController = TextEditingController();
  final _departmentController = TextEditingController();
  final _productCategoryController = TextEditingController();
  final _partNumberController = TextEditingController();
  final _quantityController = TextEditingController(text: '1');
  final _poNoController = TextEditingController();
  final _defaultPriceController = TextEditingController();
  final _currencyRateController = TextEditingController(text: '1');
  final _itemPriceController = TextEditingController(text: '0.00');
  final _doNumberController = TextEditingController();
  final _warrantyController = TextEditingController();
  final _invoiceNumberController = TextEditingController();
  final _serialNumberController = TextEditingController();

  // Dates
  DateTime? _purchaseDate;
  DateTime? _doDate;
  DateTime? _warrantyEndDate;
  DateTime? _invoiceDate;

  // Dropdowns
  final List<String> _teams = ['Continuous', 'Manual'];
  String? _selectedTeam;
  List<dynamic> _products = [];
  dynamic _selectedProduct;
  List<dynamic> _suppliers = [];
  dynamic _selectedSupplier;
  Map<String, dynamic> _currencies = {};
  String? _selectedCurrency;
  List<dynamic> _companies = [];
  dynamic _selectedCompany;
  List<dynamic> _departmentsForSelectedCompany = [];
  dynamic _selectedDepartment;


  @override
  void initState() {
    super.initState();
    _setupInitialData();

    _defaultPriceController.addListener(_calculateItemPrice);
    _currencyRateController.addListener(_calculateItemPrice);
    _warrantyController.addListener(_calculateWarrantyEnd);

    if (widget.item != null) {
      _populateForm(widget.item!);
    }
  }

  void _setupInitialData() {
    final currentUser = SessionManager.instance.currentUser;
    final isSuperAdmin = currentUser?['isSuperAdmin'] ?? false;

    if (!isSuperAdmin && currentUser != null) {
        _companyController.text = currentUser['company'] ?? '';
        _departmentController.text = currentUser['department']?['departmentName'] ?? '';
    }
    _fetchDropdownData();
  }

  void _populateForm(Map<String, dynamic> item) {
    _selectedTeam = item['teamType'];
    _partNumberController.text = item['partNumber']?.toString() ?? '';
    _quantityController.text = item['quantity']?.toString() ?? '1';
    _poNoController.text = item['poNo']?.toString() ?? '';
    _defaultPriceController.text = item['defaultPrice']?.toString() ?? '0.00';
    _currencyRateController.text = item['currencyRate']?.toString() ?? '1';
    _itemPriceController.text = item['convertPrice']?.toString() ?? '0.00';
    _doNumberController.text = item['doNo']?.toString() ?? '';
    _warrantyController.text = item['warranty']?.toString() ?? '';
    _invoiceNumberController.text = item['invoiceNo']?.toString() ?? '';
    _serialNumberController.text = item['serialNumber']?.toString() ?? '';

    if (item['purchaseDate'] != null) _purchaseDate = DateTime.tryParse(item['purchaseDate']);
    if (item['doDate'] != null) {
       _doDate = DateTime.tryParse(item['doDate']);
    }
    if (item['endWDate'] != null) _warrantyEndDate = DateTime.tryParse(item['endWDate']);
    if (item['invoiceDate'] != null) _invoiceDate = DateTime.tryParse(item['invoiceDate']);
    
    _calculateItemPrice();
    _calculateWarrantyEnd();
  }

  Future<void> _fetchDropdownData() async {
    setState(() => _isLoading = true);
    try {
      final products = await _productService.fetchProducts();
      final suppliers = await _supplierService.fetchSuppliers();
      final currencies = await _currencyService.fetchCurrencies();
      final companies = await _departmentService.fetchDepartments();

      if (!mounted) return;

      setState(() {
        _products = products;
        _suppliers = suppliers;
        _currencies = currencies;
        _companies = companies;
        _selectedCurrency = _currencies.keys.contains('MYR') ? 'MYR' : null;

        if (widget.item != null) {
          final item = widget.item!;
          _selectedProduct = _products.firstWhere((p) => p['productId'] == item['productId'], orElse: () => null);
          if (_selectedProduct != null) {
            _productCategoryController.text = _selectedProduct['category'] ?? '';
          }
          _selectedSupplier = _suppliers.firstWhere((s) => s['supplierCompName'] == item['supplier'], orElse: () => null);
          if (_currencies.keys.contains(item['currency'])) {
            _selectedCurrency = item['currency'];
          }
          
          _selectedCompany = _companies.firstWhere((c) => c['companyId'] == item['companyId'], orElse: () => null);
          if (_selectedCompany != null) {
            _departmentsForSelectedCompany = _selectedCompany['departments'] ?? [];
            _selectedDepartment = _departmentsForSelectedCompany.firstWhere((d) => d['departmentId'] == item['departmentId'], orElse: () => null);
          }
        }
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load form data: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }
  
  @override
  void dispose() {
    _companyController.dispose();
    _departmentController.dispose();
    _productCategoryController.dispose();
    _partNumberController.dispose();
    _quantityController.dispose();
    _poNoController.dispose();
    _defaultPriceController.dispose();
    _currencyRateController.dispose();
    _itemPriceController.dispose();
    _doNumberController.dispose();
    _warrantyController.dispose();
    _invoiceNumberController.dispose();
    _serialNumberController.dispose();
    super.dispose();
  }

  void _calculateItemPrice() {
    final defaultPrice = double.tryParse(_defaultPriceController.text) ?? 0.0;
    final currencyRate = double.tryParse(_currencyRateController.text) ?? 1.0;
    final calculatedPrice = defaultPrice * currencyRate;
    if (mounted) {
      setState(() {
        _itemPriceController.text = calculatedPrice.toStringAsFixed(2);
      });
    }
  }

  void _calculateWarrantyEnd() {
    if (_doDate != null) {
      final warrantyMonths = int.tryParse(_warrantyController.text) ?? 0;
      if (mounted) {
        setState(() {
          _warrantyEndDate = DateTime(_doDate!.year, _doDate!.month + warrantyMonths, _doDate!.day);
        });
      }
    }
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) {
       ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please correct the errors in the form'), backgroundColor: Colors.red),
      );
      return;
    }

    setState(() => _isLoading = true);
    
    final currentUser = SessionManager.instance.currentUser;
    final isSuperAdmin = currentUser?['isSuperAdmin'] ?? false;
    final String category = _selectedProduct?['category'] ?? '';

    final int companyId = isSuperAdmin 
        ? (_selectedCompany?['companyId'] ?? 0) 
        : (currentUser?['department']?['companyId'] ?? 0);

    final int departmentId = isSuperAdmin 
        ? (_selectedDepartment?['departmentId'] ?? 0) 
        : (currentUser?['department']?['departmentId'] ?? 0);

    final itemData = {
      'ItemID': widget.item?['itemID'] ?? 0,
      'CompanyId': companyId,
      'DepartmentId': departmentId,
      'ProductId': _selectedProduct?['productId'] ?? 0,
      'TeamType': _selectedTeam,
      'PartNumber': _partNumberController.text,
      'Quantity': (category == 'Asset' || category == 'Part') ? 1 : int.tryParse(_quantityController.text) ?? 1,
      'Supplier': _selectedSupplier?['supplierCompName'] ?? '',
      'PurchaseDate': _purchaseDate != null ? DateFormat('yyyy-MM-dd').format(_purchaseDate!) : null,
      'PONo': _poNoController.text,
      'Currency': _selectedCurrency,
      'DefaultPrice': double.tryParse(_defaultPriceController.text) ?? 0,
      'CurrencyRate': double.tryParse(_currencyRateController.text) ?? 1,
      'ConvertPrice': _itemPriceController.text,
      'DONo': _doNumberController.text,
      'DODate': _doDate != null ? DateFormat('yyyy-MM-dd').format(_doDate!) : null,
      'Warranty': int.tryParse(_warrantyController.text) ?? 0,
      'EndWDate': _warrantyEndDate != null ? DateFormat('yyyy-MM-dd').format(_warrantyEndDate!) : null,
      'InvoiceNo': _invoiceNumberController.text,
      'InvoiceDate': _invoiceDate != null ? DateFormat('yyyy-MM-dd').format(_invoiceDate!) : null,
      'CreatedByUserId': currentUser?['id'] ?? 1,
      'SerialNumber': (category == 'Disposable') ? '' : _serialNumberController.text,
      'createdDate': null,
      'modifiedDate': null,
    };

    // Debugging: Print the data being sent
    final jsonItemData = jsonEncode(itemData);
    debugPrint('Submitting item data: $jsonItemData');

    try {
      if (widget.item == null) {
        await _itemService.addItem(itemData);
      } else {
        await _itemService.updateItem(itemData);
      }

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Item saved successfully'), backgroundColor: Colors.green));
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      // Enhanced error logging
      debugPrint('Failed to save item. Error: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to save item: $e'), backgroundColor: Colors.red),
      );
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEdit = widget.item != null;
    final selectedCategory = _selectedProduct?['category'] as String?;
    final isSuperAdmin = SessionManager.instance.currentUser?['isSuperAdmin'] ?? false;

    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(isEdit ? 'Edit Item' : 'Registration Item', style: const TextStyle(color: Colors.black87, fontSize: 18, fontWeight: FontWeight.w600),)
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(24.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (isSuperAdmin)
                      ...[
                        _buildLabel('Company'),
                        const SizedBox(height: 8),
                        _buildDropdown(_companies, _selectedCompany, 'Select Company', 
                          (val) => setState(() {
                            _selectedCompany = val;
                            _departmentsForSelectedCompany = _selectedCompany != null ? _selectedCompany['departments'] : [];
                            _selectedDepartment = null;
                          }), 
                          (item) => item['companyName'] ?? '', isRequired: true),
                        const SizedBox(height: 16),

                        _buildLabel('Department'),
                        const SizedBox(height: 8),
                        _buildDropdown(_departmentsForSelectedCompany, _selectedDepartment, 'Select Department', 
                          (val) => setState(() => _selectedDepartment = val), 
                          (item) => item['departmentName'] ?? '', isRequired: true),
                        const SizedBox(height: 16),
                      ]
                    else
                      ...[
                        _buildLabel('Company'),
                        const SizedBox(height: 8),
                        _buildTextField(_companyController, 'Company', readOnly: true),
                        const SizedBox(height: 16),

                        _buildLabel('Department'),
                        const SizedBox(height: 8),
                        _buildTextField(_departmentController, 'Department', readOnly: true),
                        const SizedBox(height: 16),
                      ],
                    
                    _buildLabel('Team'),
                    const SizedBox(height: 8),
                    _buildDropdown(_teams, _selectedTeam, 'Select Team', (val) => setState(() => _selectedTeam = val), (item) => item.toString()),
                    const SizedBox(height: 16),

                    _buildLabel('Product Name'),
                    const SizedBox(height: 8),
                    _buildDropdown(_products, _selectedProduct, 'Select Product', 
                      (val) => setState(() { 
                        _selectedProduct = val; 
                        _productCategoryController.text = _selectedProduct?['category'] ?? '';
                        _serialNumberController.clear();
                        _quantityController.text = '1';
                      }), 
                      (item) => item['productName'] ?? '', isRequired: true
                    ),
                    const SizedBox(height: 16),

                    _buildLabel('Product Image'),
                    const SizedBox(height: 8),
                    _buildProductImage(),
                    const SizedBox(height: 16),
                    
                    _buildLabel('Product Category'),
                    const SizedBox(height: 8),
                    _buildTextField(_productCategoryController, '', readOnly: true),
                    const SizedBox(height: 16),

                    if (selectedCategory != null) ...[
                      _buildLabel('Part Number'),
                      const SizedBox(height: 8),
                      _buildTextField(_partNumberController, 'Part Number'),
                      const SizedBox(height: 16),
                    ],

                    if (selectedCategory == 'Asset' || selectedCategory == 'Part') ...[
                      _buildLabel('Serial Number'),
                      const SizedBox(height: 8),
                      _buildTextField(_serialNumberController, 'Serial Number'),
                      const SizedBox(height: 16),
                    ],

                    if (selectedCategory == 'Disposable') ...[
                      _buildLabel('Quantity'),
                      const SizedBox(height: 8),
                      _buildTextField(_quantityController, 'Quantity', keyboardType: TextInputType.number, isRequired: true),
                      const SizedBox(height: 16),
                    ],

                    _buildLabel('Supplier'),
                    const SizedBox(height: 8),
                    _buildDropdown(_suppliers, _selectedSupplier, 'Select Supplier', (val) => setState(() => _selectedSupplier = val), (item) => item['supplierCompName'] ?? ''),
                    const SizedBox(height: 16),

                    _buildLabel('Purchase Date'),
                    const SizedBox(height: 8),
                     _buildDatePicker('Purchase Date', _purchaseDate, (date) => setState(() => _purchaseDate = date)),
                    const SizedBox(height: 16),

                    _buildLabel('PO Number'),
                    const SizedBox(height: 8),
                    _buildTextField(_poNoController, 'Enter PO'),
                    const SizedBox(height: 16),

                    _buildLabel('Default Item Price'),
                    const SizedBox(height: 8),
                    _buildTextField(_defaultPriceController, 'RM0.00', keyboardType: TextInputType.number, isRequired: true),
                    const SizedBox(height: 16),

                    _buildLabel('Currency'),
                    const SizedBox(height: 8),
                    _buildDropdown(_currencies.keys.toList(), _selectedCurrency, 'Select Currency', 
                      (val) {
                        setState(() {
                          _selectedCurrency = val;
                          _calculateItemPrice();
                        });
                      },
                     (item) => item.toString(), isRequired: true),
                    const SizedBox(height: 16),

                    _buildLabel('Currency Rate(%)'),
                    const SizedBox(height: 8),
                    _buildTextField(_currencyRateController, 'Currency Rate(%)', keyboardType: TextInputType.number, isRequired: true),
                    const SizedBox(height: 16),

                    _buildLabel('Item Price (${_selectedCurrency ?? ''})'),
                    const SizedBox(height: 8),
                    _buildTextField(_itemPriceController, 'Item Price', keyboardType: TextInputType.number, readOnly: true, isRequired: true),
                    const SizedBox(height: 16),

                    _buildLabel('DO Number'),
                    const SizedBox(height: 8),
                    _buildTextField(_doNumberController, 'Enter DO Number'),
                    const SizedBox(height: 16),

                    _buildLabel('DO Date'),
                    const SizedBox(height: 8),
                    _buildDatePicker('DO Date', _doDate, (date) {
                      setState(() => _doDate = date);
                      _calculateWarrantyEnd();
                    }),
                    const SizedBox(height: 16),

                    _buildLabel('Warranty (Months)'),
                    const SizedBox(height: 8),
                    _buildTextField(_warrantyController, 'Enter Warranty (Months)', keyboardType: TextInputType.number),
                    const SizedBox(height: 16),

                    _buildLabel('Warranty End'),
                    const SizedBox(height: 8),
                    _buildTextField(
                      TextEditingController(text: _warrantyEndDate != null ? DateFormat.yMMMd().format(_warrantyEndDate!) : 'Calculated automatically'),
                      'Warranty End Date',
                      readOnly: true,
                    ),
                    const SizedBox(height: 16),

                     _buildLabel('Invoice Number'),
                    const SizedBox(height: 8),
                     _buildTextField(_invoiceNumberController, 'Invoice Number'),
                    const SizedBox(height: 16),

                    _buildLabel('Invoice Date'),
                    const SizedBox(height: 8),
                    _buildDatePicker('Invoice Date', _invoiceDate, (date) => setState(() => _invoiceDate = date)),

                    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 _buildProductImage() {
    String? imageUrl = _selectedProduct?['imageProduct'];
    return Container(
      height: 150,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: imageUrl != null && imageUrl.isNotEmpty
        ? Image.network(
            ApiService.baseUrl + imageUrl,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) => const Icon(Icons.broken_image, color: Colors.grey, size: 48),
          )
        : const Center(child: Text('Select a product to see image', style: TextStyle(color: Colors.grey))),
    );
  }

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

  Widget _buildTextField(TextEditingController controller, String hintText, {TextInputType? keyboardType, bool isRequired = false, bool readOnly = false}) {
    return TextFormField(
      controller: controller,
      readOnly: readOnly,
      decoration: InputDecoration(
        hintText: hintText,
        filled: true,
        fillColor: readOnly ? Colors.grey.shade100 : Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
      ),
      keyboardType: keyboardType,
      validator: isRequired ? (value) => (value == null || value.isEmpty) ? 'This field is required' : null : null,
    );
  }

  Widget _buildDatePicker(String label, DateTime? date, Function(DateTime) onDateChanged) {
    return InkWell(
      onTap: () async {
        final pickedDate = await showDatePicker(
          context: context,
          initialDate: date ?? DateTime.now(),
          firstDate: DateTime(2000),
          lastDate: DateTime(2101),
        );
        if (pickedDate != null && mounted) {
          onDateChanged(pickedDate);
        }
      },
      child: InputDecorator(
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
          suffixIcon: const Icon(Icons.calendar_today)
        ),
        child: Text(date != null ? DateFormat.yMMMd().format(date) : label),
      ),
    );
  }

  Widget _buildDropdown(
      List<dynamic> items,
      dynamic selectedItem,
      String hint,
      void Function(dynamic) onChanged,
      String Function(dynamic) displayField, {
        bool isRequired = false,
      }) {
    return DropdownButtonFormField<dynamic>(
      value: selectedItem,
      hint: Text(hint),
      isExpanded: true,
      items: items.map<DropdownMenuItem<dynamic>>((item) {
        return DropdownMenuItem<dynamic>(
          value: item,
          child: Text(displayField(item)),
        );
      }).toList(),
      onChanged: (val) => onChanged(val),
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
         border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
      ),
      validator: isRequired ? (value) => (value == null) ? 'This field is required' : null : null,
    );
  }
}
