import 'dart:convert';
import 'dart:io';

import 'package:car_provider_app/api/client/profile_api_client.dart';
import 'package:car_provider_app/classes/app_state.dart';
import 'package:car_provider_app/classes/utils.dart';
import 'package:car_provider_app/extensions/string_extensions.dart';
import 'package:car_provider_app/models/profile/document.dart';
import 'package:car_provider_app/utils/utils.dart';
import 'package:car_provider_app/widgets/button/show_fill_button.dart';
import 'package:car_provider_app/widgets/txt_field.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:car_provider_app/extensions/int_extensions.dart';
import 'package:sizer/sizer.dart';

import '../../classes/colors.dart';
import '../../generated/locale_keys.g.dart';
import '../../widgets/app_bar.dart';

class DefineLicensePage extends StatefulWidget {
  @override
  State<DefineLicensePage> createState() => _DefineLicensePageState();
}

class _DefineLicensePageState extends State<DefineLicensePage> {
  Document? document;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDocuments();
  }

  getDocuments() async {
    document = await ProfileApiClent().getServiceProviderDocument(AppState().getUser.data!.userInfo!.providerId ?? 0);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(
        context,
        title: LocaleKeys.defineLicences.tr(),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: 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(),
                    ],
                  ),
                ),
              ),
            ),
            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()) {
                      updateDocument();
                    } else {
                      Utils.showToast("All document's are mandatory for Dealership Provider");
                    }
                  } else {
                    updateDocument();
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  updateDocument() {
    Utils.showLoading(context);
    ProfileApiClent().serviceProviderDocumentsUpdate(document!.data).then((value) {
      Utils.hideLoading(context);
      if (value.messageStatus == 1) {
        Utils.showToast("Documents uploaded successfully");
      } else {
        Utils.showToast(value.message ?? "");
      }
    });
  }

  Widget showWidget() {
    if (document != null) {
      return document!.data!.length == 0
          ? Text(LocaleKeys.somethingWrong.tr())
          : ListView.separated(
              itemBuilder: (context, index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      document?.data![index].documentName ?? "",
                      style: TextStyle(
                        fontSize: 16,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 20, right: 20, top: 4, bottom: 8),
                      child: LocaleKeys.enter_licence_detail.tr().toText14(color: MyColors.lightTextColor, textAlign: TextAlign.center),
                    ),
                    TxtField(
                      hint: LocaleKeys.description.tr(),
                      maxLines: 3,
                      isBackgroundEnabled: true,
                    ),
                    if (((document?.data![index].documentUrl ?? "").toString().isNotEmpty))
                      Column(
                        children: [
                          8.height,
                          (document?.data![index].documentUrl ?? "").toString().toText14(
                                color: MyColors.lightTextColor,
                              ),
                        ],
                      ),
                    8.height,
                    InkWell(
                      onTap: () {
                        selectFile(index);
                      },
                      child: Container(
                        width: double.infinity,
                        height: 45,
                        decoration: BoxDecoration(
                          color: Colors.transparent,
                          border: Border.all(color: MyColors.greyACColor, width: 2),
                          borderRadius: BorderRadius.all(Radius.circular(0)),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.attach_file,
                              size: 18,
                              color: MyColors.darkPrimaryColor,
                            ),
                            8.width,
                            Text(
                              LocaleKeys.attachFile.tr(),
                              style: TextStyle(
                                color: MyColors.darkPrimaryColor,
                              ),
                            ),
                            Icon(
                              Icons.attach_file,
                              size: 18,
                              color: Colors.transparent,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
              separatorBuilder: (context, index) {
                return 20.height;
              },
              itemCount: document!.data!.length,
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
            );
    } else {
      return 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 = convertFileToBase64(file);
        document!.data![index].fileExt = checkFileExt(file.path);
        setState(() {
          document!.data![index].documentUrl = result.files.single.path ?? "";
        });
      }
    } else {
      // User canceled the picker
    }
  }
}
