// lib/features/admin/tabs/admin_positions_tab.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../../../core/networks/api_client.dart'; // To access ApiClient.bearerToken

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

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

  @override
  State<AdminPositionsTab> createState() => _AdminPositionsTabState();
}

class _AdminPositionsTabState extends State<AdminPositionsTab> {
  late Future<List<dynamic>> _positionsFuture;
  List<dynamic> _allPositions = [];
  List<dynamic> _filteredPositions = [];
  int _cachedSnapshotRequest = 0;
  int _positionsFetchGeneration = 0;
  
  final TextEditingController _searchController = TextEditingController();
  
  // API URL Configuration
  String get _baseUrl => '${ApiClient.baseUrl}/api/positions_router.php';

  @override
  void initState() {
    super.initState();
    _positionsFuture = _fetchPositions();
    _searchController.addListener(_onSearchChanged);
    ApiClient.dataChanges.addListener(_onPositionDataChange);
  }

  @override
  void dispose() {
    ApiClient.dataChanges.removeListener(_onPositionDataChange);
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    super.dispose();
  }

  Future<List<dynamic>> _fetchPositions({bool refresh = false}) async {
    final requestGeneration = ++_positionsFetchGeneration;
    try {
      final response = await ApiClient.offlineFirstGet(
        Uri.parse(_baseUrl),
        headers: await ApiClient.getHeaders(),
        forceRefresh: refresh,
      );

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        if (mounted && requestGeneration == _positionsFetchGeneration) {
          _allPositions = data;
          _filterPositions(_searchController.text);
        }
        return data;
      } else {
        // THIS WILL NOW SHOW EXACTLY WHAT THE PYTHON SERVER RETURNED (e.g., 404, 500, etc.)
        throw Exception('Server rejected request. Status: ${response.statusCode}, Details: ${response.body}');
      }
    } catch (e) {
      // Passes the real error up to the UI
      throw Exception(e.toString());
    }
  }

  void _onPositionDataChange() {
    final change = ApiClient.dataChanges.value;
    if (change == null || change.isMutation ||
        !ApiClient.sameApiFamily(change.url, Uri.parse(_baseUrl))) return;
    final request = ++_cachedSnapshotRequest;
    // A cache notification newer than an in-flight page fetch wins over that
    // older response when it eventually completes.
    _positionsFetchGeneration++;
    _applyCachedPositions(request);
  }

  Future<void> _applyCachedPositions(int request) async {
    final response = await ApiClient.cachedGet(Uri.parse(_baseUrl));
    if (!mounted || request != _cachedSnapshotRequest ||
        response == null || response.statusCode != 200) return;
    try {
      final decoded = json.decode(response.body);
      if (decoded is! List) return;
      _allPositions = decoded;
      _filterPositions(_searchController.text);
    } on FormatException {
      // Preserve the last valid rows when a damaged snapshot is encountered.
    }
  }

  Future<void> _deletePosition(int id) async {
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        title: const Text('Delete Position', style: TextStyle(color: Colors.redAccent, fontWeight: FontWeight.bold)),
        content: const Text('Are you sure you want to permanently delete this position? This action cannot be undone.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(false),
            child: const Text('CANCEL', style: TextStyle(color: Colors.grey)),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.redAccent,
              foregroundColor: Colors.white,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
            onPressed: () => Navigator.of(ctx).pop(true),
            child: const Text('DELETE'),
          ),
        ],
      ),
    );

    if (confirm != true) return;

    try {
      final response = await http.delete(
        Uri.parse('$_baseUrl/$id'),
        headers: await ApiClient.getHeaders(),
      );

      if (response.statusCode == 204 || response.statusCode == 200) {
        ApiClient.announceSuccessfulMutation(
          response.request?.url ?? Uri.parse('$_baseUrl/$id'),
        );
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Position deleted successfully.'),
              backgroundColor: _darkGreen,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
              behavior: SnackBarBehavior.floating,
            )
          );
          _triggerRefresh();
        }
      } else {
        throw Exception('Server rejected the delete request.');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Failed to delete: $e'),
            backgroundColor: Colors.redAccent,
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            behavior: SnackBarBehavior.floating,
          )
        );
      }
    }
  }

  void _triggerRefresh() {
    setState(() {
      _positionsFuture = _fetchPositions(refresh: true);
    });
  }

  void _onSearchChanged() {
    _filterPositions(_searchController.text);
  }

  void _filterPositions(String query) {
    if (query.isEmpty) {
      setState(() {
        _filteredPositions = List.from(_allPositions);
      });
    } else {
      final lowercaseQuery = query.toLowerCase();
      setState(() {
        _filteredPositions = _allPositions.where((pos) {
          final title = pos['title']?.toString().toLowerCase() ?? '';
          final dept = pos['department']?.toString().toLowerCase() ?? '';
          return title.contains(lowercaseQuery) || dept.contains(lowercaseQuery);
        }).toList();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: EdgeInsets.all(MediaQuery.sizeOf(context).width < 600 ? 12.0 : 24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // --- HEADER & SEARCH ---
            Wrap(
              alignment: WrapAlignment.spaceBetween,
              spacing: 12,
              runSpacing: 12,
              crossAxisAlignment: WrapCrossAlignment.center,
              children: [
                Text(
                  'MANAGE POSITIONS',
                  style: TextStyle(
                    fontSize: 18, 
                    fontWeight: FontWeight.w900, 
                    color: Colors.grey.shade800, 
                    letterSpacing: 1.5
                  ),
                ),
                Wrap(
                  spacing: 12,
                  runSpacing: 10,
                  crossAxisAlignment: WrapCrossAlignment.center,
                  children: [
                    // Search Bar
                    SizedBox(
                      width: MediaQuery.sizeOf(context).width < 600
                          ? (MediaQuery.sizeOf(context).width - 48).clamp(180.0, 300.0).toDouble()
                          : 300.0,
                      child: TextField(
                        controller: _searchController,
                        decoration: InputDecoration(
                          hintText: 'Search Title or Dept...',
                          prefixIcon: const Icon(Icons.search, color: Colors.grey),
                          filled: true,
                          fillColor: Colors.white,
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                          border: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _darkGreen, width: 2)),
                        ),
                      ),
                    ),
                    Tooltip(
                      message: 'Refresh positions',
                      child: IconButton(
                        onPressed: _triggerRefresh,
                        icon: const Icon(Icons.refresh_rounded, color: _darkGreen),
                        style: IconButton.styleFrom(
                          backgroundColor: _darkGreen.withOpacity(.08),
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                        ),
                      ),
                    ),
                    // Add Button
                    ElevatedButton.icon(
                      onPressed: () async {
                        final result = await showDialog<bool>(
                          context: context,
                          builder: (_) => const PositionEntryDialog(),
                        );
                        if (result == true) {
                          _triggerRefresh();
                        }
                      },
                      icon: const Icon(Icons.add_box_rounded, color: Colors.white),
                      label: const Text(
                        'ADD POSITION',
                        style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _standardGold,
                        foregroundColor: Colors.white,
                        elevation: 0,
                        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 22),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 24),

            // --- DATA TABLE WITH FUTURE BUILDER ---
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.grey.shade300, width: 1),
                  borderRadius: BorderRadius.zero, 
                ),
                child: FutureBuilder<List<dynamic>>(
                  future: _positionsFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting && _allPositions.isEmpty) {
                      return const Center(child: CircularProgressIndicator(color: _darkGreen));
                    }

                    if (snapshot.hasError) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(Icons.error_outline_rounded, color: Colors.redAccent, size: 48),
                            const SizedBox(height: 16),
                            Text('Error loading positions: ${snapshot.error}', style: const TextStyle(color: Colors.redAccent)),
                            const SizedBox(height: 16),
                            ElevatedButton(
                              onPressed: _triggerRefresh,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: _darkGreen,
                                shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                              ),
                              child: const Text('RETRY', style: TextStyle(color: Colors.white)),
                            )
                          ],
                        )
                      );
                    }

                    if (_filteredPositions.isEmpty) {
                      return const Center(
                        child: Text('No positions found.', style: TextStyle(color: Colors.grey, fontSize: 16)),
                      );
                    }

                    return SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: DataTable(
                          headingRowColor: WidgetStateProperty.resolveWith((states) => _darkGreen),
                          headingTextStyle: const TextStyle(
                            color: Colors.white, 
                            fontWeight: FontWeight.bold,
                            letterSpacing: 0.5,
                          ),
                          dataRowMinHeight: 65,
                          dataRowMaxHeight: 65,
                          dividerThickness: 1,
                          columns: const [
                            DataColumn(label: Text('ID')),
                            DataColumn(label: Text('POSITION TITLE')),
                            DataColumn(label: Text('DEPARTMENT')),
                            DataColumn(label: Text('STATUS')),
                            DataColumn(label: Text('ACTIONS')),
                          ],
                          rows: _filteredPositions.map((position) {
                            final id = position['id']?.toString() ?? '-';
                            final title = position['title']?.toString() ?? '-';
                            final dept = position['department']?.toString() ?? '-';
                            final status = position['status']?.toString() ?? 'Active';
                            
                            final isActive = status.toLowerCase() == 'active';
                            final isHiring = status.toLowerCase() == 'hiring';

                            Color statusColor = Colors.grey;
                            if (isActive) statusColor = Colors.green;
                            if (isHiring) statusColor = _standardGold;

                            return DataRow(
                              cells: [
                                DataCell(Text(id, style: const TextStyle(fontWeight: FontWeight.bold))),
                                DataCell(Text(title)),
                                DataCell(Text(dept)),
                                DataCell(
                                  Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                    decoration: BoxDecoration(
                                      color: statusColor.withOpacity(0.1),
                                      border: Border.all(color: statusColor),
                                      borderRadius: BorderRadius.zero,
                                    ),
                                    child: Text(
                                      status.toUpperCase(), 
                                      style: TextStyle(
                                        color: statusColor,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 11,
                                        letterSpacing: 0.5,
                                      )
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      TextButton.icon(
                                        onPressed: () async {
                                          final result = await showDialog<bool>(
                                            context: context,
                                            builder: (_) => PositionEntryDialog(positionToEdit: position),
                                          );
                                          if (result == true) {
                                            _triggerRefresh();
                                          }
                                        },
                                        icon: const Icon(Icons.edit_rounded, size: 16),
                                        label: const Text('EDIT', style: TextStyle(fontWeight: FontWeight.bold)),
                                        style: TextButton.styleFrom(
                                          foregroundColor: _darkGreen,
                                          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                        ),
                                      ),
                                      const SizedBox(width: 8),
                                      TextButton.icon(
                                        onPressed: () => _deletePosition(int.parse(id)),
                                        icon: const Icon(Icons.delete_outline_rounded, size: 16),
                                        label: const Text('DELETE', style: TextStyle(fontWeight: FontWeight.bold)),
                                        style: TextButton.styleFrom(
                                          foregroundColor: Colors.redAccent,
                                          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            );
                          }).toList(),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// =====================================================================
// ADD / EDIT POSITION DIALOG
// =====================================================================
class PositionEntryDialog extends StatefulWidget {
  final Map<String, dynamic>? positionToEdit;

  const PositionEntryDialog({super.key, this.positionToEdit});

  @override
  State<PositionEntryDialog> createState() => _PositionEntryDialogState();
}

class _PositionEntryDialogState extends State<PositionEntryDialog> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _deptController = TextEditingController();
  
  String _selectedStatus = 'Active';
  final List<String> _statusOptions = ['Active', 'Hiring', 'Closed'];
  
  bool _isLoading = false;
  String get _baseUrl => '${ApiClient.baseUrl}/api/positions_router.php';

  @override
  void initState() {
    super.initState();
    if (widget.positionToEdit != null) {
      _titleController.text = widget.positionToEdit!['title']?.toString() ?? '';
      _deptController.text = widget.positionToEdit!['department']?.toString() ?? '';
      
      final status = widget.positionToEdit!['status']?.toString() ?? 'Active';
      if (_statusOptions.contains(status)) {
        _selectedStatus = status;
      }
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _deptController.dispose();
    super.dispose();
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);

    try {
      final payload = {
        'title': _titleController.text.trim(),
        'department': _deptController.text.trim(),
        'status': _selectedStatus,
      };

      http.Response response;
      
      if (widget.positionToEdit == null) {
        // Create
        response = await http.post(
          Uri.parse(_baseUrl),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode(payload),
        );
      } else {
        // Update
        final id = widget.positionToEdit!['id'];
        response = await http.put(
          Uri.parse('$_baseUrl/$id'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode(payload),
        );
      }

      if (mounted) {
        setState(() => _isLoading = false);
        
        if (response.statusCode == 200 || response.statusCode == 201) {
          ApiClient.announceSuccessfulMutation(
            response.request?.url ?? Uri.parse(_baseUrl),
          );
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(widget.positionToEdit == null ? 'Position created successfully.' : 'Position updated successfully.'),
              backgroundColor: _darkGreen,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
              behavior: SnackBarBehavior.floating,
            ),
          );
          Navigator.of(context).pop(true); // Return true to trigger refresh
        } else {
          throw Exception('Failed to save data. Server returned ${response.statusCode}');
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: $e'),
            backgroundColor: Colors.redAccent,
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.positionToEdit != null;
    final compact = MediaQuery.sizeOf(context).width < 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 ? MediaQuery.sizeOf(context).width - 24 : 500, maxHeight: MediaQuery.sizeOf(context).height * .9),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Header
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 14 : 24, vertical: 16),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    isEditing ? 'EDIT POSITION' : 'ADD NEW POSITION',
                    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(),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),

            // Form
            Flexible(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 14 : 24.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildLabel('POSITION TITLE'),
                      TextFormField(
                        controller: _titleController,
                        enabled: !_isLoading,
                        decoration: _buildInputDecoration('e.g., Head of IT', Icons.work_outline_rounded),
                        validator: (value) => value == null || value.isEmpty ? 'Title is required' : null,
                      ),
                      const SizedBox(height: 20),

                      _buildLabel('DEPARTMENT'),
                      TextFormField(
                        controller: _deptController,
                        enabled: !_isLoading,
                        decoration: _buildInputDecoration('e.g., Computer Science', Icons.business_rounded),
                        validator: (value) => value == null || value.isEmpty ? 'Department is required' : null,
                      ),
                      const SizedBox(height: 20),

                      _buildLabel('STATUS'),
                      DropdownButtonFormField<String>(
                        initialValue: _selectedStatus,
                        decoration: _buildInputDecoration('', Icons.flag_rounded),
                        items: _statusOptions.map((status) {
                          return DropdownMenuItem(
                            value: status,
                            child: Text(status, style: const TextStyle(fontWeight: FontWeight.w600)),
                          );
                        }).toList(),
                        onChanged: _isLoading ? null : (value) {
                          setState(() {
                            if (value != null) _selectedStatus = value;
                          });
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // Footer
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 12 : 24, vertical: 12),
              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(),
                    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.icon(
                    onPressed: _isLoading ? null : _submitForm,
                    icon: _isLoading 
                        ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : const Icon(Icons.save_rounded, color: Colors.white),
                    label: Text(
                      _isLoading ? 'SAVING...' : 'SAVE POSITION',
                      style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _standardGold,
                      foregroundColor: Colors.white,
                      elevation: 0,
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLabel(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Text(
        text,
        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: _darkGreen, letterSpacing: 1.0),
      ),
    );
  }

  InputDecoration _buildInputDecoration(String hint, IconData icon) {
    return InputDecoration(
      hintText: hint,
      prefixIcon: Icon(icon, color: Colors.grey),
      filled: true,
      fillColor: Colors.white,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      border: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
      focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _darkGreen, width: 2)),
      errorBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.redAccent, width: 1)),
      focusedErrorBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.redAccent, width: 2)),
    );
  }
}
