import 'package:mitra_corporate/model/surat_jalan_model.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mitra_corporate/model/create_surat_jalan_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/provider/surat_jalan_provider.dart';

import 'package:mitra_corporate/screen/surat_jalan/dialog_surat_jalan.dart';
import 'package:mitra_corporate/screen/surat_jalan/table_surat_jalan.dart';
import 'package:mitra_corporate/widgets/header.dart';
import 'package:intl/intl.dart';

import '../../app/constant.dart';
import '../../provider/menu_provider.dart';
import '../../widgets/custom_text_field.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final auth = ref.watch(authProvider);
    final selectedDateType = ref.watch(sjDateType);
    final isExpand = ref.watch(sideBarExpandProvider);
    final searchCtr = useTextEditingController(text: "");
    final startDateCtr = useTextEditingController(
        text: DateFormat('dd-MM-yyyy').format(ref.watch(sjStartDateProvider)));
    final startDateState = useState(ref.watch(sjStartDateProvider));
    final endDateCtr = useTextEditingController(
        text: DateFormat('dd-MM-yyyy').format(ref.watch(sjEndDateProvider)));
    final endDateState = useState(ref.watch(sjEndDateProvider));

    final dateFilterKey = useState(1);

    final selectedDateFilter = useState(selectedDateType);
    useEffect(() {
      // ref.read(sjDateType.notifier).state = dateFilter.first;
      selectedDateFilter.value = selectedDateType;
      dateFilterKey.value = dateFilterKey.value + 1;
      return null;
    }, [isExpand]);
    // useEffect(() {
    //   selectedDateFilter.value = selectedDateType;
    //   print(selectedDateType.name);
    // }, [selectedDateType]);

    return Material(
      child: Column(
        children: [
          Header(),
          Padding(
            padding: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 32),
                vertical: Constant.getActualY(context: context, y: 32)),
            child: Column(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  // width: Constant.getActualX(context: context, x: 1079),
                  height: Constant.getActualY(context: context, y: 40),
                  child: Text('Kirim Order',
                      style: Constant.h3_400(context: context)
                          .copyWith(color: Constant.textBlack)),
                ),
                SizedBox(height: Constant.getActualY(context: context, y: 42)),
                Container(
                  padding: EdgeInsets.symmetric(
                      horizontal: Constant.getActualX(context: context, x: 24),
                      vertical: Constant.getActualY(context: context, y: 32)),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      color: Colors.white),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(child: LayoutBuilder(builder:
                              (BuildContext context,
                                  BoxConstraints constraints) {
                            return DropdownMenu<dateFilterModel>(
                              key: ValueKey(dateFilterKey.value),
                              hintText: "Tipe Tanggal",
                              inputDecorationTheme: InputDecorationTheme(
                                  border: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Constant.primaryRed),
                                      borderRadius: BorderRadius.circular(8))),
                              menuHeight:
                                  Constant.getActualY(context: context, y: 300),
                              // width: Constant.getActualX(context: context, x: 150),
                              width: constraints.maxWidth,
                              textStyle: Constant.body2_400(context: context),
                              label: const Text(
                                "Tipe Tanggal",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              initialSelection: selectedDateFilter.value,

                              onSelected: (dateFilterModel? value) {
                                // This is called when the user selects an item.
                                // print(value!.name);
                                ref.read(sjDateType.notifier).state = value!;
                                selectedDateFilter.value = value;
                              },
                              dropdownMenuEntries: Constant.dateFilter
                                  .map<DropdownMenuEntry<dateFilterModel>>(
                                      (dateFilterModel value) {
                                return DropdownMenuEntry<dateFilterModel>(
                                    value: value, label: value.name);
                              }).toList(),
                            );
                          })),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 24),
                          ),
                          Expanded(
                              child: TextField(
                            style: Constant.body1_600(context: context),
                            controller: startDateCtr,
                            decoration: InputDecoration(
                                suffixIcon: Icon(EvaIcons.calendar),
                                border: OutlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Constant.primaryBlue),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                labelStyle:
                                    Constant.body1_600(context: context),
                                labelText: "Tanggal Awal" //label text of field
                                ),
                            readOnly: true,
                            onTap: () async {
                              DateTime? pickedDate = await showDatePicker(
                                  // locale: Locale("id"),
                                  confirmText: "OK",
                                  cancelText: "Batal",
                                  context: context,
                                  initialDate: startDateState.value,
                                  firstDate: DateTime(1800),
                                  initialEntryMode:
                                      DatePickerEntryMode.calendarOnly,

                                  //DateTime.now() - not to allow to choose before today.
                                  lastDate: DateTime(2100));

                              if (pickedDate != null) {
                                print(
                                    pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                String formattedDate =
                                    DateFormat('dd-MM-yyyy').format(pickedDate);
                                print(
                                    formattedDate); //formatted date output using intl package =>  2021-03-16
                                startDateCtr.text =
                                    formattedDate; //set output date to TextField value.
                                startDateState.value = pickedDate;
                                ref.read(sjStartDateProvider.notifier).state =
                                    pickedDate;
                              } else {}
                            },
                          )),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 24),
                          ),
                          Expanded(
                              child: TextField(
                            style: Constant.body1_600(context: context),
                            controller: endDateCtr,
                            decoration: InputDecoration(
                                suffixIcon: Icon(EvaIcons.calendar),
                                border: OutlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Constant.primaryBlue),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                labelStyle:
                                    Constant.body1_600(context: context),
                                labelText: "Tanggal Akhir" //label text of field
                                ),
                            readOnly: true,
                            onTap: () async {
                              DateTime? pickedDate = await showDatePicker(
                                  // locale: Locale("id"),
                                  confirmText: "OK",
                                  cancelText: "Batal",
                                  context: context,
                                  initialDate: endDateState.value,
                                  firstDate: DateTime(1800),
                                  initialEntryMode:
                                      DatePickerEntryMode.calendarOnly,

                                  //DateTime.now() - not to allow to choose before today.
                                  lastDate: DateTime(2100));

                              if (pickedDate != null) {
                                print(
                                    pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                String formattedDate =
                                    DateFormat('dd-MM-yyyy').format(pickedDate);
                                print(
                                    formattedDate); //formatted date output using intl package =>  2021-03-16
                                endDateCtr.text =
                                    formattedDate; //set output date to TextField value.
                                endDateState.value = pickedDate;
                                ref.read(sjEndDateProvider.notifier).state =
                                    pickedDate;
                              } else {}
                            },
                          )),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 24),
                          ),
                          Expanded(
                            // width: Constant.getActualX(context: context, x: 408),
                            // height: Constant.getActualY(context: context, y: 56),
                            child: CustomTextField(
                              onChange: (value) {
                                ref
                                    .read(suratJalankeywordProvider.notifier)
                                    .state = value;
                              },
                              controller: searchCtr,
                              isPassword: false,
                              hintText: "Cari No/Tujuan/Staff PIC",
                              labelText: "Cari No/Tujuan/Staff PIC",
                              suffixIcon: Icon(EvaIcons.search),
                            ),
                          ),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 24),
                          ),
                          Container(
                            // width: Constant.getActualX(context: context, x: 171),
                            height:
                                Constant.getActualY(context: context, y: 56),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                color: Constant.primaryRed),
                            child: ElevatedButton.icon(
                              label: Text('Kirim order Baru',
                                  style: Constant.button_large(context: context)
                                      .copyWith(color: Constant.textWhite)),
                              icon: Icon(EvaIcons.plus,
                                  color: Colors.white, size: 20.0),
                              onPressed: () {
                                ref
                                        .read(createSuratJalanProvider.notifier)
                                        .state =
                                    CreateSuratJalanModel(
                                        order: Order(
                                            regionalId:
                                                auth?.MUserSRegionalID ?? ""));
                                showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: ((context) => DialogSuratJalan()));
                              },
                              style: ElevatedButton.styleFrom(
                                  shadowColor: Colors.transparent),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                          height: Constant.getActualY(context: context, y: 24)),
                      TableSuratJalan()
                    ],
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
