import 'dart:async';
import 'package:flutter/material.dart';
import '../const/app_dimens.dart';
import '../const/app_theme.dart';
import '../const/colors.dart';
import '../localization/language/languages.dart';
import '../network/api/api_utils.dart';
import '../network/api/dio_exeption.dart';
import '../res/images/images.dart';
import 'image_widget.dart';

Future<void> showProcessDialog(BuildContext context) async {
  await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => WillPopScope(
            onWillPop: () async => false,
            child: new AlertDialog(
              content: Row(
                children: <Widget>[
                  CircularProgressIndicator(),
                  SizedBox(width: AppDimens.spaceMedium),
                  Text(Languages.of(context)!.loading)
                ],
              ),
            ),
          ));
}

showDialogError(BuildContext context, String? title, {required String msg}) {
  return showDialog(
    context: context,
    builder: (context) {
      return AlertDialog(
          title: Text(title == null ? Languages.of(context)!.error : title),
          content:
              Text(msg != null ? msg : Languages.of(context)!.errorMessage),
          actions: <Widget>[
            MaterialButton(
                onPressed: () => Navigator.pop(context),
                child: Text(Languages.of(context)!.close.toUpperCase()))
          ]);
    },
  );
}

 callApiDialogError(BuildContext ct,
    {required String? stitle,
    required String? btn,
    required String? msg,
    required String? code,required Function(bool) retry}) async {
  String message = msg!;
  if (code == DioExceptions.BAD_REQUEST) {
    message = Languages.of(ct)!.badRequest;
  } else if (code == DioExceptions.SOME_THING) {
    message = Languages.of(ct)!.someThing;
  } else if (code == DioExceptions.INTERNAL_SERVER) {
    message = Languages.of(ct)!.internalServer;
  } else if (code == DioExceptions.RECEIVE_TIMEOUT) {
    message = Languages.of(ct)!.receiveTimeout;
  } else if (code == DioExceptions.CONNECT_TIMEOUT) {
    message = Languages.of(ct)!.connectTimeout;
  } else if (code == DioExceptions.SEND_TIMEOUT) {
    message = Languages.of(ct)!.sendTimeout;
  } else if (code == DioExceptions.CANCEL) {
    message = Languages.of(ct)!.cancel;
  } else if (code == DioExceptions.AUTHENT ||
      code == DioExceptions.EXPIRED_SESSION) {
    message = Languages.of(ct)!.expiredSession;
  } else if (code == DioExceptions.SUCCESS) {
    message = Languages.of(ct)!.success;
  }

}


showLoaderDialog(BuildContext context){
  AlertDialog alert=AlertDialog(
    content: new Row(
      children: [
        CircularProgressIndicator(),
        Container(margin: EdgeInsets.only(left: 7),child:Text("Loading..." )),
      ],),
  );
  showDialog(barrierDismissible: false,
    context:context,
    builder:(BuildContext context){
      return alert;
    },
  );
}



Widget buildNoDataView(String message) {
  return Center(
    child: Column(children: [
      Padding(
        padding: const EdgeInsets.only(top: 16.0),
        child: Image.asset(Images.ongbut_sad,width: 120,height: 80,),
      ),
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: NeoText(message,textStyle: AppTheme.textStyleLexendThin(fontSize:14,color:AppColors.grey)),
      )
    ],),
  );
}



void toastMessage(String message) {
  // Toast.show(message, gravity: Toast.center);
}

Widget circleOffer(double pageHight, double scale) {
  return Align(
    alignment: Alignment.bottomCenter,
    child: Container(
      margin: EdgeInsets.only(bottom: 10),
      height: pageHight * scale,
      width: pageHight * scale,
      child: Card(
        elevation: 4,
        clipBehavior: Clip.antiAlias,
        shape: CircleBorder(
            side: BorderSide(color: Colors.grey.shade200, width: 5)),
        child: Image.asset(
          Images.indicator,
          fit: BoxFit.cover,
        ),
      ),
    ),
  );
}



dialogTransfer(BuildContext context, String? courseName, String? money) {
  showDialog(
      context: context,
      builder: (_) => Center( // Aligns the container to center
          child: Container(
            width: MediaQuery.of(context).size.width - 20,
            height: 250,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: Colors.white
            ),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: NeoText(Languages.of(context)!.transferTitle,textStyle: AppTheme.textStyleLexendBold(fontSize:18,color:AppColors.black),textAlign: TextAlign.center),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: NeoText(courseName!,textStyle: AppTheme.textStyleLexendRegular(fontSize:16,color:AppColors.black),textAlign: TextAlign.center),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: NeoText(Languages.of(context)!.price(money!),textStyle: AppTheme.textStyleLexendRegular(fontSize:16,color:AppColors.grey),textAlign: TextAlign.center),
                ),
                SizedBox(height: 32,),
                SizedBox(
                  width: 300.0,
                  height: 48.0,
                  child: MaterialButton(
                    color: AppColors.white,
                    onPressed: () => {
                      // applePay(context),
                    },
                    child: NeoText(Languages.of(context)!.applePay,textStyle: AppTheme.textStyleLexendThin(fontSize:16,color:AppColors.black),textAlign: TextAlign.center),
                    textColor: AppColors.white,
                    shape:
                    RoundedRectangleBorder(side: BorderSide(color: AppColors.grey, width: 1, style: BorderStyle.solid), borderRadius: BorderRadius.circular(25)),
                  ),
                ),

                SizedBox(height: 8,),
                // SizedBox(
                //   width: 300.0,
                //   height: 48.0,
                //   child: FlatButton(
                //     color: AppColors.white,
                //     onPressed: () => {
                //
                //     },
                //     child: NeoText(Languages.of(context)!.transferAccount,textStyle: AppTheme.textStyleLexendThin(fontSize:16,color:AppColors.black),textAlign: TextAlign.center),
                //     textColor: AppColors.white,
                //     shape:
                //     RoundedRectangleBorder(side: BorderSide(color: AppColors.grey, width: 1, style: BorderStyle.solid), borderRadius: BorderRadius.circular(25)),
                //   ),
                // )
              ],),
            ),
          )
      )
  );
}

Widget NeoText(String text,{TextStyle? textStyle,TextAlign? textAlign,int? maxLine}){
  return Text(
    text.isEmpty?'':text,
    textAlign: textAlign,
    style: textStyle,
    textScaleFactor: 1.0,
    maxLines: maxLine != null ? maxLine: null,
    overflow: maxLine != null ? TextOverflow.ellipsis :null,
  );
}

Widget NeoText2(String text,{TextStyle? textStyle,TextAlign? textAlign, int? line}){
  return Text(
    text.isEmpty?'':text,
    textAlign: textAlign,
    style: textStyle,
    textScaleFactor: 1.0,
    maxLines: line,
  );
}

Widget DropDownNoData(){
  return Container(
    margin: EdgeInsets.only(left: 10, top: 3, bottom: 3, right: 0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(50),
        color: AppColors.white,
      ),
      height: 48,
      child: DropdownButtonHideUnderline(
        child: Padding(
          padding: const EdgeInsets.only(left: 10.0, right: 5),
          child: DropdownButton(
            iconEnabledColor: AppColors.primary_grey,
            isExpanded: true,
            items: <String>[''].map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(), onChanged: (String? value) {  },
          ),
        ),
      ),
  );
}




double getWidth(BuildContext context){
  return MediaQuery.of(context).size.width;
}

double getHeight(BuildContext context){
  return MediaQuery.of(context).size.height;
}

String getUrlImage(String url){
  return ApiUtils.URL_IMAGE + url;
}

String splitSpaceUrlImage(String value){
  var pathArr = value.split('${ApiUtils.URL_IMAGE}');
  return pathArr[-1];
}

void hideKeyBoard(BuildContext context){
  FocusScope.of(context).requestFocus(new FocusNode());
}

bool checkLandscape(BuildContext context){
  return MediaQuery.of(context).orientation == Orientation.landscape;
}

bool checkTablet(){
  return MediaQueryData.fromWindow(WidgetsBinding.instance.window).size.shortestSide>=600;
}

String splitSpace(String value){
  var pathArr = value.split(" ");
  return pathArr[0];
}

Widget buttonCustom({ required Function() onClick,required String content, Color? backgroundColorButton, Color? textColor, String? assetImage, double? borderRadius, double? fontSize, bool? minWidth}){
  return  MaterialButton(
      color: backgroundColorButton==null?AppColors.primary_blue:backgroundColorButton,
      onPressed: () => {
        onClick(),
      },
      shape: RoundedRectangleBorder(
          side: BorderSide(
              color: backgroundColorButton==null?AppColors.primary_blue:backgroundColorButton,
              width: 1,
              style: BorderStyle.solid),
          borderRadius: BorderRadius.circular(borderRadius==null?25:borderRadius)),
      child: assetImage!=null? Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        mainAxisSize: minWidth!=null?MainAxisSize.min:MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(assetImage, width: AppDimens.dimen24,height: AppDimens.dimen24,),
          SizedBox(width: AppDimens.spaceSmall,),
          NeoText('$content'.toUpperCase(), textStyle: AppTheme.textStyleLexendMedium(fontSize: fontSize==null?16:fontSize, color: textColor==null?AppColors.white:textColor), textAlign: TextAlign.center),
        ],
      ): NeoText('$content'.toUpperCase(), textStyle: AppTheme.textStyleLexendMedium(fontSize: fontSize==null?16:fontSize, color: textColor==null?AppColors.white:textColor), textAlign: TextAlign.center));
}



Widget itemAskQuestion({required BuildContext context,required String nameTeacher, required String imageLink,required bool seemore, required Function(String value) onClick}){
  return  Card(
    child: Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ImageWidget.imageNetwork(imageLink, getHeight(context)*0.3-20, getWidth(context)),
        SizedBox(height: AppDimens.spaceHalf,),
        Row(
          children: [
            SizedBox(width: AppDimens.spaceMedium,),
            NeoText(Languages.of(context)!.tutor, textStyle: AppTheme.textStyleLexendMedium(fontSize: 16, color: AppColors.black)),
            SizedBox(width: AppDimens.spaceHalf,),
            Expanded(child: NeoText('$nameTeacher', textStyle: AppTheme.textStyleLexendBold(fontSize: 16, color: AppColors.black))),
            seemore?Directionality(
              textDirection: TextDirection.rtl,
              child: TextButton.icon(
                onPressed: ()=>onClick(''),
                icon: Icon(
                  Icons.arrow_back_ios_sharp,
                  color: AppColors.primary,
                  size: 16,
                ),
                label:  NeoText(Languages.of(context)!.see, textStyle: AppTheme.textStyleLexendMedium(fontSize: 16, color: AppColors.primary)),
              ),
            ):SizedBox(),
            SizedBox(width: AppDimens.spaceHalf,)
          ],
        ),
      ],
    ),
  );
}

dialogCustom({required BuildContext context, required String title, required String content, required bool showButton, String? nameButton}){
  showDialog(
      context: context,
      builder: (_)=>AlertDialog(
        title: NeoText(title, textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center),
        content: NeoText(content, textStyle: AppTheme.textStyleLexendMedium(fontSize: 13, color: AppColors.black),textAlign: TextAlign.center),
        actions: [
          showButton?Center(
            child: buttonCustom(onClick: ()=>Navigator.pop(context), content: nameButton!),
          ):SizedBox()
        ],
      )
  );
}

double getSizeWidget({required BuildContext context, required String keyFlow, required double value}){

  return 0.0;
}

DialogCustomFunction({required BuildContext context, required String title, required String content, required bool showButton, String? nameButton, bool? barrierDismissible, required Function() onClick}){
  showDialog(
      context: context,
      barrierDismissible: barrierDismissible!=null?false:true,
      builder: (_)=>AlertDialog(
        title: NeoText(title, textStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center),
        content: NeoText(content, textStyle: AppTheme.textStyleLexendMedium(fontSize: 16, color: AppColors.black),textAlign: TextAlign.center),
        actions: [
          showButton?Center(
            child: buttonCustom(onClick: ()=>onClick(), content: nameButton!),
          ):SizedBox()
        ],
      )
  );
}
