import 'package:flutter/material.dart';
import 'business_section.dart';
import 'pages/analytics_page.dart';
import 'pages/enrollments_page.dart';
import 'pages/overview_page.dart';
import 'pages/programs_page.dart';
import 'pages/schools_page.dart';
import 'pages/student_performance_page.dart';
import 'services/business_department_service.dart';
import 'widgets/business_ui.dart';
import 'widgets/business_workspace_header.dart';
import 'widgets/business_workspace_menu.dart';

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

  @override
  State<BusinessDepartmentTab> createState() => _BusinessDepartmentTabState();
}

class _BusinessDepartmentTabState extends State<BusinessDepartmentTab> {
  final BusinessDepartmentService _service = BusinessDepartmentService();

  Map<String, dynamic> _data = {};
  BusinessSection _section = BusinessSection.overview;
  bool _loading = true;
  bool _refreshing = false;
  bool _menuOpen = false;
  bool _headerExpanded = false;
  String _error = '';
  String _schoolFilter = '';
  String _programFilter = '';
  String _yearFilter = '';

  List<Map<String, dynamic>> _maps(dynamic value) => value is List
      ? value.whereType<Map>().map((row) => Map<String, dynamic>.from(row)).toList()
      : <Map<String, dynamic>>[];

  List<Map<String, dynamic>> get _schools => _maps(_data['schools']);
  List<Map<String, dynamic>> get _programs => _maps(_data['programs']);
  List<Map<String, dynamic>> get _enrollments => _maps(_data['enrollments']);
  List<Map<String, dynamic>> get _performanceIntakes => _maps(_data['performance_intakes']);
  List<Map<String, dynamic>> get _trend => _maps(_data['trend']);
  List<dynamic> get _years => _data['years'] is List ? _data['years'] as List : <dynamic>[];
  Map<String, dynamic> get _summary => _data['summary'] is Map
      ? Map<String, dynamic>.from(_data['summary'])
      : <String, dynamic>{};

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

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _refreshing = true;
      if (_data.isEmpty) _loading = true;
      _error = '';
    });
    try {
      final result = await _service.request('overview', query: {
        if (_schoolFilter.isNotEmpty) 'school_id': _schoolFilter,
        if (_programFilter.isNotEmpty) 'program_id': _programFilter,
        if (_yearFilter.isNotEmpty) 'year': _yearFilter,
      });
      if (!mounted) return;
      setState(() {
        _data = result;
        _loading = false;
        _refreshing = false;
      });
    } catch (error) {
      if (!mounted) return;
      setState(() {
        _error = error.toString().replaceFirst('Bad state: ', '');
        _loading = false;
        _refreshing = false;
      });
    }
  }

  void _open(BusinessSection section) {
    setState(() {
      _section = section;
      _menuOpen = false;
    });
  }

  void _showMessage(String message, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(message),
      backgroundColor: error ? const Color(0xFF9F2D27) : businessGreenDark,
      behavior: SnackBarBehavior.floating,
    ));
  }

  InputDecoration _fieldDecoration(String label) => InputDecoration(
    labelText: label,
    isDense: true,
    filled: true,
    fillColor: Colors.white,
    border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
    enabledBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: businessLine)),
    focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: businessGreen, width: 1.5)),
  );

  Widget _textField(TextEditingController controller, String label, {bool numeric = false}) => TextField(
    controller: controller,
    keyboardType: numeric ? TextInputType.number : TextInputType.text,
    decoration: _fieldDecoration(label),
  );

  Future<void> _form(String title, List<Widget> fields, Future<void> Function() save) async {
    await showDialog<void>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        title: Text(title, style: const TextStyle(color: businessGreen, fontWeight: FontWeight.w800)),
        content: SizedBox(
          width: 440,
          child: SingleChildScrollView(child: Column(
            mainAxisSize: MainAxisSize.min,
            children: fields.expand((field) => [field, const SizedBox(height: 12)]).toList(),
          )),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('CANCEL')),
          ElevatedButton(
            onPressed: () async {
              try {
                await save();
                if (dialogContext.mounted) Navigator.pop(dialogContext);
                await _load();
              } catch (error) {
                _showMessage(error.toString().replaceFirst('Bad state: ', ''), error: true);
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: businessGreen, foregroundColor: Colors.white,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero)),
            child: const Text('SAVE'),
          ),
        ],
      ),
    );
  }

  Future<void> _addSchool() async {
    final name = TextEditingController();
    final code = TextEditingController();
    await _form('Create School', [_textField(name, 'School name'), _textField(code, 'School code (optional)')], () async {
      if (name.text.trim().isEmpty) throw StateError('Enter a school name.');
      await _service.request('create_school', body: {'school_name': name.text.trim(), 'school_code': code.text.trim()});
      if (mounted) setState(() => _section = BusinessSection.schools);
    });
    name.dispose();
    code.dispose();
  }

  Future<void> _addProgram() async {
    if (_schools.isEmpty) {
      _showMessage('Create a school before adding a program.');
      return;
    }
    final name = TextEditingController();
    final code = TextEditingController();
    var schoolId = businessNumber(_schools.first['id']);
    await _form('Create Program', [
      StatefulBuilder(builder: (context, setDialog) => DropdownButtonFormField<int>(
        value: schoolId,
        isExpanded: true,
        decoration: _fieldDecoration('School'),
        items: _schools.map((school) => DropdownMenuItem(
          value: businessNumber(school['id']), child: Text(businessText(school['school_name']), overflow: TextOverflow.ellipsis))).toList(),
        onChanged: (value) => setDialog(() => schoolId = value ?? schoolId),
      )),
      _textField(name, 'Program name'),
      _textField(code, 'Program code (optional)'),
    ], () async {
      if (name.text.trim().isEmpty) throw StateError('Enter a program name.');
      await _service.request('create_program', body: {
        'school_id': schoolId,
        'program_name': name.text.trim(),
        'program_code': code.text.trim(),
      });
      if (mounted) setState(() => _section = BusinessSection.programs);
    });
    name.dispose();
    code.dispose();
  }

  Future<void> _addEnrollment() async {
    if (_programs.isEmpty) {
      _showMessage('Create a program before entering intake numbers.');
      return;
    }
    final intake = TextEditingController();
    final year = TextEditingController(text: DateTime.now().year.toString());
    final male = TextEditingController(text: '0');
    final female = TextEditingController(text: '0');
    var programId = businessNumber(_programs.first['id']);
    await _form('Enter Intake Enrollment', [
      StatefulBuilder(builder: (context, setDialog) => DropdownButtonFormField<int>(
        value: programId,
        isExpanded: true,
        decoration: _fieldDecoration('Program'),
        items: _programs.map((program) => DropdownMenuItem(
          value: businessNumber(program['id']),
          child: Text('${businessText(program['school_name'])} • ${businessText(program['program_name'])}', overflow: TextOverflow.ellipsis),
        )).toList(),
        onChanged: (value) => setDialog(() => programId = value ?? programId),
      )),
      _textField(intake, 'Intake name (e.g. January or September)'),
      _textField(year, 'Intake year', numeric: true),
      Row(children: [
        Expanded(child: _textField(male, 'Male students', numeric: true)),
        const SizedBox(width: 10),
        Expanded(child: _textField(female, 'Female students', numeric: true)),
      ]),
      const Text('Saving the same program, intake and year updates its existing totals.', style: TextStyle(color: businessMuted, fontSize: 12)),
    ], () async {
      final intakeYear = int.tryParse(year.text.trim());
      final maleCount = int.tryParse(male.text.trim());
      final femaleCount = int.tryParse(female.text.trim());
      if (intake.text.trim().isEmpty || intakeYear == null || maleCount == null || femaleCount == null || maleCount < 0 || femaleCount < 0) {
        throw StateError('Enter a valid intake, year and non-negative student counts.');
      }
      await _service.request('save_enrollment', body: {
        'program_id': programId,
        'intake_year': intakeYear,
        'intake_name': intake.text.trim(),
        'male_count': maleCount,
        'female_count': femaleCount,
      });
    });
    intake.dispose();
    year.dispose();
    male.dispose();
    female.dispose();
  }

  Widget _page() {
    switch (_section) {
      case BusinessSection.overview:
        return BusinessOverviewPage(
          key: const ValueKey('overview'), summary: _summary, trend: _trend, schools: _schools, programs: _programs,
          onOpenSchools: () => _open(BusinessSection.schools),
          onOpenPrograms: () => _open(BusinessSection.programs),
          onOpenEnrollments: () => _open(BusinessSection.enrollments),
          onOpenAnalytics: () => _open(BusinessSection.analytics),
        );
      case BusinessSection.schools:
        return BusinessSchoolsPage(key: const ValueKey('schools'), schools: _schools, programs: _programs, onAdd: _addSchool);
      case BusinessSection.programs:
        return BusinessProgramsPage(key: const ValueKey('programs'), programs: _programs, onAdd: _addProgram);
      case BusinessSection.analytics:
        return BusinessAnalyticsPage(
          key: const ValueKey('analytics'), summary: _summary, trend: _trend, schools: _schools, programs: _programs, years: _years,
          schoolId: _schoolFilter, programId: _programFilter, year: _yearFilter,
          onSchool: (value) => setState(() { _schoolFilter = value ?? ''; _programFilter = ''; }),
          onProgram: (value) => setState(() => _programFilter = value ?? ''),
          onYear: (value) => setState(() => _yearFilter = value ?? ''),
          onApply: _load,
        );
      case BusinessSection.enrollments:
        return BusinessEnrollmentsPage(
          key: const ValueKey('enrollments'), records: _enrollments, schools: _schools, programs: _programs, years: _years,
          schoolId: _schoolFilter, programId: _programFilter, year: _yearFilter,
          onSchool: (value) => setState(() { _schoolFilter = value ?? ''; _programFilter = ''; }),
          onProgram: (value) => setState(() => _programFilter = value ?? ''),
          onYear: (value) => setState(() => _yearFilter = value ?? ''),
          onApply: _load,
          onAdd: _addEnrollment,
        );
      case BusinessSection.studentPerformance:
        return BusinessStudentPerformancePage(
          key: const ValueKey('student-performance'),
          programs: _programs,
          intakes: _performanceIntakes,
          onSave: (record) async {
            await _service.request('save_student_performance', body: record);
            await _load();
          },
        );
    }
  }

  @override
  Widget build(BuildContext context) => LayoutBuilder(builder: (context, constraints) {
    final width = constraints.maxWidth;
    final drawerWidth = width < 360 ? width : (width < 680 ? width * .86 : 300.0);
    return Container(
      color: businessCanvas,
      child: Column(children: [
        BusinessWorkspaceHeader(
          section: _section,
          expanded: _headerExpanded,
          refreshing: _refreshing && !_loading,
          onMenu: () => setState(() => _menuOpen = true),
          onToggle: () => setState(() => _headerExpanded = !_headerExpanded),
          onRefresh: _load,
        ),
        Expanded(child: Stack(children: [
          Positioned.fill(child: Padding(
            padding: EdgeInsets.all(width < 600 ? 12 : 18),
            child: _loading
                ? const Center(child: CircularProgressIndicator(color: businessGreen, strokeWidth: 2.5))
                : _error.isNotEmpty && _data.isEmpty
                    ? Center(child: ConstrainedBox(
                        constraints: const BoxConstraints(maxWidth: 420),
                        child: Column(mainAxisSize: MainAxisSize.min, children: [
                          const Icon(Icons.cloud_off_outlined, color: businessMuted, size: 38),
                          const SizedBox(height: 10),
                          Text(_error, textAlign: TextAlign.center, style: const TextStyle(color: businessMuted)),
                          const SizedBox(height: 12),
                          OutlinedButton.icon(onPressed: _load, icon: const Icon(Icons.refresh), label: const Text('TRY AGAIN')),
                        ]),
                      ))
                    : AnimatedSwitcher(
                        duration: const Duration(milliseconds: 280),
                        reverseDuration: const Duration(milliseconds: 220),
                        switchInCurve: Curves.easeOutCubic,
                        switchOutCurve: Curves.easeInCubic,
                        transitionBuilder: (child, animation) => FadeTransition(
                          opacity: animation,
                          child: SlideTransition(
                            position: Tween<Offset>(begin: const Offset(.018, 0), end: Offset.zero).animate(animation),
                            child: child,
                          ),
                        ),
                        child: KeyedSubtree(key: ValueKey(_section), child: _page()),
                      ),
          )),
          BusinessWorkspaceMenu(
            open: _menuOpen,
            width: drawerWidth,
            selected: _section,
            onClose: () => setState(() => _menuOpen = false),
            onSelect: _open,
          ),
        ])),
      ]),
    );
  });
}
