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

import 'package:app_petty_cash/app/app_extension.dart';
import 'package:app_petty_cash/app/route.dart';
import 'package:app_petty_cash/model/list_type_model.dart';
import 'package:app_petty_cash/screen/transaksi/insert_transaksi_provider.dart';
import 'package:app_petty_cash/screen/transaksi/list_category_provider.dart';
import 'package:app_petty_cash/screen/transaksi/list_type_provider.dart';
import 'package:app_petty_cash/screen/transaksi/transaksi_pick_date_widget.dart';
import 'package:app_petty_cash/screen/transaksi/transaksi_select_kategori_widget.dart';
import 'package:app_petty_cash/screen/transaksi/transaksi_upload_area_widget.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:file_picker/file_picker.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:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:mime/mime.dart';

import '../../app/constant.dart';
import '../../model/list_category_model.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/custom_drawer.dart';
import '../../widget/sankbar_widget.dart';
import '../login/custom_text_field.dart';

class DummyDropdownTipe {
  final String options;
  final int id;

  DummyDropdownTipe(
    this.options,
    this.id,
  );
}

class DummyRadioTipe {
  final String text;
  final int id;

  DummyRadioTipe(this.text, this.id);
}

class TransaksiScreen extends HookConsumerWidget {
  const TransaksiScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final ctrlJumlah = useTextEditingController(text: "");
    final ctrlCatatan = useTextEditingController(text: "");
    final ctrlNamaPengirim = useTextEditingController(text: "");
    final ctrlCompanyName = useTextEditingController(text: "");
    final fileData = useState<XFile?>(null);
    final fileDataBase64 = useState<String>("");
    final isImage = useState(false);
    final fileEkstension = useState("");

    String formattedDate = DateFormat('dd-MM-yyyy').format(DateTime.now());

    // final ctrlTglAwal = useTextEditingController(
    //   text: DateTime.now().toString().split(' ')[0],
    // );

    final ctrlTglAwal = useTextEditingController(text: formattedDate);

    final tglAwal = useState<DateTime>(DateTime.now());
    final tglAwalTmp = useState<String>("");

    final listTypeData = useState<List<ListType>>(List.empty(growable: true));
    final selectedListTypeData = useState<ListType>(ListType());

    final listTypeLoading = useState(false);

    // category
    final listCategoryLoading = useState(false);
    final selectedListCategory = useState<ListCategory>(ListCategory());
    final listCategoryData = useState<List<ListCategory>>(
      List.empty(
        growable: true,
      ),
    );

    // transaksi
    final transaksiIsLoading = useState(false);

    // A. LISTEN PROVIDER
    ref.listen(
      listTypeProvider,
      (previous, next) {
        if (next is ListTypeStateLoading) {
          listTypeLoading.value = true;
        } else if (next is ListTypeStateError) {
          // print(next.message);
          listTypeLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is ListTypeStateDone) {
          // print(jsonEncode(next.model));
          // print(next.model.length);
          listTypeData.value = next.model;
          listTypeLoading.value = false;

          var idx = 0;
          for (var i = 0; i < listTypeData.value.length; i++) {
            if (listTypeData.value[i].typeid == "KREDIT") {
              selectedListTypeData.value = listTypeData.value[i];
              idx = i;
            }
          }
          selectedListTypeData.value = listTypeData.value[idx];
        }
      },
    );

    ref.listen(
      listCategoryProvider,
      (previous, next) {
        if (next is ListCategoryStateLoading) {
          listCategoryLoading.value = true;
        } else if (next is ListCategoryStateError) {
          // print(next.message);
          listCategoryLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is ListCategoryStateDone) {
          // print(jsonEncode(next.model));
          // print(next.model.length);
          listCategoryData.value = next.model;
          listCategoryLoading.value = false;
          selectedListCategory.value = listCategoryData.value[0];
        }
      },
    );

    // insert transaksi provider
    ref.listen(
      insertTransaksiProvider,
      (previous, next) {
        if (next is InsertTransaksiStateLoading) {
          transaksiIsLoading.value = true;
        } else if (next is InsertTransaksiStateError) {
          print(next.message);
          transaksiIsLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is InsertTransaksiStateDone) {
          // print(jsonEncode(next.model));
          // print(next.model.length);
          transaksiIsLoading.value = false;
          SanckbarWidget(
            context,
            'Data Berhasil Disimpan',
            snackbarType.success,
          );
          Navigator.of(context).pop();
          Navigator.of(context).pushNamed(homeRoute);
        }
      },
    );

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";
        if (userID == "0") {
          //not login
          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => true);

          //  Navigator.popAndPushNamed(context, loginRoute);
          return;
        }

        ctrlCompanyName.text =
            ref.read(currentUserProvider)?.model.M_CompanyName ?? "";
      });
      return () {};
    }, []);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // list Type Provider
        ref.read(listTypeProvider.notifier).getListType();

        // list category provider
        ref.read(listCategoryProvider.notifier).getListCategory();
      });
      return () {};
    }, []);

    final isMounted = useIsMounted();

    // var sbHeight = MediaQuery.of(context).padding.top;

    // print('Height : ${sbHeight}');

    final userIDLogin = ref.read(currentUserProvider)?.model.M_UserID ?? "0";

    getBase64() async {
      // List<int> imageBytes = await fileData.value?.readAsBytes();
      if (fileData.value != null) {
        final bytes = io.File(fileData.value!.path).readAsBytesSync();
        String base64Image = base64Encode(bytes);
        fileDataBase64.value = base64Image;
        final file = File(fileData.value!.path);
        print(file.lengthSync() / 1000000);
        print(await fileData.value!.length());

        // await getExternalStorageDirectory();
        // print(await fileData.value!.saveTo(path));
        print(base64Image);
      }
    }

    final ImagePicker _picker = ImagePicker();
    pickImage() async {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
      );
      if (pickedFile != null) {
        if (await pickedFile.length() > 10000000) {
          SanckbarWidget(context, "File tidak boleh lebih dari 10 MB",
              snackbarType.warning);
        } else {
          fileData.value = pickedFile;
          isImage.value = true;
        }
        // final Directory appDocumentsDir =
        //     await getApplicationDocumentsDirectory();
        // print(appDocumentsDir);
        // await pickedFile!.saveTo(appDocumentsDir.path);
        await getBase64();
      }
    }

    browseImage() async {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
      );
      fileData.value = pickedFile;
      getBase64();
    }

    pickFile() async {
      List<String> imgExt = [
        'jpg',
        'png',
        'jpeg',
      ];
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        allowMultiple: false,
        type: FileType.custom,
        dialogTitle: "Pick a file",
        allowedExtensions: [
          ...imgExt,
          'pdf',
          'doc',
          'docx',
          'xls',
          'xlsx',
          'ppt',
          'pptx',
          'txt'
        ],
      );

      if (result != null) {
        if (result.files.single.size > 10000000) {
          SanckbarWidget(context, "File tidak boleh lebih dari 10 MB",
              snackbarType.warning);
        } else {
          File files = File(result.files.single.path!);
          print(result.files.single.extension);
          XFile fl = XFile(result.files.single.path!);

          isImage.value = imgExt.contains(result.files.single.extension);

          print("ini xfile");
          fileData.value = fl;
          await getBase64();
          fileEkstension.value = result.files.single.extension ?? "";
        }
      } else {
        // User canceled the picker
      }
    }

    return Padding(
      padding: EdgeInsets.only(
        top: Constant.getActualYPhone(context: context, y: 30),
      ),
      child: Scaffold(
        appBar: AppBar(
          //  centerTitle: true,
          title: Text(
            'Transaksi',
            style: TextStyle(color: Constant.textWhite),
          ),
          backgroundColor: Constant.pcBtnBackgroundColor,
          iconTheme: IconThemeData(
            color: Constant.textWhite,
          ),
        ),
        drawer: CustomDrawer(),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Container(
                height: MediaQuery.of(context).size.height - 10,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Company Name
                    Text(
                      'Company Name',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 10),
                    ),
                    TextField(
                      controller: ctrlCompanyName,
                      readOnly: true,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Company Name",
                        hintText: 'Company Name',
                      ),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),
                    Text(
                      'Tanggal Transaksi',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 10),
                    ),
                    // Tanggal Transaksi
                    TransaksiPickDateWidget(
                        ctrlTglAwal: ctrlTglAwal,
                        tglAwal: tglAwal,
                        tglAwalTmp: tglAwalTmp),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    // tipe transaksi
                    Text(
                      'Tipe Transaksi',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 10),
                    ),
                    SizedBox(
                      width: Constant.getActualXPhone(context: context, x: 340),
                      height: Constant.getActualYPhone(context: context, y: 36),
                      child: (listTypeLoading.value)
                          ? SizedBox(
                              width: Constant.getActualXPhone(
                                  context: context, x: 24),
                              height: Constant.getActualYPhone(
                                  context: context, y: 32),
                              child: Center(
                                child: CircularProgressIndicator(),
                              ),
                            )
                          : Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                if (listTypeData.value.isEmpty)
                                  Text('Radio Button Empty')
                                else
                                  for (var i = 0;
                                      i < listTypeData.value.length;
                                      i++)
                                    Padding(
                                      padding: const EdgeInsets.only(right: 20),
                                      child: Row(
                                        children: [
                                          Radio<ListType>(
                                            activeColor:
                                                Constant.pcBtnBackgroundColor,
                                            value: listTypeData.value[i],
                                            groupValue:
                                                selectedListTypeData.value,
                                            onChanged: (ListType? index) {
                                              if (isMounted()) {
                                                selectedListTypeData.value =
                                                    index!;
                                              } else {
                                                return;
                                              }
                                            },
                                          ),
                                          Text(
                                            listTypeData.value[i].typename ??
                                                "",
                                            style:
                                                Constant.body1(context: context)
                                                    .copyWith(
                                              color: Constant.textBlack,
                                              fontWeight: FontWeight.w400,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                              ],
                            ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    // Kategori
                    if (selectedListTypeData.value.typeid == "DEBIT") ...[
                      Text(
                        'Kategori',
                        style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack,
                        ),
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 10),
                      ),
                      // Dropdown kategori
                      (listCategoryLoading.value)
                          ? SizedBox(
                              width: Constant.getActualXPhone(
                                  context: context, x: 24),
                              height: Constant.getActualYPhone(
                                  context: context, y: 32),
                              child: Center(
                                child: CircularProgressIndicator(),
                              ),
                            )
                          : TransaksiSelectKategoriWidget(
                              listCategoryData: listCategoryData,
                              selectedListCategory: selectedListCategory),

                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 20),
                      ),
                    ],

                    // Nama Pengirim
                    if (selectedListTypeData.value.typeid == "KREDIT") ...[
                      Text(
                        'Nama Pengirim',
                        style: Constant.body1(context: context).copyWith(
                            fontWeight: FontWeight.w600,
                            color: Constant.textBlack),
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 10),
                      ),
                      TextField(
                        controller: ctrlNamaPengirim,
                        decoration: InputDecoration(
                          hintStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Constant.textGreyv2,
                          ),
                          labelStyle:
                              Constant.body2_400(context: context).copyWith(
                            color: Constant.textGreyv2,
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.orange,
                              width: 1,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Constant.textGreyv2,
                              width: 1,
                            ),
                          ),
                          labelText: "Nama Pengirim",
                          hintText: 'Nama Pengirim',
                        ),
                      ),
                    ],
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    // jumlah
                    Text(
                      'Jumlah',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),
                    TextField(
                      controller: ctrlJumlah,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Jumlah",
                        hintText: 'Jumlah',
                      ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    // catatan
                    Text(
                      'Catatan',
                      style: Constant.body1(context: context).copyWith(
                          fontWeight: FontWeight.w600,
                          color: Constant.textBlack),
                    ),
                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    TextField(
                      controller: ctrlCatatan,
                      maxLines: 4,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Catatan",
                        hintText: 'Catatan',
                      ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 20),
                    ),

                    // Upload File
                    TransaksiUploadAreaWidget(
                        isImage: isImage,
                        fileData: fileData,
                        fileDataBase64: fileDataBase64,
                        pickFile: pickFile,
                        pickImage: pickImage),

                    // Spacer(),

                    Container(
                      width: Constant.getActualXPhone(context: context, x: 390),
                      child: ElevatedButton(
                        style: ButtonStyle(
                          backgroundColor: MaterialStateColor.resolveWith(
                              (st) => Constant.pcBtnBackgroundColor),
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                              side: BorderSide(
                                color: Constant.pcBtnBackgroundColor,
                              ),
                            ),
                          ),
                          shadowColor:
                              MaterialStateProperty.all(Color(0xffff48423d)),
                          elevation: MaterialStateProperty.all(4.0),
                        ),
                        child: Stack(
                          children: [
                            (transaksiIsLoading.value)
                                ? SizedBox(
                                    width: Constant.getActualXPhone(
                                        context: context, x: 24),
                                    height: Constant.getActualYPhone(
                                        context: context, y: 32),
                                    child: CircularProgressIndicator(
                                      color: Colors.white,
                                    ),
                                  )
                                : Text(
                                    'Simpan',
                                    style: Constant.body1(context: context)
                                        .copyWith(
                                            fontWeight: FontWeight.w600,
                                            color: Constant.white),
                                  ),
                          ],
                        ),
                        onPressed: () {
                          if (selectedListTypeData.value.typeid.toString() ==
                              "DEBIT") {
                            ctrlNamaPengirim.text = "";
                            //  validasi form
                          } else {
                            if (selectedListTypeData.value.typeid.toString() ==
                                "KREDIT") {
                              selectedListCategory.value.categoryid = "0";
                              // validasi form
                            }
                          }

                          DateTime parsedDate = DateFormat('dd-MM-yyyy').parse(
                            ctrlTglAwal.value.text.toString(),
                          );
                          String formattedDateTransaksi =
                              DateFormat('yyyy-MM-dd').format(parsedDate);
                          var param = {
                            "tgltransaksi": formattedDateTransaksi,
                            "typeid":
                                selectedListTypeData.value.typeid.toString(),
                            "categoryid": selectedListCategory.value.categoryid
                                .toString(),
                            "jumlah": ctrlJumlah.value.text.toString(),
                            "catatan": ctrlCatatan.value.text.toString(),
                            // "userid": "1",
                            "userid": userIDLogin,
                            "namapengirim":
                                ctrlNamaPengirim.value.text.toString(),
                            "url": "",
                          };
                          print(param);
                          ref
                              .read(insertTransaksiProvider.notifier)
                              .insertTransaksi(
                                formattedDateTransaksi,
                                selectedListTypeData.value.typeid.toString(),
                                selectedListCategory.value.categoryid
                                    .toString(),
                                ctrlJumlah.value.text.toString(),
                                ctrlCatatan.value.text.toString(),
                                // "1",
                                userIDLogin,
                                ctrlNamaPengirim.value.text.toString(),
                                "",
                              );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        // bottomNavigationBar: Padding(
        //   padding: EdgeInsets.only(
        //     right: Constant.getActualXPhone(context: context, x: 27),
        //     left: Constant.getActualXPhone(context: context, x: 27),
        //     bottom: Constant.getActualYPhone(context: context, y: 32),
        //     top: Constant.getActualYPhone(context: context, y: 10),
        //   ),
        //   child: BottomAppBar(
        //     elevation: 2.0,
        //     child: Container(
        //       width: Constant.getActualXPhone(context: context, x: 336),
        //       height: Constant.getActualYPhone(context: context, y: 42),
        //       child: ElevatedButton(
        //         style: ButtonStyle(
        //           backgroundColor: MaterialStateColor.resolveWith(
        //               (st) => Constant.pcBtnBackgroundColor),
        //           shape: MaterialStateProperty.all<RoundedRectangleBorder>(
        //             RoundedRectangleBorder(
        //               borderRadius: BorderRadius.circular(8),
        //               side: BorderSide(
        //                 color: Constant.pcBtnBackgroundColor,
        //               ),
        //             ),
        //           ),
        //           shadowColor: MaterialStateProperty.all(Color(0xffff48423d)),
        //           elevation: MaterialStateProperty.all(4.0),
        //         ),
        //         child: Stack(
        //           children: [
        //             (transaksiIsLoading.value)
        //                 ? SizedBox(
        //                     width: Constant.getActualXPhone(
        //                         context: context, x: 24),
        //                     height: Constant.getActualYPhone(
        //                         context: context, y: 32),
        //                     child: CircularProgressIndicator(
        //                       color: Colors.white,
        //                     ),
        //                   )
        //                 : Text(
        //                     'Simpan',
        //                     style: Constant.body1(context: context).copyWith(
        //                         fontWeight: FontWeight.w600,
        //                         color: Constant.white),
        //                   ),
        //           ],
        //         ),
        //         onPressed: () {
        //           if (selectedListTypeData.value.typeid.toString() == "DEBIT") {
        //             ctrlNamaPengirim.text = "";
        //             //  validasi form
        //           } else {
        //             if (selectedListTypeData.value.typeid.toString() ==
        //                 "KREDIT") {
        //               selectedListCategory.value.categoryid = "0";
        //               // validasi form
        //             }
        //           }

        //           DateTime parsedDate = DateFormat('dd-MM-yyyy').parse(
        //             ctrlTglAwal.value.text.toString(),
        //           );
        //           String formattedDateTransaksi =
        //               DateFormat('yyyy-MM-dd').format(parsedDate);
        //           var param = {
        //             "tgltransaksi": formattedDateTransaksi,
        //             "typeid": selectedListTypeData.value.typeid.toString(),
        //             "categoryid":
        //                 selectedListCategory.value.categoryid.toString(),
        //             "jumlah": ctrlJumlah.value.text.toString(),
        //             "catatan": ctrlCatatan.value.text.toString(),
        //             // "userid": "1",
        //             "userid": userIDLogin,
        //             "namapengirim": ctrlNamaPengirim.value.text.toString(),
        //             "url": "",
        //           };
        //           print(param);
        //           ref.read(insertTransaksiProvider.notifier).insertTransaksi(
        //                 formattedDateTransaksi,
        //                 selectedListTypeData.value.typeid.toString(),
        //                 selectedListCategory.value.categoryid.toString(),
        //                 ctrlJumlah.value.text.toString(),
        //                 ctrlCatatan.value.text.toString(),
        //                 // "1",
        //                 userIDLogin,
        //                 ctrlNamaPengirim.value.text.toString(),
        //                 "",
        //               );
        //         },
        //       ),
        //     ),
        //   ),
        // ),
      ),
    );
  }
}
