import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:inventory_system/services/product_service.dart';
import 'package:inventory_system/services/station_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 ProductRequestUserForm extends StatefulWidget {
  const ProductRequestUserForm({super.key});

  @override
  State<ProductRequestUserForm> createState() => _ProductRequestUserFormState();
}

class _ProductRequestUserFormState extends State<ProductRequestUserForm> {
  final _formKey = GlobalKey<FormState>();
  
  // Services
  final _productService = ProductService();
  final _stationService = StationService();
  final _requestService = ProductRequestService();

  bool _isLoading = false;
  bool _isSubmitting = false;

  // Data
  List<dynamic> _products = [];
  List<Map<String, dynamic>> _userStations = [];
  final List<String> _assignmentTypes = ['Self-Assign', 'Station'];

  // Selections & Controllers
  dynamic _selectedProduct;
  String? _selectedAssignmentType;
  int? _selectedStationId;
  
  final _quantityController = TextEditingController();
  final _remarkController = TextEditingController();
  final _categoryController = TextEditingController();
  
  String? _fileName;
  String? _documentBase64;

  @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 stations = await _stationService.fetchStations();

      if (!mounted) return;

      setState(() {
        _products = products;
        // Filter stations where stationPicID matches the current user's ID
        _userStations = stations.where((s) => s['stationPicID'] == userId).cast<Map<String, dynamic>>().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> _pickFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.any,
      );

      if (result != null) {
        PlatformFile file = result.files.first;
        
        if (file.path != null) {
          final File ioFile = File(file.path!);
          final bytes = await ioFile.readAsBytes();
          final base64File = base64Encode(bytes);
          
          setState(() {
            _fileName = file.name;
            _documentBase64 = base64File;
          });
          
          if (!mounted) return;
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('File selected: ${file.name}')),
          );
        }
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error picking file: $e'), backgroundColor: Colors.red),
      );
    }
  }

  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
      final requestData = {
        "ProductId": _selectedProduct['productId'],
        "StationId": _selectedAssignmentType == 'Station' ? _selectedStationId : null,
        "UserId": userId,
        "ProductCategory": _selectedProduct['category'],
        "RequestQuantity": int.parse(_quantityController.text),
        "remarkUser": _remarkController.text,
        "remarkMasterInv": "",
        "status": "Requested",
        "requestDate": DateTime.now().toIso8601String(),
        "approvalDate": null,
        "Document": _documentBase64 
      };

      // Use standard addRequest API (not master)
      await _requestService.addRequest(requestData);

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Request submitted successfully'), backgroundColor: Colors.green),
      );
      Navigator.pop(context, true);
    } 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('Item Assignment'),
                      const SizedBox(height: 8),
                      _buildDropdown(
                        _assignmentTypes, 
                        _selectedAssignmentType, 
                        'Select Assignment Type', 
                        (val) {
                          setState(() {
                            _selectedAssignmentType = val;
                            if (val == 'Self-Assign') _selectedStationId = null;
                          });
                        }
                      ),
                      const SizedBox(height: 16),

                      if (_selectedAssignmentType == 'Station') ...[
                        _buildLabel('Station'),
                        const SizedBox(height: 8),
                        _buildStationDropdown(),
                        if (_userStations.isEmpty)
                          const Padding(
                            padding: EdgeInsets.only(top: 4.0),
                            child: Text('No stations 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 _buildDropdown(List<String> items, String? currentValue, String hint, Function(String?) onChanged) {
    return DropdownButtonFormField<String>(
      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: items.map((s) {
        return DropdownMenuItem<String>(
          value: s,
          child: Text(s),
        );
      }).toList(),
      onChanged: onChanged,
      validator: (val) => val == null ? 'Required' : null,
    );
  }

  Widget _buildStationDropdown() {
    return DropdownButtonFormField<int>(
      value: _selectedStationId,
      isExpanded: true,
      hint: const Text('Select Station'),
      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: _userStations.map((s) {
        return DropdownMenuItem<int>(
          value: s['stationId'],
          child: Text(s['stationName'] ?? 'Unknown Station', overflow: TextOverflow.ellipsis),
        );
      }).toList(),
      onChanged: (val) => setState(() => _selectedStationId = val),
      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: _pickFile,
      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(
                _fileName ?? 'Choose File...', 
                style: TextStyle(color: _fileName != null ? Colors.black87 : Colors.grey.shade600),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
