// lib/features/admin/tabs/kpi/kpi_data_entry_dialog.dart

import 'package:flutter/material.dart';

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

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

  @override
  State<KpiDataEntryDialog> createState() => _KpiDataEntryDialogState();
}

class _KpiDataEntryDialogState extends State<KpiDataEntryDialog> {
  // ---------------------------------------------------------------------------
  // MOCK DATABASE REPRESENTING THE EXCEL SHEET ARCHITECTURE
  // ---------------------------------------------------------------------------
  final Map<String, List<Map<String, dynamic>>> _kpiDatabase = {
    'Marketing': [
      {'name': 'Lead conversion rate', 'formula': 'Applications/Inquiries*100', 'target': '70', 'unit': '%'},
      {'name': 'Brand reach', 'formula': 'Monthly engagements', 'target': '10000', 'unit': 'Engagements'},
      {'name': 'Cost per lead', 'formula': 'Marketing spend/Leads', 'target': '50', 'unit': 'ZMW'},
    ],
    'Admissions': [
      {'name': 'Application-to-enrollment rate', 'formula': 'Enrollments/Applications*100', 'target': '70', 'unit': '%'},
      {'name': 'Yield rate', 'formula': 'Registered/Accepted*100', 'target': '75', 'unit': '%'},
      {'name': 'Processing time', 'formula': 'Avg days', 'target': '14', 'unit': 'Days'},
    ],
    'Exams': [
      {'name': 'Results turnaround time', 'formula': 'Days to release', 'target': '14', 'unit': 'Days'},
      {'name': 'Malpractice rate', 'formula': 'Cases/Students*1000', 'target': '2', 'unit': 'Cases'},
      {'name': 'Exam completion rate', 'formula': 'Students sat/Registered*100', 'target': '95', 'unit': '%'},
    ],
    'Library': [
      {'name': 'Utilization rate', 'formula': 'Visits/day', 'target': '500', 'unit': 'Visits'},
      {'name': 'E-resource usage', 'formula': 'Downloads/month', 'target': '5000', 'unit': 'Downloads'},
      {'name': 'Book-to-student ratio', 'formula': 'Books/Students', 'target': '5', 'unit': 'Ratio'},
    ],
    'Accounts': [
      {'name': 'Fee collection rate', 'formula': 'Collected/Billed*100', 'target': '95', 'unit': '%'},
      {'name': 'Budget variance', 'formula': '(Actual-Budget)/Budget*100', 'target': '5', 'unit': '%'},
      {'name': 'Audit findings', 'formula': 'Unresolved issues', 'target': '0', 'unit': 'Issues'},
    ],
    'School of Natural Science': [
      {'name': 'Lab usage rate', 'formula': 'Used hours/Scheduled*100', 'target': '90', 'unit': '%'},
      {'name': 'Research grants', 'formula': 'Funding secured', 'target': '50000', 'unit': 'ZMW'},
      {'name': 'Project completion', 'formula': 'Completed/Total*100', 'target': '95', 'unit': '%'},
    ],
  };

  final List<String> _months = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];

  String? _selectedDepartment;
  String? _selectedKpiName;
  String? _selectedMonth;
  Map<String, dynamic>? _activeKpiDetails;

  final TextEditingController _actualValueController = TextEditingController();

  void _onDepartmentChanged(String? newDept) {
    setState(() {
      _selectedDepartment = newDept;
      _selectedKpiName = null; // Reset KPI selection when dept changes
      _activeKpiDetails = null;
      _actualValueController.clear();
    });
  }

  void _onKpiChanged(String? newKpi) {
    setState(() {
      _selectedKpiName = newKpi;
      if (_selectedDepartment != null && newKpi != null) {
        _activeKpiDetails = _kpiDatabase[_selectedDepartment]!
            .firstWhere((kpi) => kpi['name'] == newKpi);
      }
      _actualValueController.clear();
    });
  }

  void _submitData() {
    if (_selectedDepartment == null || _selectedKpiName == null || _selectedMonth == null || _actualValueController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please complete all fields before submitting.'),
          backgroundColor: Colors.redAccent,
          behavior: SnackBarBehavior.floating,
        ),
      );
      return;
    }

    // In a real app, this would POST to your FastAPI backend to the `kpi_records` table
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('$_selectedKpiName data for $_selectedMonth recorded successfully.'),
        backgroundColor: _darkGreen,
        behavior: SnackBarBehavior.floating,
      ),
    );

    // Reset fields after successful entry
    setState(() {
      _actualValueController.clear();
      _selectedKpiName = null;
      _activeKpiDetails = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 800, // Constrain width for a focused data entry experience
        margin: const EdgeInsets.symmetric(horizontal: 24),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade300, width: 1),
          borderRadius: BorderRadius.zero, // Strict sharp edges
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 15,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // --- HEADER ---
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 24),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 4)),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'MONTHLY KPI DATA ENTRY',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.w900,
                      letterSpacing: 1.5,
                    ),
                  ),
                  SizedBox(height: 4),
                  Text(
                    'Select a department and KPI to log actual performance metrics.',
                    style: TextStyle(
                      color: Colors.white70,
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),

            // --- FORM BODY ---
            Padding(
              padding: const EdgeInsets.all(32.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Row 1: Department & Month Selection
                  Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: _buildDropdownField(
                          label: 'DEPARTMENT',
                          hint: 'Select Department',
                          value: _selectedDepartment,
                          items: _kpiDatabase.keys.toList(),
                          onChanged: _onDepartmentChanged,
                        ),
                      ),
                      const SizedBox(width: 24),
                      Expanded(
                        flex: 1,
                        child: _buildDropdownField(
                          label: 'REPORTING MONTH',
                          hint: 'Select Month',
                          value: _selectedMonth,
                          items: _months,
                          onChanged: (val) => setState(() => _selectedMonth = val),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 32),

                  // Row 2: KPI Selection (Dynamic based on Department)
                  _buildDropdownField(
                    label: 'KEY PERFORMANCE INDICATOR (KPI)',
                    hint: _selectedDepartment == null 
                        ? 'Please select a department first' 
                        : 'Select specific KPI to update',
                    value: _selectedKpiName,
                    items: _selectedDepartment != null 
                        ? _kpiDatabase[_selectedDepartment]!.map((kpi) => kpi['name'] as String).toList()
                        : [],
                    onChanged: _selectedDepartment != null ? _onKpiChanged : null,
                  ),

                  const SizedBox(height: 32),

                  // Dynamic Context Panel (Only shows when KPI is selected)
                  if (_activeKpiDetails != null) ...[
                    Container(
                      padding: const EdgeInsets.all(24),
                      // Change this part inside your Container's decoration:
                    decoration: BoxDecoration(
                      color: Colors.grey.shade50,
                      border: Border(
                        top: BorderSide(color: Colors.grey.shade200, width: 1),
                        right: BorderSide(color: Colors.grey.shade200, width: 1),
                        bottom: BorderSide(color: Colors.grey.shade200, width: 1),
                        left: const BorderSide(color: _standardGold, width: 4), // <--- This creates the independent left accent border
                      ),
                    ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text('MEASUREMENT FORMULA', style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: Colors.grey)),
                                const SizedBox(height: 4),
                                Text(
                                  _activeKpiDetails!['formula'],
                                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: _darkGreen),
                                ),
                              ],
                            ),
                          ),
                          Container(width: 1, height: 40, color: Colors.grey.shade300, margin: const EdgeInsets.symmetric(horizontal: 24)),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text('MONTHLY TARGET', style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: Colors.grey)),
                                const SizedBox(height: 4),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Text(
                                      _activeKpiDetails!['target'].toString(),
                                      style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: _darkGreen),
                                    ),
                                    const SizedBox(width: 4),
                                    Padding(
                                      padding: const EdgeInsets.only(bottom: 2.0),
                                      child: Text(
                                        _activeKpiDetails!['unit'],
                                        style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.grey.shade600),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 32),

                    // Data Entry Field
                    const Text(
                      'ACTUAL PERFORMANCE METRIC',
                      style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.black87, letterSpacing: 0.5),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _actualValueController,
                            keyboardType: const TextInputType.numberWithOptions(decimal: true),
                            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                            cursorColor: _standardGold,
                            decoration: InputDecoration(
                              hintText: 'Enter achieved value...',
                              filled: true,
                              fillColor: Colors.white,
                              contentPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                              suffixIcon: Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      _activeKpiDetails!['unit'],
                                      style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey.shade500),
                                    ),
                                  ],
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.zero,
                                borderSide: BorderSide(color: Colors.grey.shade300, width: 1),
                              ),
                              focusedBorder: const OutlineInputBorder(
                                borderRadius: BorderRadius.zero,
                                borderSide: BorderSide(color: _standardGold, width: 2),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],

                  const SizedBox(height: 48),

                  // Submit Button
                  SizedBox(
                    width: double.infinity,
                    height: 56,
                    child: ElevatedButton.icon(
                      onPressed: _submitData,
                      icon: const Icon(Icons.check_circle_outline_rounded, color: Colors.white),
                      label: const Text(
                        'SUBMIT KPI RECORD',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.2,
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _standardGold,
                        elevation: 0,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.zero, // Sharp edges
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // --- HELPER WIDGET: SHARP DROPDOWN ---
  Widget _buildDropdownField({
    required String label,
    required String hint,
    required String? value,
    required List<String> items,
    required void Function(String?)? onChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
            letterSpacing: 0.5,
          ),
        ),
        const SizedBox(height: 8),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
            color: onChanged == null ? Colors.grey.shade100 : Colors.white,
            border: Border.all(color: Colors.grey.shade300, width: 1),
            borderRadius: BorderRadius.zero, // Sharp edges
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: value,
              hint: Text(hint, style: TextStyle(color: Colors.grey.shade500, fontSize: 14)),
              isExpanded: true,
              icon: const Icon(Icons.keyboard_arrow_down_rounded, color: _darkGreen),
              dropdownColor: Colors.white,
              style: const TextStyle(
                color: Colors.black87,
                fontSize: 15,
                fontWeight: FontWeight.w500,
              ),
              items: items.map((String item) {
                return DropdownMenuItem<String>(
                  value: item,
                  child: Text(item),
                );
              }).toList(),
              onChanged: onChanged,
            ),
          ),
        ),
      ],
    );
  }
}