import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:inventory_system/services/product_service.dart';
import 'package:inventory_system/services/store_service.dart';
import 'package:inventory_system/services/product_request_service.dart';
import 'package:inventory_system/services/session_manager.dart';
import 'package:inventory_system/services/api_service.dart';
import 'package:intl/intl.dart';

class ProductRequestFormScreen extends StatefulWidget {
  const ProductRequestFormScreen({super.key});

  @override
  State<ProductRequestFormScreen> createState() => _ProductRequestFormScreenState();
}

class _ProductRequestFormScreenState extends State<ProductRequestFormScreen> {
  final _formKey = GlobalKey<FormState>();
  
  // Services
  final _productService = ProductService();
  final _storeService = StoreService();
  final _requestService = ProductRequestService();

  bool _isLoading = false;
  bool _isSubmitting = false;

  // Data Lists
  List<dynamic> _products = [];
  List<Map<String, dynamic>> _allStores = [];
  List<Map<String, dynamic>> _userStores = [];
  List<Map<String, dynamic>> _requestFromStores = [];

  // Selections & Controllers
  dynamic _selectedProduct;
  int? _fromStoreId;
  int? _toStoreId;
  final _quantityController = TextEditingController();
  final _remarkController = TextEditingController();
  final _categoryController = TextEditingController();
  
  // File placeholder
  String? _documentPath; 

  @override
  void initState() {
    super.initState();
    _fetchInitialData();
  }

  @override
  void dispose() {
    _quantityController.dispose();
    _remarkController.dispose();
    _categoryController.dispose();
    super.dispose();
  }

  Future<void> _fetchInitialData() async {
    setState(() => _isLoading = true);
    try {
      final currentUser = SessionManager.instance.currentUser;
      final userId = currentUser?['id'];

      if (userId == null) throw Exception("User not logged in");

      final products = await _productService.fetchProducts();
      final allStores = await _storeService.fetchStores();
      final userStores = await _storeService.fetchSpecificUserStores(userId);

      if (!mounted) return;

      setState(() {
        _products = products;
        _allStores = allStores;
        _userStores = userStores;

        // Filter 'Request From' stores: Exclude stores the user manages
        final userStoreIds = userStores.map((s) => s['id']).toSet();
        _requestFromStores = allStores.where((s) => !userStoreIds.contains(s['id'])).toList();
        
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error loading data: $e'), backgroundColor: Colors.red),
      );
      setState(() => _isLoading = false);
    }
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }
    if (_selectedProduct == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please select a product'), backgroundColor: Colors.red),
      );
      return;
    }

    setState(() => _isSubmitting = true);

    try {
      final currentUser = SessionManager.instance.currentUser;
      final userId = currentUser?['id'];
      
      // Construct payload based on web app logic
      final requestData = {
        "ProductId": _selectedProduct['productId'],
        "StationId": null, // As per web app observation
        "UserId": userId,
        "ProductCategory": _selectedProduct['category'],
        "RequestQuantity": int.parse(_quantityController.text),
        "remarkUser": _remarkController.text,
        "remarkMasterInv": "",
        "status": "Requested",
        "requestDate": DateTime.now().toIso8601String(), // Or use server time
        "approvalDate": null,
        "fromStoreItem": _fromStoreId,
        "assignStoreItem": _toStoreId,
        "Document": _documentPath // Placeholder for now
      };

      await _requestService.addRequestMaster(requestData);

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Request submitted successfully'), backgroundColor: Colors.green),
      );
      Navigator.pop(context, true); // Return true to refresh list
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to submit: $e'), backgroundColor: Colors.red),
      );
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    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: const Text(
          'New Product Request',
          style: TextStyle(color: Colors.black87, fontSize: 18, fontWeight: FontWeight.w600),
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SafeArea(
              child: Form(
                key: _formKey,
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildLabel('Product'),
                      const SizedBox(height: 8),
                      _buildProductDropdown(),
                      const SizedBox(height: 16),

                      _buildLabel('Product Image'),
                      const SizedBox(height: 8),
                      _buildProductImage(),
                      const SizedBox(height: 16),

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

                      _buildLabel('Quantity'),
                      const SizedBox(height: 8),
                      _buildTextField(_quantityController, 'Enter quantity', keyboardType: TextInputType.number, isRequired: true),
                      const SizedBox(height: 16),

                      _buildLabel('Request From Store'),
                      const SizedBox(height: 8),
                      _buildStoreDropdown(
                        _requestFromStores, 
                        _fromStoreId, 
                        'Select Source Store', 
                        (val) => setState(() => _fromStoreId = val)
                      ),
                      const SizedBox(height: 16),

                      _buildLabel('Send To Store'),
                      const SizedBox(height: 8),
                      _buildStoreDropdown(
                        _userStores, 
                        _toStoreId, 
                        'Select Your Store', 
                        (val) => setState(() => _toStoreId = val)
                      ),
                      if (_userStores.isEmpty)
                        const Padding(
                          padding: EdgeInsets.only(top: 4.0),
                          child: Text('No stores assigned to you.', style: TextStyle(color: Colors.red, fontSize: 12)),
                        ),
                      const SizedBox(height: 16),

                      _buildLabel('Remark'),
                      const SizedBox(height: 8),
                      _buildTextField(_remarkController, 'Optional remarks'),
                      const SizedBox(height: 16),

                      _buildLabel('Document / Picture'),
                      const SizedBox(height: 8),
                      _buildFilePickerPlaceholder(),
                      const SizedBox(height: 32),

                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton.icon(
                          onPressed: _isSubmitting ? null : _submit,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.purple.shade300,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 16),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                            elevation: 0,
                          ),
                          icon: _isSubmitting 
                              ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                              : const Icon(Icons.save),
                          label: Text(_isSubmitting ? 'Submitting...' : 'Submit Request', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
    );
  }

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

  Widget _buildTextField(TextEditingController controller, String hint, {bool readOnly = false, TextInputType? keyboardType, bool isRequired = false}) {
    return TextFormField(
      controller: controller,
      readOnly: readOnly,
      keyboardType: keyboardType,
      decoration: InputDecoration(
        hintText: hint,
        filled: true,
        fillColor: readOnly ? Colors.grey.shade100 : Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: Colors.grey.shade300)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: Colors.grey.shade300)),
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      ),
      validator: isRequired ? (val) => (val == null || val.isEmpty) ? 'Required' : null : null,
    );
  }

  Widget _buildProductDropdown() {
    return DropdownButtonFormField<dynamic>(
      value: _selectedProduct,
      isExpanded: true,
      hint: const Text('Select Product'),
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: Colors.grey.shade300)),
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      ),
      items: _products.map((p) {
        final name = p['productName'] ?? 'Unknown';
        final model = p['modelNo'] ?? '';
        return DropdownMenuItem(
          value: p,
          child: Text('$name ($model)', overflow: TextOverflow.ellipsis),
        );
      }).toList(),
      onChanged: (val) {
        setState(() {
          _selectedProduct = val;
          _categoryController.text = val?['category'] ?? '';
        });
      },
      validator: (val) => val == null ? 'Required' : null,
    );
  }

  Widget _buildStoreDropdown(List<Map<String, dynamic>> stores, int? currentValue, String hint, Function(int?) onChanged) {
    return DropdownButtonFormField<int>(
      value: currentValue,
      isExpanded: true,
      hint: Text(hint),
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: Colors.grey.shade300)),
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      ),
      items: stores.map((s) {
        return DropdownMenuItem<int>(
          value: s['id'],
          child: Text(s['storeName'] ?? 'Unknown Store', overflow: TextOverflow.ellipsis),
        );
      }).toList(),
      onChanged: onChanged,
      validator: (val) => val == null ? 'Required' : null,
    );
  }

  Widget _buildProductImage() {
    final 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.toString().isNotEmpty
          ? Image.network(
              ApiService.baseUrl + imageUrl,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) => const Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.broken_image, color: Colors.grey, size: 40),
                  SizedBox(height: 8),
                  Text('Image not found', style: TextStyle(color: Colors.grey)),
                ],
              ),
            )
          : const Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.image, color: Colors.grey, size: 40),
                SizedBox(height: 8),
                Text('Select a product to view image', style: TextStyle(color: Colors.grey)),
              ],
            ),
    );
  }

  Widget _buildFilePickerPlaceholder() {
    return InkWell(
      onTap: () {
        // Placeholder for file picker logic
        setState(() {
          _documentPath = "demo_document.pdf"; // Simulate selection
        });
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("File selected (Demo)")));
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            const Icon(Icons.attach_file, color: Colors.grey),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                _documentPath ?? 'Choose File...',
                style: TextStyle(color: _documentPath != null ? Colors.black87 : Colors.grey.shade600),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

