import 'package:cached_network_image/cached_network_image.dart';
import 'package:farm_tpf/models/item_dropdown.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp_type.dart';
import 'package:farm_tpf/presentation/screens/codes/widgets/item_column.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';

import '../../../utils/utils.dart';
import '../../custom_widgets/app_bar_widget.dart';
import '../../custom_widgets/button_widget.dart';
import '../../custom_widgets/date_picker/date_picker_widget.dart';
import '../../custom_widgets/dropdown/dropdown_bottom_sheet.dart';
import '../../custom_widgets/textfield/text_field_normal.dart';
import 'cubit/create_stamp_cubit.dart';

class CreateStampPage extends StatefulWidget {
  const CreateStampPage({
    super.key,
  });

  @override
  State<CreateStampPage> createState() => _CreateStampPageState();
}

class _CreateStampPageState extends State<CreateStampPage> {
  final bloc = CreateStampCubit();

  @override
  void initState() {
    super.initState();
    bloc.preparedData();
  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(),
      body: BlocListener<CreateStampCubit, CreateStampState>(
        bloc: bloc,
        listener: ((context, state) {
          if (state is CreateStampLoading) {
            SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
              UtilWidget.showLoading();
            });
          } else if (state is CreateStampFailure) {
            SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
              UtilWidget.hideLoading();
              // UtilWidget.showToastError(state.errorMessage);
            });
          } else if (state is CreateStampPrepareDataSuccessful) {
            SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
              UtilWidget.hideLoading();
            });
          }
        }),
        child: KeyboardDismisser(
          child: Container(
            child: Form(
              key: bloc.formKey,
              child: Column(
                children: [
                  Expanded(
                    child: _widgetBody(),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ButtonWidget(
                      title: 'Cập nhật',
                      onPressed: () {
                        bloc.onSubmit();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _widgetBody() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ItemColumnWidget(
              title: 'Lô',
              child: ValueListenableBuilder<String>(
                valueListenable: bloc.selectedPlot,
                builder: (context, selected, _) {
                  return ValueListenableBuilder<List<ItemDropDown>>(
                    valueListenable: bloc.plots,
                    builder: (context, plots, _) {
                      return DropdownBottomSheet(
                        dataSources: plots,
                        initValue: selected,
                        onSelected: (val) {
                          bloc.selectedPlot.value = val.key ?? '';
                        },
                        hint: 'Lô',
                      );
                    },
                  );
                },
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ItemColumnWidget(
              title: 'Tên sản phẩm',
              child: TextFieldNormal(
                controller: bloc.productNameCtl,
                maxLines: 1,
                hint: 'Tên sản phẩm',
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ItemColumnWidget(
              title: 'Mô tả',
              child: TextFieldNormal(
                controller: bloc.descriptionCtl,
                maxLines: 1,
                hint: 'Mô tả',
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ItemColumnWidget(
              title: 'Số lượng tem',
              child: TextFieldNormal(
                controller: bloc.quantityCtl,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                ],
                maxLines: 1,
                hint: 'Số lượng tem',
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ItemColumnWidget(
              title: 'Hạn sử dụng (ngày)',
              child: TextFieldNormal(
                controller: bloc.expiredDateCtl,
                maxLines: 1,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                ],
                hint: 'Hạn sử dụng (ngày)',
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ItemColumnWidget(
              title: 'Mẫu tem',
              child: ValueListenableBuilder<String>(
                valueListenable: bloc.selectedStampType,
                builder: (context, selected, _) {
                  return ValueListenableBuilder<List<ItemDropDown>>(
                    valueListenable: bloc.stampTypes,
                    builder: (context, types, _) {
                      return DropdownBottomSheet(
                        dataSources: types,
                        initValue: selected,
                        onSelected: (val) {
                          bloc.selectedStampType.value = val.key ?? '';
                        },
                        hint: 'Mẫu tem',
                      );
                    },
                  );
                },
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            ValueListenableBuilder<String>(
              valueListenable: bloc.selectedStampType,
              builder: (context, selected, _) {
                if (selected.isEmpty) {
                  return const SizedBox.shrink();
                }
                var stamp = bloc.stampTypeRaws.firstWhere(
                  (e) => selected == e.id?.toString(),
                  orElse: () => StampType(),
                );
                return Container(
                  child: CachedNetworkImage(
                    imageUrl: stamp.exampleStampImage ?? '',
                    width: Get.width,
                    height: Get.width / 2,
                    fit: BoxFit.contain,
                    placeholder: (context, url) => Icon(
                      Icons.image,
                      size: 100,
                      color: Colors.grey[200],
                    ),
                    errorWidget: (context, url, _) => Icon(
                      Icons.image_not_supported,
                      size: 100,
                      color: Colors.grey[200],
                    ),
                  ),
                );
              },
            ),
            const SizedBox(
              height: 16,
            ),
          ],
        ),
      ),
    );
  }
}
