import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/string_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/constants/meet_constants.dart';
import 'package:hamlemuhcrm/features/calendar/view_mixin/add_meet_one_view_mixin.dart';
import 'package:hamlemuhcrm/features/calendar/view/add_meet_second_view.dart';
import 'package:hamlemuhcrm/features/calendar/widgets/meet_repeating_dropdown.dart';
import 'package:hamlemuhcrm/features/calendar/widgets/select_meet_manager_dropdown.dart';

import 'package:hamlemuhcrm/features/customers/widgets/interview_type_dd.dart';
import '../../../core/constants/app_constants.dart';
import '../../../core/constants/color_constants.dart';
import '../../../core/utility/toast_manager.dart';
import '../../customers/cubit/customers_cubit.dart';
import '../cubit/calendar_cubit.dart';
import '../utility/calendar_textfield_input.dart';
import '../../../core/constants/font_styles.dart';
import '../../../core/extensions/responsive_extension.dart';
import '../../../core/extensions/svg_enum_extension.dart';
import '../widgets/select_project_dropdown.dart';

class AddMeetOneView extends StatefulWidget {
  const AddMeetOneView({Key? key}) : super(key: key);
  @override
  State<AddMeetOneView> createState() => _AddMeetOneViewState();
}

class _AddMeetOneViewState extends State<AddMeetOneView>
    with AddMeetOneViewMixin {
  @override
  Widget build(BuildContext context) {
    return isLoading
        ? _isLoadingEffect
        : Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              title: Text(MeetConstants.instance.addMeetPageOneTxt,
                  style: FontStyles.instance.appbarTitleStyle),
              centerTitle: true,
              leading: IconButton(
                onPressed: () {
                  Navigator.of(context).popUntil((route) => route.isFirst);
                },
                icon: const Icon(
                  Icons.arrow_back_ios_new,
                  color: Colors.black54,
                  size: 20,
                ),
              ),
            ),
            body: SingleChildScrollView(
              child: Padding(
                padding: _pagePaddingHorizontal,
                child: _form(
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      _pageImage,
                      _headlineToContainerHeightSpace,
                      _headLine(MeetConstants.instance.meetHeadlineTxt),
                      _headlineToContainerHeightSpace,
                      _tfContainer(tfToplantiAd),
                      _emptyMiddleHeightSpace,
                      _headLine(MeetConstants.instance.meetSessionNameTxt),
                      _headlineToContainerHeightSpace,
                      _tfContainer(tfToplantiGundem),
                      _emptyMiddleHeightSpace,
                      _headLine(MeetConstants.instance.meetProjectTxt),
                      _emptyMiddleHeightSpace,
                      const SelectProjectDropdown(),
                      _emptyMiddleHeightSpace,
                      _headLine(MeetConstants.instance.meetManagerTxt),
                      _emptyMiddleHeightSpace,
                      // Toplantı Eklerken Yönetici Kısmında İlk Olarak Giriş Yapan Kullanıcı Seçili Gelecek
                      SelectMeetManagerDropdown(
                          initialManagerIdValue: context.read<LoginCubit>().id),
                      _emptyMiddleHeightSpace,
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _headLine(MeetConstants.instance.meetTypeTxt),
                              _headlineToContainerHeightSpace,
                              const InterViewTypeDD(
                                isShadow: false,
                                isShort: true,
                              ),
                            ],
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _headLine(MeetConstants.instance.meetRepeatTxt),
                              _headlineToContainerHeightSpace,
                              const MeetRepeatingDropdown(),
                            ],
                          ),
                        ],
                      ),
                      _emptyMiddleHeightSpace,
                      _headLine(MeetConstants.instance.meetFromTxt),
                      _headlineToContainerHeightSpace,
                      _tfContainer(tfToplantiYeri),
                      _emptyMiddleHeightSpace,
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [_meetDateChangeContainer, _tfTimeContainer],
                      ),
                      _emptyMiddleHeightSpace,
                      _headLine(MeetConstants.instance.meetDescriptionTxt),
                      _headlineToContainerHeightSpace,
                      _tfContainer(tfToplantiAciklama, isLongInput: true),
                      _emptyMiddleHeightSpace,
                      _nextPageButton
                    ],
                  ),
                ),
              ),
            ));
  }

  Widget get _emptyMiddleHeightSpace => SizedBox(
        height: context.dynamicHeight(0.012),
      );

  EdgeInsets get _pagePaddingHorizontal =>
      EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.06));

  Widget _form(Widget child) {
    return Form(key: AddMeetOneViewMixin.addMeetKey, child: child);
  }

  Widget get _pageImage =>
      Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        SizedBox(
            height: context.dynamicHeight(0.15), child: SvgEnums.meet.toSvg)
      ]);

  Widget _headLine(String title,
      {String description = '', bool isRequired = true}) {
    return Row(
      children: [
        Text(
          title,
          style: FontStyles.instance.employeetbxBaslik,
        ),
        SizedBox(
          width: context.dynamicWidth(0.01),
        ),
        Text(
          isRequired ? '(*$description)' : '',
          style: FontStyles.instance.employeetbxRequired,
        ),
      ],
    );
  }

  Widget _tfContainer(TextEditingController tf, {bool isLongInput = false}) =>
      Container(
          height: context.dynamicHeight(isLongInput ? 0.1 : 0.05),
          width: context.dynamicWidth(0.88),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.grey.shade400),
              borderRadius: BorderRadius.circular(10)),
          child: _textFormField(tf, isLongInput: isLongInput ? true : false));

  Widget _textFormField(TextEditingController tfcontroller,
          {bool isLongInput = false}) =>
      TextFormField(
        style: FontStyles.instance.meetGeneralStyle,
        controller: tfcontroller,
        magnifierConfiguration: TextMagnifierConfiguration.disabled,
        decoration: CalendarTextFieldInput(context,
            isLongInput: isLongInput ? true : false),
        maxLines: isLongInput ? 10 : 1,
        cursorColor: ColorsConstants.instance.baseTheme,
      );

  Widget get _tfTimeContainer => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _headLine(MeetConstants.instance.meetTimeTxt,
                description: MeetConstants.instance.meetTimeSubtitleTxt),
            _headlineToContainerHeightSpace,
            Container(
                height: context.dynamicHeight(0.05),
                width: context.dynamicWidth(0.38),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(color: Colors.grey.shade400),
                    borderRadius: BorderRadius.circular(10)),
                child: _textformfieldTime),
          ]);

  Widget get _textformfieldTime => TextFormField(
      style: FontStyles.instance.meetGeneralStyle,
      controller: tfToplantiSure,
      magnifierConfiguration: TextMagnifierConfiguration.disabled,
      keyboardType: TextInputType.number,
      inputFormatters: <TextInputFormatter>[
        FilteringTextInputFormatter.digitsOnly,
        LengthLimitingTextInputFormatter(1)
      ],
      cursorColor: ColorsConstants.instance.baseTheme,
      decoration: timeTextFieldInput);

  InputDecoration get timeTextFieldInput => InputDecoration(
      suffixIcon: Icon(
        Icons.timelapse_rounded,
        color: ColorsConstants.instance.iconColor,
      ),
      contentPadding:
          EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.02)),
      border: const OutlineInputBorder(borderSide: BorderSide.none));

  dateTimePickerWidget(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy HH:mm',
      locale: DateTimePickerLocale.tr,
      initialDateTime: DateTime.now(),
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: saatSecildi
            ? Text(
                'Değiştir',
                style: TextStyle(color: ColorsConstants.instance.baseTheme),
              )
            : Text(
                'Yeni Tarih Seç',
                style: TextStyle(color: ColorsConstants.instance.baseTheme),
              ),
      ),
      onMonthChangeStartWithFirstDate: true,
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate = dateTime;
        final selIOS = DateFormat('yyyy-MM-dd HH:mm').format(selectdate);
        setState(() {
          dbSaat = '$selIOS:00';
          dbSaat == '' ? saatSecildi = false : saatSecildi = true;
          gosterilenSaat = dbSaat.substring(0, 16);
          debugPrint('gosterılenSaat : $gosterilenSaat');
          gosterilenSaat = ''.toTrTypeNoHour(gosterilenSaat);
          debugPrint('gosterılenSaat : $gosterilenSaat');
          debugPrint('dbSaat : $dbSaat');
          // final DateFormat format = DateFormat.yMd('tr');
          // var trTarih = format.format(DateTime.parse(gosterilenSaat));
          // gosterilenSaat = trTarih;
        });
      },
    );
  }

  Widget get _headlineToContainerHeightSpace => SizedBox(
        height: context.dynamicHeight(0.01),
      );

  Widget get _meetDateChangeContainer => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _headLine('Toplantı Tarihi'),
          _headlineToContainerHeightSpace,
          _containerDate,
        ],
      );

  Widget get _containerDate {
    return Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.42),
        padding: const EdgeInsets.only(left: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade400),
        ),
        child: _containerDateRow);
  }

  Widget get _containerDateRow => Row(
        children: [
          Text(
            gosterilenSaat,
            style: FontStyles.instance.meetGeneralStyle,
          ),
          const Spacer(),
          IconButton(
              onPressed: () {
                dateTimePickerWidget(context);
              },
              tooltip: 'Tarih Seç',
              padding: EdgeInsets.zero,
              icon: Icon(
                Icons.calendar_month,
                size: 20,
                color: ColorsConstants.instance.iconColor,
              )),
        ],
      );

  Widget get _nextPageButton => TextButton(
        onPressed: () {
          _nextToPage();
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme,
        ),
        child: Center(
          child: Text(
            ApplicationConstants.instance.moduleNextTxt,
            style: const TextStyle(color: Colors.white),
          ),
        ),
      );

  Future<void> _nextToPage() async {
    if (context.read<CalendarCubit>().secilenProjeFirmaID.isNotEmpty &&
        context.read<CalendarCubit>().secilenProjeID.isNotEmpty &&
        context.read<CustomersCubit>().secilenGorusmeTipi.isNotEmpty &&
        context.read<CalendarCubit>().secilenToplantiYoneticiID.isNotEmpty &&
        dbSaat.isNotEmpty &&
        tfToplantiAd.text.isNotEmpty &&
        tfToplantiGundem.text.isNotEmpty &&
        tfToplantiSure.text.isNotEmpty &&
        tfToplantiYeri.text.isNotEmpty &&
        tfToplantiAciklama.text.isNotEmpty) {
      Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => AddMeetSecondView(
                tfBaslik: tfToplantiAd.text,
                tfGundem: tfToplantiGundem.text,
                tfToplantiYeri: tfToplantiYeri.text,
                tfToplantiAciklama: tfToplantiAciklama.text,
                toplantiYoneticiId:
                    context.read<CalendarCubit>().secilenToplantiYoneticiID,
                alinanSure: tfToplantiSure.text,
                alinanTarih: dbSaat,
                projeFirmaId: context.read<CalendarCubit>().secilenProjeFirmaID,
                projeid: context.read<CalendarCubit>().secilenProjeID,
              )));
      return;
    }
    ToastManager.instance.toastMessageService('Gerekli Alanlar Eksik');
  }

  Widget get _isLoadingEffect => const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
}
