import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/pharmacy-intervention-model/nursing_station.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../../../widgets/shared/app_texts_widget.dart';
import '../../patients/profile/soap_update_vida_plus/assessment/widget/empty_dropdown.dart';

class PharmacyInterventionDialog extends StatefulWidget {
  final Function(
      String, // dataFrom
      String, // dateTo
      String, // admissionNumber
      String, // patient ID
      NursingStationEntity?, // nursingStation
      ) onDispose;

  final String dateFrom;
  final String dateTo;
  final String admissionNumber;
  final String patientID;
  final NursingStationEntity? nursingStation;
  final NursingStation? station;

  const PharmacyInterventionDialog({super.key,
    required this.onDispose,
    required this.dateFrom,
    required this.dateTo,
    required this.admissionNumber,
    required this.patientID,
    required this.nursingStation,
    required this.station,
  });

  @override
  State<PharmacyInterventionDialog> createState() =>
      _PharmacyInterventionDialogState();
}

class _PharmacyInterventionDialogState
    extends State<PharmacyInterventionDialog> {
  final TextEditingController admissionNumber = TextEditingController();
   NursingStationEntity? nursingStation = null;

  final TextEditingController patientId = TextEditingController();

  String dateFrom = '';

  String dateTo = '';

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

  void initData() {
    admissionNumber.text = (widget.admissionNumber == '0')?'':widget.admissionNumber;
    nursingStation = widget.nursingStation;
    patientId.text = (widget.patientID == '0' )?'':widget.patientID;
    dateTo = getDateString(widget.dateTo);
    dateFrom = getDateString(widget.dateFrom);
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              IconButton(
                icon: Icon(Icons.close),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              SizedBox(height: 8,),
              nursingStationView,
              SizedBox(
                height: 4,
              ),
              _titleAndTextField(TranslationBase
                  .of(context)
                  .admissionNumber,
                  admissionNumber, TextInputType.text),
              SizedBox(
                height: 4,
              ),
              _titleAndTextField(TranslationBase
                  .of(context)
                  .patientID, patientId,
                  TextInputType.number),
              SizedBox(
                height: 4,
              ),
              _dateSelection(TranslationBase
                  .of(context)
                  .dateFrom, (date) {
                DateTime? fromDate = getDate(date);
                DateTime? toDate = getDate(dateTo);
                if (toDate == null) {
                  setState(() {
                    dateFrom = date;
                  });
                  return;
                }
                if (fromDate!.compareTo(toDate!) == 1) {
                  setState(() {
                    dateFrom = date;
                    dateTo = '';
                  });
                  return;
                }
                setState(() {
                  dateFrom = date;
                });
              }, dateFrom, false),
              SizedBox(
                height: 4,
              ),
              _dateSelection(TranslationBase
                  .of(context)
                  .dateTo, (date) {
                setState(() {
                  dateTo = date;
                });
              }, dateTo, true, selectedFromDate: dateFrom),
              SizedBox(
                height: 8,
              ),
              Row(children: [
                Expanded(
                  child: AppButton(
                    title: TranslationBase
                        .of(context)
                        .search,
                    hasBorder: true,
                    borderColor: Color(0xFFB8382B),
                    color: AppGlobal.appRedColor,
                    fontColor: Colors.white,
                    onPressed: () async {
                      //(dateFrom, dateTo, admissionNumber, patientId, nursingStation)
                      widget.onDispose(dateFrom, dateTo, admissionNumber.text,
                          patientId.text, nursingStation);
                    },
                  ),
                ),
              ]),
            ],
          ),
        ),
      ),
    );
  }

  Widget _dateSelection(String title, Function(String) onDateSelected,
      String selectedDate, bool isToDateSelection,{String? selectedFromDate}) {
    return GestureDetector(
      onTap: () => _selectDate(onDateSelected,
          (isToDateSelection == true) ? selectedDate : "", isToDateSelection,
          selectedFromDate: selectedFromDate),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(title),
          Expanded(
            child: ListTile(
              title: Text(
                selectedDate,
              ),
              trailing: Icon(Icons.arrow_drop_down_outlined),
            ),
          )
        ],
      ),
    );
  }

  Future _selectDate(Function(String) updateDate , String date, bool toDateSelection, {String? selectedFromDate}) async {
    DateTime? dateTime = getDate(date);
    DateTime? fromDate = getDate(selectedFromDate??'');
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: date.isNotEmpty ? getDate(date) : fromDate != null
            ? fromDate
            : DateTime.now(),
        firstDate: (toDateSelection && fromDate != null) ? fromDate : ((date
            .isNotEmpty && dateTime != null)) ? dateTime : DateTime(DateTime
            .now()
            .year - 150),
        lastDate: DateTime(DateTime
            .now()
            .year + 150),
        initialEntryMode: DatePickerEntryMode.calendar,
        builder: (_, child) {
          return Theme(
            data: ThemeData.light().copyWith(
              colorScheme: ColorScheme.fromSwatch(
                primarySwatch: Colors.red,
                accentColor: AppGlobal.appRedColor,
              ),
              dialogBackgroundColor: Colors.white,
            ),
            child: child!,
          );
        });
    if (picked != null) {
      updateDate(getFormattedDate(picked));
    }
    // }
  }

  Widget _titleAndTextField(String title, TextEditingController controller,
      TextInputType? inputType) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(title),
        Expanded(
          child: TextFormField(
            keyboardType: inputType,
            decoration: InputDecoration(
              hintText: '',
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
              contentPadding: EdgeInsetsDirectional.only(start: 10.0),
            ),
            textAlign: TextAlign.end,
            controller: controller,
          ),
        )
      ],
    );
  }

  void initFromDate() {
    var time = DateTime.now();
    dateFrom = getFormattedDate(time);
  }

  String getFormattedDate(DateTime time) {
    return DateFormat('yyyy-MM-dd').format(time);
  }

  String getDateString(String dateTime) {
    if (dateTime.isEmpty) return '';
   DateTime? now = getDate(dateTime);
   if(now == null ) return '';
    return DateFormat('yyyy-MM-dd').format(now);
  }

  DateTime? getDate(String dateTime){
    if (dateTime.isEmpty) return null;
    List<String> splitedDate = dateTime.split('-');
    DateTime now = DateTime(int.parse(splitedDate[0]),
        int.parse(splitedDate[1]), int.parse(splitedDate[2]));
    return now;
  }

  Widget get nursingStationView =>
      Row(
          children: [
        Text(TranslationBase
            .of(context)
            .nursingStation,),
        SizedBox(width: 10,),
        widget.station?.entityList?.isEmpty == true ? Expanded(
            child: EmptyDropDown())
            : Expanded(
          child: DropdownSearch<NursingStationEntity>(
              itemAsString:(item){
                return item.description??'';
              } ,
            items:  widget.station?.entityList ?? [],
            popupProps: PopupProps.menu(
              showSearchBox: true,
              searchDelay: Duration(microseconds: 100),
              searchFieldProps: TextFieldProps(
                  decoration: InputDecoration(
                    border: UnderlineInputBorder(),
                    hintText: TranslationBase.of(context).search
                  )
              )
            ),
            dropdownButtonProps: DropdownButtonProps(color: AppGlobal.appRedColor,),
            dropdownDecoratorProps: DropDownDecoratorProps(
              textAlignVertical: TextAlignVertical.center,
              dropdownSearchDecoration: InputDecoration(
                border: InputBorder.none
              ),
                baseStyle: TextStyle(
                  fontSize: 14
                )
            ),

              selectedItem: nursingStation == null
                    ? widget.station?.entityList?.first
                    : nursingStation,
                onChanged: (newValue) async {
                  if (newValue != null)
                    setState(() {
                      nursingStation = newValue ;
                    });
                },
          )
          // DropdownButtonHideUnderline(
          //   child: DropdownButton(
          //     dropdownColor: Colors.white,
          //     iconEnabledColor: Colors.black,
          //     icon: Icon(Icons.keyboard_arrow_down),
          //     isExpanded: true,
          //     value: nursingStation == null
          //         ? widget.station?.entityList?.first
          //         : nursingStation,
          //     iconSize: 25,
          //     elevation: 16,
          //     onChanged: (newValue) async {
          //       if (newValue != null)
          //         setState(() {
          //           nursingStation = newValue ;
          //         });
          //     },
          //     items:
          //     widget.station?.entityList?.map((item) {
          //       return DropdownMenuItem(
          //         child: AppText(
          //           item.description ?? '',
          //           fontSize: 14,
          //           letterSpacing: -0.96,
          //           color: AppGlobal.appTextColor,
          //           fontWeight: FontWeight.normal,
          //           textAlign: TextAlign.left,
          //         ),
          //         value: item,
          //       );
          //     }).toList(),
          //   ),
          // ),
        )
      ]);
}