import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../app/constant.dart';

class CustomTextField extends StatelessWidget {
  final String hintText;
  final String labelText;
  final bool isPassword;
  final int? minLines;
  final int? maxLines;
  final Widget? suffixIcon;
  final TextInputType? inputType;
  final TextEditingController? controller;
  final TextStyle? hintStyle;
  final TextStyle? labelStyle;
  final TextStyle? style;
  final bool? isDense;
  final bool? disable;
  final Function? onChange;
  final List<TextInputFormatter>? inputFormater;
  final String? initialValue;
  final String? Function(String?)? validator;
  // final String Function(String?)? validator;

  const CustomTextField(
      {super.key,
      required this.hintText,
      required this.labelText,
      this.isPassword = false,
      this.maxLines = 1,
      this.minLines = 1,
      this.suffixIcon,
      this.inputType,
      this.style,
      this.hintStyle,
      this.labelStyle,
      this.isDense,
      this.disable,
      this.onChange,
      this.inputFormater,
      this.initialValue,
      this.validator,
      this.controller});

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      onChanged: (value) {
        if (onChange != null) {
          onChange!(value);
        }
      },
      enabled: disable,
      controller: controller,
      style: style ?? Constant.body2_400(context: context),
      obscureText: isPassword,
      minLines: minLines,
      maxLines: maxLines,
      keyboardType: inputType,
      initialValue: initialValue,
      validator: validator,
      autovalidateMode: AutovalidateMode.always,
      inputFormatters: <TextInputFormatter>[
        if (inputType == TextInputType.number)
          FilteringTextInputFormatter.digitsOnly,
        ...?inputFormater
      ],
      decoration: InputDecoration(
          hintStyle: hintStyle ?? Constant.body2_400(context: context),
          labelStyle: labelStyle ?? Constant.body2_400(context: context),
          fillColor: Constant.primaryBlue,
          labelText: labelText,
          isDense: isDense ?? false,
          contentPadding: isDense == true
              ? EdgeInsets.symmetric(
                  vertical: Constant.getActualY(context: context, y: 8),
                  horizontal: Constant.getActualX(context: context, x: 10))
              : null,

          // isCollapsed: true,
          hintText: hintText,
          suffixIcon: suffixIcon,
          border: OutlineInputBorder(
            borderSide: BorderSide(color: Constant.primaryBlue),
            borderRadius: BorderRadius.circular(8),
          )),
    );
  }
}

class CustomPasswordField extends HookConsumerWidget {
  final String hintText;
  final String labelText;
  final ValueNotifier<bool> isPassword;
  final int? minLines;
  final int? maxLines;
  final Widget? suffixIcon;
  final TextEditingController? controller;
  final String? Function(String?)? validator;

  const CustomPasswordField(
      {super.key,
      required this.hintText,
      required this.labelText,
      required this.isPassword,
      this.maxLines = 1,
      this.minLines = 1,
      this.suffixIcon,
      this.validator,
      this.controller});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return TextFormField(
      controller: controller,
      style: Constant.body2_400(context: context),
      obscureText: isPassword.value,
      minLines: minLines,
      maxLines: maxLines,
      validator: validator,
      autovalidateMode: AutovalidateMode.always,
      decoration: InputDecoration(
          hintStyle: Constant.body2_400(context: context),
          labelStyle: Constant.body2_400(context: context),
          fillColor: Constant.primaryBlue,
          labelText: labelText,
          hintText: hintText,
          suffixIcon: IconButton(
            icon:
                Icon(!isPassword.value ? EvaIcons.eye : EvaIcons.eyeOffOutline),
            onPressed: () {
              isPassword.value = !isPassword.value;
            },
          ),
          border: OutlineInputBorder(
            borderSide: BorderSide(color: Constant.primaryBlue),
            borderRadius: BorderRadius.circular(8),
          )),
    );
  }
}

class CustomDropDownModel {
  String? id;
  String? name;
  String? type;

  CustomDropDownModel({this.id, this.name, this.type});

  CustomDropDownModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    type = json['type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['name'] = name;
    data['type'] = type;
    return data;
  }
}

class CustomDropDown extends HookConsumerWidget {
  const CustomDropDown(
      {super.key,
      required this.data,
      this.selectedData,
      required this.onSelect,
      required this.hintText,
      required this.width,
      required this.loading,
      required this.label});
  final List<CustomDropDownModel> data;
  final ValueNotifier<CustomDropDownModel>? selectedData;
  final Function onSelect;
  final String hintText;
  final bool loading;
  final Widget label;
  final double width;
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedLokal = useState(CustomDropDownModel());
    final key = useState(10000);
    // final selectedLokal = useState(CustomDropDownModel());
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        if (selectedData?.value.id != null) {
          var tempIdx = CustomDropDownModel(id: "-1");
          if (data.isNotEmpty) {
            tempIdx = data
                .firstWhere((element) => element.id == selectedData?.value.id);
          }
          var selectedDataIndex = data.indexOf(tempIdx);
          if (selectedDataIndex != -1) {
            if (data.isNotEmpty) {
              selectedLokal.value = data[selectedDataIndex];
            }
          }
        }
        key.value = key.value + 1;
      });
      return () {};
    }, [selectedData]);
    selectedLokal.addListener(
      () {
        selectedData?.value = selectedLokal.value;
      },
    );
    return DropdownMenu<CustomDropDownModel>(
        key: ValueKey(key.value),
        initialSelection: selectedLokal.value,
        trailingIcon: loading
            ? LoadingAnimationWidget.discreteCircle(
                color: Constant.primaryBlue, size: 20)
            : null,
        width: width,
        hintText: hintText,
        textStyle: Constant.body2_400(context: context),
        inputDecorationTheme: InputDecorationTheme(
            border: OutlineInputBorder(
          borderSide: BorderSide(color: Constant.primaryBlue),
          borderRadius: BorderRadius.circular(8),
        )),
        label: label,
        onSelected: (value) {
          onSelect(value);
          selectedLokal.value = value!;
        },
        dropdownMenuEntries: data
            .map<DropdownMenuEntry<CustomDropDownModel>>(
                (e) => DropdownMenuEntry(value: e, label: e.name ?? ""))
            .toList());

    // return DropdownButton<CustomDropDownModel>(
    //   // value: selectedData?.value,
    //   items: data.length > 0
    //       ? data
    //           .map<DropdownMenuItem<CustomDropDownModel>>(
    //               (e) => DropdownMenuItem(
    //                     child: Text(e.name!),
    //                   ))
    //           .toList()
    //       : [],
    //   onChanged: (value) => onSelect(value),
    // );
  }
}
