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:dropdown_button2/dropdown_button2.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:intl/intl.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: "");

    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;
        }
      });
      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}');

    return Padding(
      padding: EdgeInsets.only(
        top: Constant.getActualYPhone(context: context, y: 30),
      ),
      child: Scaffold(
        appBar: AppBar(
          //  centerTitle: true,
          title: Text('Transaksi'),
        ),
        drawer: CustomDrawer(),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  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
                  Row(
                    children: [
                      Expanded(
                        child: TextField(
                          controller: ctrlTglAwal,
                          decoration: InputDecoration(
                            hintStyle:
                                Constant.body2_400(context: context).copyWith(
                              color: Colors.orange,
                            ),
                            labelStyle:
                                Constant.body2_400(context: context).copyWith(
                              color: Colors.orange,
                            ),
                            border: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.orange,
                                width: 1,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.orange,
                                width: 1,
                              ),
                            ),
                            // labelText: "Tanggal Awal",
                            hintText: 'Tanggal Awal',
                            // suffixIcon: isLoadingFilterScope.value
                            //     ? SizedBox(
                            //         width: Constant.getActualXPhone(
                            //           context: context,
                            //           x: 4,
                            //         ),
                            //         height: Constant.getActualYPhone(
                            //           context: context,
                            //           y: 4,
                            //         ),
                            //         child: CircularProgressIndicator(
                            //           color: Constant.textRed,
                            //         ),
                            //       )
                            //     : Icon(
                            //         Icons.calendar_month_sharp,
                            //         color: Constant.colorIconDate,
                            //       ),
                          ),
                          onTap: () async {
                            final selectedDateAwal = await showDatePicker(
                              // locale: const Locale("en-CA"),
                              // locale: ,
                              context: context,
                              initialEntryMode:
                                  DatePickerEntryMode.calendarOnly,
                              firstDate: DateTime(2000),
                              lastDate: DateTime(2100),

                              initialDate: (ctrlTglAwal.text.isEmpty)
                                  ? DateTime.now()
                                  : tglAwal.value,
                            );

                            if (selectedDateAwal != null) {
                              String formattedDate = DateFormat('dd-MM-yyyy')
                                  .format(selectedDateAwal);
                              // ctrlTglAwal.text =
                              //     selectedDateAwal.toString().split(' ')[0];
                              ctrlTglAwal.text = formattedDate;
                              tglAwal.value = selectedDateAwal;
                              tglAwalTmp.value = selectedDateAwal.toString();
                            }

                            if (selectedDateAwal == null) {
                              print('cancel button');
                              return;
                            }
                          },
                        ),
                      ),
                    ],
                  ),

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

                  // jenis
                  Text(
                    'Jenis',
                    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 == "KREDIT") ...[
                    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(),
                            ),
                          )
                        : SizedBox(
                            width: Constant.getActualXPhone(
                                context: context, x: 390),
                            child: DropdownButtonHideUnderline(
                              child: DropdownButton2<ListCategory>(
                                isExpanded: true,
                                hint: Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        'Select Item',
                                        style: Constant.body1(context: context)
                                            .copyWith(
                                                fontWeight: FontWeight.w600,
                                                color: Constant.textBlack),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                items: listCategoryData.value
                                    .map((ListCategory option) {
                                  return DropdownMenuItem<ListCategory>(
                                    value: option,
                                    child: Text(
                                      option.categoryname ?? "",
                                      style: Constant.body1(context: context)
                                          .copyWith(
                                              color: Constant.textBlack,
                                              fontWeight: FontWeight.w600),
                                    ),
                                  );
                                }).toList(),
                                value: selectedListCategory.value,
                                onChanged: (ListCategory? newValue) {
                                  // if (newValue) {
                                  selectedListCategory.value = newValue!;
                                  print(selectedListCategory.value.categoryid);
                                  // }
                                },
                                buttonStyleData: ButtonStyleData(
                                  height: Constant.getActualY(
                                      context: context, y: 56),
                                  width: Constant.getActualX(
                                      context: context, x: 320),
                                  padding: EdgeInsets.only(
                                    left: Constant.getActualX(
                                        context: context, x: 10),
                                    right: Constant.getActualX(
                                        context: context, x: 10),
                                  ),
                                  decoration: BoxDecoration(
                                    color: Constant.white,
                                    border: Border.all(
                                        color: Constant.textBlack, width: 1),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  elevation: 2,
                                ),
                                iconStyleData: IconStyleData(
                                  icon: Icon(
                                    Icons.keyboard_arrow_down_outlined,
                                  ),
                                  iconSize: 24,
                                  iconEnabledColor: Constant.textBlack,
                                  iconDisabledColor: Colors.grey,
                                ),
                                dropdownStyleData: DropdownStyleData(
                                  maxHeight: Constant.getActualY(
                                      context: context, y: 200),
                                  // width: Constant.getActualX(context: context, x: 320),
                                  padding: EdgeInsets.only(
                                    top: Constant.getActualY(
                                        context: context, y: 10),
                                    left: Constant.getActualX(
                                        context: context, x: 10),
                                    right: Constant.getActualX(
                                        context: context, x: 10),
                                    bottom: Constant.getActualY(
                                        context: context, y: 10),
                                  ),
                                  decoration: BoxDecoration(
                                    color: Constant.white,
                                    borderRadius: BorderRadius.circular(8),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey,
                                        blurRadius: 20.0,
                                        spreadRadius: 2.0,
                                        offset: Offset(0.0, 0.0),
                                      ),
                                    ],
                                  ),
                                  elevation: 8,
                                  offset: const Offset(0, -10),
                                  scrollbarTheme: ScrollbarThemeData(
                                    radius: const Radius.circular(40),
                                    thickness:
                                        MaterialStateProperty.all<double>(6),
                                    thumbVisibility:
                                        MaterialStateProperty.all<bool>(true),
                                  ),
                                ),
                                menuItemStyleData: MenuItemStyleData(
                                  height: Constant.getActualY(
                                      context: context, y: 56),
                                  padding: EdgeInsets.only(
                                    top: Constant.getActualY(
                                        context: context, y: 10),
                                    left: Constant.getActualX(
                                        context: context, x: 10),
                                    right: Constant.getActualX(
                                        context: context, x: 10),
                                  ),
                                ),
                              ),
                            ),
                          ),

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

                  // Nama Pengirim
                  if (selectedListTypeData.value.typeid == "DEBIT") ...[
                    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: Colors.orange,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Colors.orange,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        // labelText: "Nama Pengirim",
                        // hintText: 'Nama Pengirim',
                      ),
                    ),
                  ],
                  // CustomTextField(
                  //   isNumber: false,
                  //   isReadOnly: false,
                  //   ctrl: ctrlNamaPengirim,
                  //   isPassword: false,
                  //   isMaxLine: false,
                  //   hintText: "Nama Pengirim",
                  //   labelText: "Nama Pengirim",
                  //   // onChange: (String searchResult) {},
                  //   isPrefix: false,
                  // ),
                  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: Colors.orange,
                      ),
                      labelStyle: Constant.body2_400(context: context).copyWith(
                        color: Colors.orange,
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.orange,
                          width: 1,
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.orange,
                          width: 1,
                        ),
                      ),
                      // labelText: "Jumlah",
                      // hintText: 'Jumlah',
                    ),
                  ),
                  // CustomTextField(
                  //   isNumber: true,
                  //   isReadOnly: false,
                  //   ctrl: ctrlJumlah,
                  //   isPassword: false,
                  //   isMaxLine: false,
                  //   hintText: "Jumlah",
                  //   labelText: "Jumlah",
                  //   // onChange: (String searchResult) {},
                  //   isPrefix: false,
                  // ),

                  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: Colors.orange,
                      ),
                      labelStyle: Constant.body2_400(context: context).copyWith(
                        color: Colors.orange,
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.orange,
                          width: 1,
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.orange,
                          width: 1,
                        ),
                      ),
                      // labelText: "Catatan",
                      // hintText: 'Catatan',
                    ),
                  ),
                  // CustomTextField(
                  //   isNumber: false,
                  //   isReadOnly: false,
                  //   ctrl: ctrlCatatan,
                  //   isPassword: false,
                  //   isMaxLine: true,
                  //   isTextArea: true,
                  //   hintText: "Catatan",
                  //   labelText: "Catatan",
                  //   // onChange: (String searchResult) {},
                  //   isPrefix: false,
                  // ),

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

                  // Upload File
                  Container(
                    width: Constant.getActualXPhone(context: context, x: 390),
                    height: Constant.getActualYPhone(context: context, y: 83),
                    decoration: BoxDecoration(color: Constant.bgUploadFile),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.upload_outlined,
                          color: Constant.pcBtnBackgroundColor,
                        ),
                        Text(
                          'Upload File',
                          style: Constant.body1(context: context).copyWith(
                              fontWeight: FontWeight.w600,
                              color: Constant.pcBtnBackgroundColor),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        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() ==
                      "KREDIT") {
                    ctrlNamaPengirim.text = "";
                    //  validasi form
                  } else {
                    if (selectedListTypeData.value.typeid.toString() ==
                        "DEBIT") {
                      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",
                    "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",
                        ctrlNamaPengirim.value.text.toString(),
                        "",
                      );
                },
              ),
            ),
          ),
        ),
      ),
    );
  }
}
