import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/config/routes.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/general_models/m_response.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/app_permission_handler.dart';

import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/service_view_model.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';

import 'package:mc_common_app/widgets/txt_field.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class ProviderLicensePage extends StatefulWidget {
  @override
  State<ProviderLicensePage> createState() => _ProviderLicensePageState();
}

class _ProviderLicensePageState extends State<ProviderLicensePage> {
  late ServiceVM branchVM;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    branchVM = Provider.of<ServiceVM>(context, listen: false);
    branchVM.getServiceProviderDocument(AppState().getUser.data!.userInfo!.providerId ?? 0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.defineLicences.tr(),
        isRemoveBackButton: false,
      ),
      body: Consumer<ServiceVM>(builder: (_, model, __) {
        return Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      // LocaleKeys.defineLicences.tr().toText20(isBold: true),
                      // 12.height,
                      // LocaleKeys.defineLicenese.tr().toText14(color: MyColors.lightTextColor),
                      20.height,
                      showWidget(model),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: ShowFillButton(
                title: LocaleKeys.continu.tr(),
                maxWidth: double.infinity,
                onPressed: () {
                  if (AppState().getUser.data!.userInfo!.roleId == 5) {
                    if (validation(model)) {
                      updateDocument(model);
                    } else {
                      Utils.showToast(LocaleKeys.allDocumentMandatoryDealershipProvider.tr());
                    }
                  } else {
                    updateDocument(model);
                  }
                  Future.delayed(const Duration(seconds: 1), () {
                    Navigator.of(context).pop();
                  });
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  validation(ServiceVM model) {
    bool valid = true;
    model.document!.data!.forEach((element) {
      if (element.documentUrl == null) {
        valid = false;
      }
    });
    return valid;
  }

  updateDocument(ServiceVM model) async {
    Utils.showLoading(context);
    MResponse res = await model.updateDocument(model.document!.data);
    Utils.hideLoading(context);
    if (res.messageStatus == 1) {
      Utils.showToast(LocaleKeys.documentsUploadedSuccessfully.tr());
    } else {
      Utils.showToast(res.message ?? "");
    }
  }

  Widget showWidget(ServiceVM model) {
    if (model.state == ViewState.idle) {
      return model.document!.data!.isEmpty
          ? Text(LocaleKeys.somethingWrong.tr())
          : ListView.separated(
              itemBuilder: (context, index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      model.document?.data![index].documentName ?? "",
                      style: const TextStyle(
                        fontSize: 16,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 20, right: 20, top: 4, bottom: 8),
                      child: LocaleKeys.enter_licence_detail.tr().toText(fontSize: 14, color: MyColors.lightTextColor, textAlign: TextAlign.center),
                    ),
                    TxtField(
                      hint: LocaleKeys.description.tr(),
                      maxLines: 3,
                      isBackgroundEnabled: true,
                    ),
                    if ((model.document?.data![index].documentUrl ?? "").toString().isNotEmpty)
                      Column(
                        children: [
                          8.height,
                          (model.document?.data![index].documentUrl ?? "").toString().toText(
                                fontSize: 14,
                                color: MyColors.lightTextColor,
                              ),
                        ],
                      ),
                    8.height,
                    InkWell(
                      onTap: () async {
                        model.selectFile(context, index);
                      },
                      child: Container(
                        width: double.infinity,
                        height: 45,
                        decoration: BoxDecoration(
                          color: Colors.transparent,
                          border: Border.all(color: MyColors.greyACColor, width: 2),
                          borderRadius: const BorderRadius.all(Radius.circular(0)),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            const Icon(
                              Icons.attach_file,
                              size: 18,
                              color: MyColors.darkPrimaryColor,
                            ),
                            8.width,
                            Text(
                              LocaleKeys.attachFile.tr(),
                              style: const TextStyle(
                                color: MyColors.darkPrimaryColor,
                              ),
                            ),
                            const Icon(
                              Icons.attach_file,
                              size: 18,
                              color: Colors.transparent,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
              separatorBuilder: (context, index) {
                return 20.height;
              },
              itemCount: model.document!.data!.length,
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
            );
    } else {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
  }

// selectFile(int index) async {
//   FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['png', 'pdf', 'jpeg']);
//
//   if (result != null) {
//     File file = File(result.files.single.path ?? "");
//     int sizeInBytes = file.lengthSync();
//     // double sizeInMb = sizeInBytes / (1024 * 1024);
//     if (sizeInBytes > 1000) {
//       Utils.showToast("File is larger then 1KB");
//     } else {
//       document!.data![index].document = Utils.convertFileToBase64(file);
//       document!.data![index].fileExt = Utils.checkFileExt(file.path);
//       setState(() {
//         document!.data![index].documentUrl = result.files.single.path ?? "";
//       });
//     }
//   } else {
//     // User canceled the picker
//   }
// }
}
