import 'package:flutter/material.dart';
import 'package:inventory_system/services/station_service.dart';
import 'package:inventory_system/services/user_service.dart';

class StationFormScreen extends StatefulWidget {
  final Map<String, dynamic>? station;

  const StationFormScreen({super.key, this.station});

  @override
  State<StationFormScreen> createState() => _StationFormScreenState();
}

class _StationFormScreenState extends State<StationFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _stationService = StationService();
  final _userService = UserService();
  bool _isLoading = false;

  late TextEditingController _nameController;
  late TextEditingController _departmentController; // For display

  List<dynamic> _users = [];
  dynamic _selectedUser;

  @override
  void initState() {
    super.initState();
    // Use camelCase for data from StationList
    _nameController = TextEditingController(text: widget.station?['stationName']?.toString() ?? '');
    _departmentController = TextEditingController(text: widget.station?['departmentName']?.toString() ?? '');
    _fetchUsers();
  }

  Future<void> _fetchUsers() async {
    try {
      final users = await _userService.fetchUsers();
      if (!mounted) return;
      setState(() {
        _users = users;
        if (widget.station != null) {
          // Use camelCase for StationList data, but PascalCase for user data
          final picId = widget.station!['stationPicID'];
          _selectedUser = _users.firstWhere((user) => user['id'] == picId, orElse: () => null);
        }
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text('Failed to load users: $e'),
              backgroundColor: Colors.red),
        );
      }
    }
  }

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

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

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

    final isEdit = widget.station != null;

    // Send PascalCase keys to the API
    final stationData = {
      'StationName': _nameController.text,
      'StationPicID': _selectedUser['id'],
      'DepartmentId': _selectedUser['department']['departmentId'],
    };

    if (isEdit) {
      stationData['StationId'] = widget.station!['stationId'];
    }

    try {
      if (isEdit) {
        await _stationService.updateStation(stationData);
      } else {
        await _stationService.addStation(stationData);
      }

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text('Station ${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 station: $e'),
            backgroundColor: Colors.red),
      );
    }

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

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

    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 Station' : 'Add Station',
          style: const TextStyle(
              color: Colors.black87, fontSize: 18, fontWeight: FontWeight.w600),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildLabel('Station Name'),
              const SizedBox(height: 8),
              _buildTextField(
                controller: _nameController,
                hintText: 'Enter station name',
                validator: (value) =>
                    (value == null || value.isEmpty) ? 'Station name is required' : null,
              ),
              const SizedBox(height: 20),
              _buildLabel('Station User PIC'),
              const SizedBox(height: 8),
              _buildUserDropdown(),
              const SizedBox(height: 20),
              _buildLabel('Department'),
              const SizedBox(height: 8),
              _buildTextField(
                controller: _departmentController,
                hintText: '',
                readOnly: true,
              ),
              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.black87,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                    elevation: 0,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUserDropdown() {
    return DropdownButtonFormField<dynamic>(
      value: _selectedUser,
      hint: const Text('Select a user'),
      isExpanded: true,
      items: _users.map<DropdownMenuItem<dynamic>>((user) {
        return DropdownMenuItem<dynamic>(
          value: user,
          // Use camelCase for user list data
          child: Text(user['fullName'] ?? 'Unnamed User'),
        );
      }).toList(),
      onChanged: (newValue) {
        setState(() {
          _selectedUser = newValue;
          // Use camelCase for user list data
          _departmentController.text = newValue?['department']?['departmentName'] ?? '';
        });
      },
      validator: (value) => value == null ? 'Please select a user' : null,
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
      ),
    );
  }

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

  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    bool readOnly = false,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      readOnly: readOnly,
      validator: validator,
      decoration: InputDecoration(
        hintText: hintText,
        filled: true,
        fillColor: readOnly ? Colors.grey.shade200 : Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
      ),
    );
  }
}
