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

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart'; // Make sure this is in your pubspec.yaml

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

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

  @override
  State<DepartmentDrilldownPanel> createState() => _DepartmentDrilldownPanelState();
}

class _DepartmentDrilldownPanelState extends State<DepartmentDrilldownPanel> {
  // Mock list of 20 Departments for Rockview University
  // Removed 'final' so we can add new departments dynamically
  final List<String> _departments = [
    'School of Agriculture',
    'School of Health Sciences',
    'School of Education',
    'School of Business',
    'School of Engineering',
    'School of Humanities',
    'School of Natural Sciences',
    'Directorate of ICT',
    'Admissions & Records',
    'Sports & Recreation',
    'Projects & Infrastructure',
    'Finance Department',
    'Human Resources',
    'Library Services',
    'Student Affairs',
    'Quality Assurance',
    'Marketing & Communications',
    'Security Services',
    'Transport & Logistics',
    'Procurement',
  ];

  int _selectedDeptIndex = 0;

  // Method to display the custom sharp-edged dialog form
  void _showAddDepartmentDialog(BuildContext context) {
    final TextEditingController deptController = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return Dialog(
          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          backgroundColor: Colors.white,
          child: Container(
            width: 400,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade300, width: 1),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Dialog Header
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                  decoration: const BoxDecoration(
                    color: _darkGreen,
                    border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
                  ),
                  child: const Row(
                    children: [
                      Icon(Icons.domain_add_rounded, color: Colors.white, size: 24),
                      SizedBox(width: 12),
                      Text(
                        'ADD NEW DEPARTMENT',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w900,
                          letterSpacing: 1.0,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // Dialog Body
                Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'DEPARTMENT NAME',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          color: Colors.grey.shade700,
                          letterSpacing: 0.5,
                        ),
                      ),
                      const SizedBox(height: 8),
                      TextField(
                        controller: deptController,
                        cursorColor: _standardGold,
                        decoration: InputDecoration(
                          hintText: 'e.g. School of Law',
                          hintStyle: TextStyle(color: Colors.grey.shade400),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                          filled: true,
                          fillColor: Colors.grey.shade50,
                          border: const OutlineInputBorder(
                            borderRadius: BorderRadius.zero,
                          ),
                          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),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                // Dialog Actions
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade50,
                    border: Border(top: BorderSide(color: Colors.grey.shade200, width: 1)),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.of(dialogContext).pop(),
                        style: TextButton.styleFrom(
                          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                        ),
                        child: Text(
                          'CANCEL',
                          style: TextStyle(
                            color: Colors.grey.shade600,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      ElevatedButton(
                        onPressed: () {
                          if (deptController.text.trim().isNotEmpty) {
                            setState(() {
                              // Add to the top of the list and select it
                              _departments.insert(0, deptController.text.trim());
                              _selectedDeptIndex = 0; 
                            });
                            Navigator.of(dialogContext).pop();
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _standardGold,
                          foregroundColor: Colors.white,
                          elevation: 0,
                          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                        ),
                        child: const Text(
                          'SAVE DEPARTMENT',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            letterSpacing: 0.5,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey.shade300, width: 1),
        borderRadius: BorderRadius.zero, // Sharp edges enforced
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // --- LEFT PANEL: DEPARTMENT LIST ---
          Container(
            width: 300,
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              border: Border(right: BorderSide(color: Colors.grey.shade300, width: 1)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: const BoxDecoration(
                    color: _darkGreen,
                    border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'DEPARTMENTS',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.0,
                        ),
                      ),
                      // NEW ADD BUTTON
                      InkWell(
                        onTap: () => _showAddDepartmentDialog(context),
                        child: Container(
                          padding: const EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            border: Border.all(color: _standardGold, width: 1),
                            borderRadius: BorderRadius.zero,
                          ),
                          child: const Icon(
                            Icons.add,
                            color: _standardGold,
                            size: 18,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ListView.separated(
                    itemCount: _departments.length,
                    separatorBuilder: (context, index) => Divider(
                      height: 1,
                      thickness: 1,
                      color: Colors.grey.shade200,
                    ),
                    itemBuilder: (context, index) {
                      final isSelected = _selectedDeptIndex == index;
                      return InkWell(
                        onTap: () {
                          setState(() {
                            _selectedDeptIndex = index;
                          });
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                          decoration: BoxDecoration(
                            color: isSelected ? _standardGold.withOpacity(0.1) : Colors.transparent,
                            border: Border(
                              left: BorderSide(
                                color: isSelected ? _standardGold : Colors.transparent,
                                width: 4,
                              ),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: Text(
                                  _departments[index],
                                  style: TextStyle(
                                    fontSize: 13,
                                    fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                                    color: isSelected ? _darkGreen : Colors.grey.shade800,
                                  ),
                                ),
                              ),
                              if (isSelected)
                                const Icon(Icons.arrow_forward_ios_rounded, size: 14, color: _standardGold),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),

          // --- RIGHT PANEL: KPI DETAILS & CHARTS ---
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(32.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Department Header
                  Text(
                    _departments[_selectedDeptIndex].toUpperCase(),
                    style: const TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.w900,
                      color: _darkGreen,
                      letterSpacing: 1.2,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Current Month Performance vs Targets',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey.shade600,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 32),

                  // KPI Snapshot Cards
                  Row(
                    children: [
                      Expanded(
                        child: _buildKPICard(
                          title: 'KPI 1: Enrollment / Output',
                          actual: '85%',
                          target: '90%',
                          isFailing: true,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: _buildKPICard(
                          title: 'KPI 2: Budget Variance',
                          actual: '+2.4%',
                          target: '0.0%',
                          isFailing: false,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: _buildKPICard(
                          title: 'KPI 3: Project Completion',
                          actual: '92%',
                          target: '85%',
                          isFailing: false,
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 48),

                  // Trend Analysis Chart
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(color: Colors.grey.shade300, width: 1),
                      borderRadius: BorderRadius.zero, // Sharp edges
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade100,
                            border: Border(bottom: BorderSide(color: Colors.grey.shade300, width: 1)),
                          ),
                          child: const Text(
                            '12-MONTH TREND ANALYSIS',
                            style: TextStyle(
                              color: _darkGreen,
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              letterSpacing: 1.0,
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(32.0),
                          child: SizedBox(
                            height: 350,
                            child: _buildTrendChart(),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // --- HELPER: SHARP KPI SNAPSHOT CARD ---
  Widget _buildKPICard({
    required String title,
    required String actual,
    required String target,
    required bool isFailing,
  }) {
    final statusColor = isFailing ? Colors.redAccent : _darkGreen;
    final statusIcon = isFailing ? Icons.warning_rounded : Icons.check_circle_rounded;

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey.shade200, width: 1),
        borderRadius: BorderRadius.zero,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title.toUpperCase(),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade500,
              letterSpacing: 1.0,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                actual,
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w900,
                  color: statusColor,
                ),
              ),
              const SizedBox(width: 8),
              Padding(
                padding: const EdgeInsets.only(bottom: 4.0),
                child: Text(
                  '/ $target target',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey.shade400,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Icon(statusIcon, color: statusColor, size: 16),
              const SizedBox(width: 8),
              Text(
                isFailing ? 'Below Target' : 'On Target',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  color: statusColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // --- HELPER: FL_CHART IMPLEMENTATION ---
  Widget _buildTrendChart() {
    return LineChart(
      LineChartData(
        gridData: FlGridData(
          show: true,
          drawVerticalLine: true,
          horizontalInterval: 20,
          verticalInterval: 1,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: Colors.grey.shade200,
              strokeWidth: 1,
            );
          },
          getDrawingVerticalLine: (value) {
            return FlLine(
              color: Colors.grey.shade200,
              strokeWidth: 1,
            );
          },
        ),
        titlesData: FlTitlesData(
          show: true,
          rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 30,
              interval: 1,
              getTitlesWidget: (value, meta) {
                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                if (value.toInt() >= 0 && value.toInt() < months.length) {
                  return Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      months[value.toInt()],
                      style: TextStyle(color: Colors.grey.shade600, fontSize: 12, fontWeight: FontWeight.bold),
                    ),
                  );
                }
                return const Text('');
              },
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              interval: 20,
              reservedSize: 42,
              getTitlesWidget: (value, meta) {
                return Text(
                  '${value.toInt()}%',
                  style: TextStyle(color: Colors.grey.shade600, fontSize: 12, fontWeight: FontWeight.bold),
                );
              },
            ),
          ),
        ),
        borderData: FlBorderData(
          show: true,
          border: Border.all(color: Colors.grey.shade300, width: 1), // Sharp edges on chart border
        ),
        minX: 0,
        maxX: 11,
        minY: 0,
        maxY: 100,
        lineBarsData: [
          // KPI 1 Line
          LineChartBarData(
            spots: const [
              FlSpot(0, 45), FlSpot(1, 50), FlSpot(2, 55), FlSpot(3, 40),
              FlSpot(4, 60), FlSpot(5, 65), FlSpot(6, 70), FlSpot(7, 60),
              FlSpot(8, 75), FlSpot(9, 80), FlSpot(10, 85), FlSpot(11, 85),
            ],
            isCurved: false, // Strict sharp angles for the line graph to match UI
            color: _standardGold,
            barWidth: 3,
            isStrokeCapRound: false,
            dotData: const FlDotData(show: true),
            belowBarData: BarAreaData(
              show: true,
              color: _standardGold.withOpacity(0.1),
            ),
          ),
          // KPI 2 Line
          LineChartBarData(
            spots: const [
              FlSpot(0, 60), FlSpot(1, 62), FlSpot(2, 58), FlSpot(3, 65),
              FlSpot(4, 68), FlSpot(5, 75), FlSpot(6, 72), FlSpot(7, 80),
              FlSpot(8, 85), FlSpot(9, 82), FlSpot(10, 90), FlSpot(11, 92),
            ],
            isCurved: false,
            color: _darkGreen,
            barWidth: 3,
            isStrokeCapRound: false,
            dotData: const FlDotData(show: true),
            belowBarData: BarAreaData(show: false),
          ),
        ],
      ),
    );
  }
}