// ignore_for_file: library_private_types_in_public_api, non_constant_identifier_names, use_build_context_synchronously, avoid_print, prefer_const_constructors, no_leading_underscores_for_local_identifiers

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:html_editor_enhanced/html_editor.dart';
import 'package:mwcallcenter/helper/constant.dart';
import 'package:mwcallcenter/models/branch.dart';
import 'package:mwcallcenter/models/departament.dart';
import 'package:mwcallcenter/models/response_d.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mwcallcenter/screens/solicitudes.dart';

import '../methods/api.dart';

class CreateDemand extends StatefulWidget {
  const CreateDemand({Key? key}) : super(key: key);

  @override
  _CreateDemandState createState() => _CreateDemandState();
}

class _CreateDemandState extends State<CreateDemand> {
  final HtmlEditorController controller = HtmlEditorController();
  List<BranchData> sucursales = [];
  List<DepartamentData> departamentos = [];
  List<DepartamentData> _departamentos = [];
  bool disabled = true;

  dynamic SucursalesValue;
  dynamic DepartamentosValue;

  dynamic asunto;
  dynamic solicitud;

  @override
  void initState() {
    super.initState();
    obtenerSucursales();
    obtenerDepartamentos();
  }

  void create_sol() async {
    if (mounted) {
      solicitud = await controller.getText();
      if (asunto == null) {
        if (mounted) {
          errorSnackBar(context, 'Asunto requerido');
        }
      } else {
        final api = API();
        api.init(context);

        SharedPreferences preferences = await SharedPreferences.getInstance();
        final token = preferences.getString('token').toString();
        final data = {
          'asunto': '$asunto',
          'department_id': '$DepartamentosValue',
          'user_id': preferences.getInt('user_id'),
          'client_id': preferences.getInt('user_id'),
          'solicitud': '$solicitud',
        };

        final result =
        await api.postData(route: '/solicitud', data: data, token: token);
        final response = jsonDecode(result.body);
        print(response);

        if (response['status'] == 200) {
          if (mounted) {
            SuccesfullSnackBar(context, 'SOLICITUD GENERADA CON EXITO!');
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                builder: (context) => const Home(),
              ),
            );
          }
        } else {
          if (mounted) {
            errorSnackBar(context, '¡COMPLETA LOS CAMPOS!');
          }
        }
      }
    }
  }

  Future<void> obtenerSucursales() async {
    API().context;
    API().init(context);
    SharedPreferences preferences = await SharedPreferences.getInstance();
    final token = preferences.getString('token').toString();
    final response = await API().getData(route: '/sucursal', token: token);
    final datas = jsonDecode(response.body);
    ResponseD responseD = ResponseD.fromJson(datas);
    BranchData branches = BranchData.fromJsonList(responseD.data);
    setState(() {
      sucursales = branches.toList;
    });
  }

  Future<void> obtenerDepartamentos() async {
    API().context;
    API().init(context);
    SharedPreferences preferences = await SharedPreferences.getInstance();
    final token = preferences.getString('token').toString();
    final response = await API().getData(route: '/departamento', token: token);
    final datas = jsonDecode(response.body);
    ResponseD responseD = ResponseD.fromJson(datas);
    DepartamentData departaments = DepartamentData.fromJsonList(responseD.data);
    setState(() {
      departamentos = departaments.toList;
    });
  }

  void valuechanged(_SucursalesValue) {
    print("Sucursal seleccionada: $_SucursalesValue");
    setState(() {
      SucursalesValue = _SucursalesValue;
      disabled = false;
      _departamentos = departamentos
          .where((departamento) => departamento.branchId == SucursalesValue)
          .toList();
      DepartamentosValue = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Nueva solicitud'),
        backgroundColor: const Color.fromARGB(255, 8, 25, 53),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                builder: (context) => const Home(),
              ),
            );
          },
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              DropdownButtonFormField<dynamic>(
                decoration: InputDecoration(
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(width: 3, color: Colors.blue),
                  ),
                ),
                isExpanded: true,
                hint: const Text('Sucursal'),
                items: sucursales.map<DropdownMenuItem<dynamic>>((sucursal) {
                  return DropdownMenuItem<dynamic>(
                    value: (sucursal.id),
                    child: Text(sucursal.nombre),
                  );
                }).toList(),
                value: SucursalesValue,
                onChanged: (_SucursalesValue) => setState(() {
                  valuechanged(_SucursalesValue);
                }),
              ),
              const SizedBox(
                height: 20,
              ),
              DropdownButtonFormField<dynamic>(
                decoration: InputDecoration(
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(width: 3, color: Colors.blue),
                  ),
                ),
                hint: const Text("Departamentos*"),
                disabledHint: Text("Primero seleccione una sucursal"),
                items: _departamentos
                    .map<DropdownMenuItem<dynamic>>((departament) {
                  return DropdownMenuItem<dynamic>(
                    value: departament.id,
                    child: Text(departament.nombre),
                  );
                }).toList(),
                value: DepartamentosValue,
                onChanged: disabled
                    ? null
                    : (_DepartamentosValue) => setState(() {
                  DepartamentosValue = _DepartamentosValue;
                }),
              ),
              const SizedBox(
                height: 20,
              ),
              TextField(
                decoration: const InputDecoration(
                  hintText: 'MWConsultores de Mexico',
                  labelText: 'Asunto*',
                ),
                onChanged: (value) {
                  setState(() {
                    asunto = value;
                  });
                },
              ),
              SizedBox(
                height: 100,
              ),
            ],
          ),
        ),
      ),
      // Editor de HTML
      HtmlEditor(
        controller: controller,
        htmlEditorOptions: HtmlEditorOptions(
          hint: "Escribe tu solicitud aquí...",
        ),
        htmlToolbarOptions: HtmlToolbarOptions(
          toolbarType: ToolbarType.nativeGrid,
          toolbarPosition: ToolbarPosition.belowEditor,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          create_sol();
        },
        backgroundColor: const Color.fromRGBO(15, 150, 150, 1),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.send),
            SizedBox(height: 4),
            Text('Enviar', style: TextStyle(fontSize: 9)),
          ],
        ),
      ),
    );
  }

}
podrias corregirme esto?