// lib/features/admin/tabs/positions/staff/add_staff_sub_tab.dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import '../../../../../../core/networks/api_client.dart';

// --- ADDED ISAR IMPORTS ---
import '../../../../../../main.dart'; 
import '../../../../map_search/models/user_model.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);

Widget _responsiveStaffFormFields(BuildContext context, List<Widget> fields) {
  return LayoutBuilder(builder: (context, bounds) {
    const gap = 16.0;
    final fieldWidth = bounds.maxWidth < 560
        ? bounds.maxWidth
        : (bounds.maxWidth - gap * (fields.length - 1)) / fields.length;
    return Wrap(
      spacing: gap,
      runSpacing: gap,
      children: [for (final field in fields) SizedBox(width: fieldWidth, child: field)],
    );
  });
}



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

  @override
  State<AddStaffSubTab> createState() => _AddStaffSubTabState();
}

class _AddStaffSubTabState extends State<AddStaffSubTab> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  
  final TextEditingController _fullNameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _nrcController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  
  Uint8List? _profileImageBytes;
  String _selectedGender = 'Male';
  bool _isObscured = true;
  bool _isLoading = false;

  final List<String> _genderOptions = ['Male', 'Female', 'Other'];
  String _selectedCountryCode = '+260';
  String _selectedCountry = 'Zambia';
  final List<Map<String, String>> _countries = [
    {'name': 'Zambia', 'code': '+260', 'flag': '🇿🇲'},
    {'name': 'Zimbabwe', 'code': '+263', 'flag': '🇿🇼'},
    {'name': 'South Africa', 'code': '+27', 'flag': '🇿🇦'},
  ];

  // --- DYNAMIC DATABASE DROPDOWNS ---
  bool _isFetchingDropdowns = true;
  List<String> _dbCampuses = [];
  List<String> _dbSchools = [];
  List<String> _dbDepartments = [];
  
  String? _selectedCampus;
  String? _selectedSchool;
  String? _selectedDepartment;

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

  @override
  void dispose() {
    _fullNameController.dispose();
    _emailController.dispose();
    _nrcController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  Future<void> _fetchDatabaseDropdowns() async {
    if (!mounted) return;
    setState(() => _isFetchingDropdowns = true);
    try {
      final results = await Future.wait<List<dynamic>>([
        ApiClient.getCampuses(),
        ApiClient.getSchools(),
        ApiClient.getDepartments(),
      ]);
      String label(dynamic row) => row is Map ? (row['name']?.toString().trim() ?? '') : '';
      if (!mounted) return;
      setState(() {
        _dbCampuses = results[0].map(label).where((value) => value.isNotEmpty).toSet().toList();
        _dbSchools = results[1].map(label).where((value) => value.isNotEmpty).toSet().toList();
        _dbDepartments = results[2].map(label).where((value) => value.isNotEmpty).toSet().toList();
        _isFetchingDropdowns = false;
      });
    } catch (error) {
      if (mounted) {
        setState(() => _isFetchingDropdowns = false);
        _showSnackBar('Could not load current campus, school, and department options: $error', Colors.redAccent);
      }
    }
  }

  Future<void> _pickImage() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 50);
      if (pickedFile != null) {
        final bytes = await pickedFile.readAsBytes();
        setState(() => _profileImageBytes = bytes);
      }
    } catch (e) {
      if (mounted) _showSnackBar('Failed to pick image.', Colors.redAccent);
    }
  }

  Widget _buildAvatarPreview() {
    if (_profileImageBytes != null) {
      return Image.memory(_profileImageBytes!, fit: BoxFit.cover, width: 140, height: 140);
    }
    return Icon(Icons.person_rounded, size: 55, color: Colors.grey.shade400);
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      if (_selectedCampus == null || _selectedSchool == null || _selectedDepartment == null) {
        _showSnackBar('Please select a Campus, School, and Department.', Colors.redAccent);
        return;
      }

      setState(() => _isLoading = true);

      try {
        String safePassword = _passwordController.text;
        if (safePassword.length > 72) safePassword = safePassword.substring(0, 72);

        String base64Image = '';
        if (_profileImageBytes != null) base64Image = base64Encode(_profileImageBytes!);

        final staffData = {
          'full_name': _fullNameController.text.trim(),
          'email': _emailController.text.trim(),
          'nrc': _nrcController.text.trim(),
          'phone': "$_selectedCountryCode ${_phoneController.text.trim()}",
          'gender': _selectedGender,
          'country': _selectedCountry,
          'campus': _selectedCampus,
          'school': _selectedSchool,
          'program': _selectedDepartment, 
          'role': 'staff', 
          'password': safePassword,
          'profile_picture': base64Image, 
        };

        final bool success = await ApiClient.addStaff(staffData);

        if (success && mounted) {
          // --- INSTANT ISAR LOCAL DATABASE SYNC ---
          final newLocalStaff = UserModel()
            ..fullName = _fullNameController.text.trim()
            ..role = 'staff'
            ..campus = _selectedCampus
            ..school = _selectedSchool
            ..program = _selectedDepartment
            ..email = _emailController.text.trim()
            ..profilePicture = base64Image;

          await isarDB.writeTxn(() async {
            await isarDB.userModels.put(newLocalStaff); 
          });

          _showSnackBar('New staff member provisioned successfully.', _darkGreen);
          Navigator.of(context).pop(true); 
        } else {
          throw Exception("Server returned false");
        }
      } catch (e) {
        if (mounted) _showSnackBar('Failed to save staff record.', Colors.redAccent);
      } finally {
        if (mounted) setState(() => _isLoading = false);
      }
    }
  }

  void _showSnackBar(String message, Color color) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.info_outline, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(child: Text(message, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold))),
          ],
        ),
        backgroundColor: color,
        behavior: SnackBarBehavior.floating,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Row(
      children: [
        Container(width: 4, height: 18, color: _standardGold),
        const SizedBox(width: 8),
        Text(title, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.grey.shade800, letterSpacing: 0.5)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.sizeOf(context).width;
    final compact = screenWidth < 600;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 12 : 40, vertical: 16),
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      backgroundColor: Colors.white,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: compact ? screenWidth - 24 : 850, maxHeight: MediaQuery.sizeOf(context).height * 0.9),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // --- HEADER SECTION ---
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 14 : 24, vertical: 20),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('PROVISION NEW STAFF', style: TextStyle(color: Colors.white, fontSize: compact ? 14 : 18, fontWeight: FontWeight.w900, letterSpacing: compact ? .6 : 1.5)),
                  IconButton(
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),
            
            // --- SCROLLABLE FORM CONTENT ---
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 16 : 48),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // --- CIRCULAR AVATAR PICKER ---
                      Center(
                        child: GestureDetector(
                          onTap: _pickImage,
                          child: Stack(
                            alignment: Alignment.bottomRight,
                            children: [
                              Container(
                                width: 140, height: 140,
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade50,
                                  shape: BoxShape.circle, // Strictly Round!
                                  border: Border.all(color: _standardGold.withOpacity(0.5), width: 3),
                                  boxShadow: [
                                    BoxShadow(color: Colors.black.withOpacity(0.08), blurRadius: 15, offset: const Offset(0, 5))
                                  ]
                                ),
                                child: ClipOval(
                                  child: _profileImageBytes != null 
                                      ? _buildAvatarPreview()
                                      : Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Icon(Icons.person_rounded, size: 50, color: Colors.grey.shade400),
                                            const SizedBox(height: 8),
                                            Text('Upload', style: TextStyle(color: Colors.grey.shade500, fontSize: 12, fontWeight: FontWeight.bold)),
                                          ],
                                        ),
                                ),
                              ),
                              // Floating Camera Badge
                              Positioned(
                                bottom: 4, right: 4,
                                child: Container(
                                  padding: const EdgeInsets.all(10),
                                  decoration: BoxDecoration(
                                    color: _darkGreen, shape: BoxShape.circle,
                                    border: Border.all(color: Colors.white, width: 3),
                                    boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.15), blurRadius: 8, offset: const Offset(0, 4))]
                                  ),
                                  child: const Icon(Icons.camera_alt_rounded, color: Colors.white, size: 18),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 48),

                      // --- SECTION: PERSONAL DETAILS ---
                      _buildSectionTitle('Personal Information'),
                      const SizedBox(height: 20),

                      _buildFlatTextField(controller: _fullNameController, label: 'Full Legal Name', icon: Icons.person_outline, validator: (v) => v!.isEmpty ? 'Required' : null),
                      const SizedBox(height: 16),
                      
                      _responsiveStaffFormFields(context, [
            _buildFlatTextField(controller: _emailController, label: 'Official Email Address', icon: Icons.email_outlined, keyboardType: TextInputType.emailAddress, validator: (v) => v!.contains('@') ? null : 'Invalid email'),
            _buildFlatPhoneInput(
                              controller: _phoneController, currentCode: _selectedCountryCode,
                              onCodeChanged: (val) {
                                if (val != null) setState(() { _selectedCountryCode = val; _selectedCountry = _countries.firstWhere((c) => c['code'] == val)['name']!; });
                              },
                            ),
          ]),
                      const SizedBox(height: 16),
                      
                      _responsiveStaffFormFields(context, [
            _buildFlatTextField(controller: _nrcController, label: 'NRC / ID Number', icon: Icons.credit_card_outlined),
            _buildFlatDropdown(
                              label: 'Gender', icon: Icons.people_outline, currentValue: _selectedGender, items: _genderOptions,
                              onChanged: (val) { if (val != null) setState(() => _selectedGender = val); }
                            ),
          ]),

                      const SizedBox(height: 40),
                      const Divider(height: 1),
                      const SizedBox(height: 40),

                      // --- SECTION: ACADEMIC PLACEMENT ---
                      _buildSectionTitle('Academic Placement'),
                      const SizedBox(height: 20),

                      _isFetchingDropdowns
                          ? Container(
                              padding: const EdgeInsets.all(24), decoration: BoxDecoration(color: Colors.grey.shade50, border: Border.all(color: Colors.grey.shade200)),
                              child: const Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)), SizedBox(width: 16), Text("Synchronizing Departments & Campuses...", style: TextStyle(fontWeight: FontWeight.bold, color: _darkGreen))],
                              ),
                            )
                          : LayoutBuilder(builder: (context, bounds) {
                              final gap = 16.0;
                              final fieldWidth = bounds.maxWidth < 640
                                  ? bounds.maxWidth
                                  : (bounds.maxWidth - gap * 2) / 3;
                              return Wrap(
                                spacing: gap,
                                runSpacing: gap,
                                children: [
                                  for (final field in <Widget>[
                                    _buildFlatDropdown(
                                      label: 'Campus Allocation', icon: Icons.domain,
                                      currentValue: _selectedCampus, items: _dbCampuses,
                                      onChanged: (val) => setState(() => _selectedCampus = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                    _buildFlatDropdown(
                                      label: 'School Assignment', icon: Icons.account_balance,
                                      currentValue: _selectedSchool, items: _dbSchools,
                                      onChanged: (val) => setState(() => _selectedSchool = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                    _buildFlatDropdown(
                                      label: 'Department', icon: Icons.account_tree_outlined,
                                      currentValue: _selectedDepartment, items: _dbDepartments,
                                      onChanged: (val) => setState(() => _selectedDepartment = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                  ])
                                    SizedBox(width: fieldWidth, child: field),
                                ],
                              );
                            }),
                      
                      const SizedBox(height: 40),
                      const Divider(height: 1),
                      const SizedBox(height: 40),

                      // --- SECTION: SECURITY ---
                      _buildSectionTitle('Security & Authentication'),
                      const SizedBox(height: 20),
                      
                      _buildFlatTextField(
                        controller: _passwordController, 
                        label: 'Initial Login Password', 
                        icon: Icons.lock_outline, 
                        isPassword: true,
                        validator: (v) => v!.length < 6 ? 'Minimum 6 characters required' : null,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // --- FOOTER ACTION BUTTONS ---
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 12 : 32, vertical: 16),
              decoration: BoxDecoration(color: Colors.grey.shade50, border: Border(top: BorderSide(color: Colors.grey.shade200))),
              child: Wrap(
                alignment: WrapAlignment.end,
                spacing: 8,
                runSpacing: 8,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.grey.shade700, padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                    ),
                    child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                  ),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _submitForm,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _darkGreen, foregroundColor: Colors.white, elevation: 0,
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 20),
                    ),
                    child: _isLoading 
                        ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : const Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.check_circle_outline_rounded, size: 20, color: Colors.white),
                              SizedBox(width: 12),
                              Text(
                                'PROVISION STAFF',
                                style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                              ),
                            ],
                          ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // --- FLAT INPUT WIDGETS ---
  Widget _buildFlatTextField({required TextEditingController controller, required String label, required IconData icon, bool isPassword = false, TextInputType keyboardType = TextInputType.text, String? Function(String?)? validator}) {
    return TextFormField(
      controller: controller, obscureText: isPassword ? _isObscured : false, keyboardType: keyboardType, validator: validator, cursorColor: _standardGold,
      style: const TextStyle(fontWeight: FontWeight.w600),
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14, fontWeight: FontWeight.normal),
        prefixIcon: Icon(icon, color: _standardGold, size: 22),
        suffixIcon: isPassword ? IconButton(icon: Icon(_isObscured ? Icons.visibility_off_outlined : Icons.visibility_outlined, size: 20), color: Colors.grey.shade500, onPressed: () => setState(() => _isObscured = !_isObscured)) : null,
        filled: true, fillColor: Colors.grey.shade50, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
        focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _standardGold, width: 2)), errorBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.redAccent)),
      ),
    );
  }

  Widget _buildFlatPhoneInput({required TextEditingController controller, required String currentCode, required ValueChanged<String?> onCodeChanged}) {
    return Container(
      decoration: BoxDecoration(color: Colors.grey.shade50, borderRadius: BorderRadius.zero, border: Border.all(color: Colors.grey.shade300)),
      child: Row(
        children: [
          const Padding(padding: EdgeInsets.only(left: 16.0), child: Icon(Icons.phone_outlined, color: _standardGold, size: 22)),
          const SizedBox(width: 8),
          Expanded(flex: 4, child: DropdownButtonHideUnderline(child: DropdownButton<String>(isExpanded: true, value: currentCode, icon: Icon(Icons.arrow_drop_down, color: Colors.grey.shade600), style: TextStyle(color: Colors.grey.shade800, fontSize: 14, fontWeight: FontWeight.w600), dropdownColor: Colors.white, onChanged: onCodeChanged, items: _countries.map((c) => DropdownMenuItem(value: c['code'], child: Text("${c['flag']} ${c['code']}"))).toList()))),
          const SizedBox(width: 8),
          Container(height: 24, width: 1, color: Colors.grey.shade300),
          Expanded(flex: 6, child: TextFormField(controller: controller, keyboardType: TextInputType.phone, validator: (val) => val!.isEmpty ? 'Required' : null, cursorColor: _standardGold, style: const TextStyle(fontWeight: FontWeight.w600), decoration: InputDecoration(hintText: 'Phone Number', hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14, fontWeight: FontWeight.normal), border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14)))),
        ],
      ),
    );
  }

  Widget _buildFlatDropdown({required String label, required IconData icon, required String? currentValue, required List<String> items, required ValueChanged<String?> onChanged, String? Function(String?)? validator}) {
    return DropdownButtonFormField<String>(
      isExpanded: true, initialValue: currentValue, validator: validator,
      style: const TextStyle(fontWeight: FontWeight.w600, color: Colors.black87, fontSize: 14),
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14, fontWeight: FontWeight.normal), prefixIcon: Icon(icon, color: _standardGold, size: 22),
        filled: true, fillColor: Colors.grey.shade50, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
        focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _standardGold, width: 2)),
      ),
      icon: Icon(Icons.keyboard_arrow_down, color: Colors.grey.shade600), dropdownColor: Colors.white,
      items: items.map((item) => DropdownMenuItem(value: item, child: Text(item, overflow: TextOverflow.ellipsis))).toList(),
      onChanged: onChanged,
    );
  }
}