// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/diologs/diolog_add_location.dart';
import 'package:qadirneyriz/diologs/diolog_add_subject.dart';
import 'package:qadirneyriz/global/global_class/selected_item.dart';

import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/screens/meeting_edit/state.dart';
import 'package:qadirneyriz/screens/private_meeting_edit/state.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/utils/tools/tools.dart';
import 'package:qadirneyriz/widgets/ExpansionTileCustom.dart';
import 'package:qadirneyriz/widgets/checkBox_inTile.dart';
import 'package:qadirneyriz/widgets/custom_appbar.dart';
import 'package:qadirneyriz/widgets/custom_button.dart';
import 'package:qadirneyriz/widgets/custom_textfield.dart';
import 'package:qadirneyriz/widgets/empty_widget.dart';
import 'package:qadirneyriz/widgets/error_widget.dart';
import 'package:qadirneyriz/widgets/loading_widget.dart';
import 'package:qadirneyriz/widgets/picker.dart';

class EditPrivateMeetingScreen extends StatefulWidget {
  final int id;
  const EditPrivateMeetingScreen({
    Key? key,
    required this.id,
  }) : super(key: key);

  @override
  State<EditPrivateMeetingScreen> createState() =>
      _EditPrivateMeetingScreenState();
}

class _EditPrivateMeetingScreenState extends State<EditPrivateMeetingScreen> {
  final _formKey = GlobalKey<FormState>(); // Key for form validation
// all states we have
  late EditPrivateMeetingState privateMeetingEditState;
  late GlobalState globalState;
  TextEditingController visitorName = TextEditingController();
  TextEditingController visitorPhoneController = TextEditingController();
  TextEditingController visitorRole = TextEditingController();
  TextEditingController visitorCompanyNameController = TextEditingController();
  @override
  void initState() {
    super.initState();

//set states
    privateMeetingEditState =
        Provider.of<EditPrivateMeetingState>(context, listen: false);
    globalState = Provider.of<GlobalState>(context, listen: false);

    Future.delayed(Duration.zero, () async {
      // get items
      await privateMeetingEditState.getOnePrivateMeeting(id: widget.id);
      await globalState.getAllFiltersItems(refresh: true);
// set variables

      if (privateMeetingEditState.onePrivateMeetingStatus[widget.id] ==
              Status.ready &&
          globalState.allFiltersStatus == Status.ready) {
        privateMeetingEditState.setAllVariablesAtStart(id: widget.id);
        visitorName.text = privateMeetingEditState.createdName;
        visitorPhoneController.text =
            privateMeetingEditState.createdPhoneNumber;
        visitorRole.text = privateMeetingEditState.createdRole;
        visitorCompanyNameController.text =
            privateMeetingEditState.createdCompanyName;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer2<EditPrivateMeetingState, GlobalState>(
        builder: (context, meetingEditState, globalState, child) {
          return CustomScrollView(
            slivers: <Widget>[
              CustomAppbar(
                  title: AppLocalizations.of(context)!.editprivatemeeting),
              SliverFillRemaining(
                  child: content(context, meetingEditState, globalState)),
            ],
          );
        },
      ),
    );
  }

  Widget content(BuildContext context, EditPrivateMeetingState meetingEditState,
      GlobalState globalState) {
    final itemOnePrivateMeetingStatus =
        meetingEditState.onePrivateMeetingStatus[widget.id];
    if (itemOnePrivateMeetingStatus == Status.ready &&
        globalState.allFiltersStatus == Status.ready) {
      final itemInOneMeeting =
          meetingEditState.onePrivateMeetingModel![widget.id]!;
      return Padding(
        // This is now wrapped inside SliverToBoxAdapter
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CustomTextField(
                    paddingHarizon: 0,
                    paddingVertical: 10,
                    label: AppLocalizations.of(context)!.visitorname,
                    hintText: '',
                    textEditingController: visitorName,
                    textInputType: TextInputType.text),
                CustomTextField(
                    paddingHarizon: 0,
                    paddingVertical: 10,
                    label: AppLocalizations.of(context)!.visitorrole,
                    hintText: '',
                    textEditingController: visitorRole,
                    textInputType: TextInputType.text),
                CustomTextField(
                    paddingHarizon: 0,
                    paddingVertical: 10,
                    label: AppLocalizations.of(context)!.phonenumber,
                    hintText: '',
                    textEditingController: visitorPhoneController,
                    textInputType: TextInputType.phone),
                CustomTextField(
                    paddingHarizon: 0,
                    paddingVertical: 10,
                    label: AppLocalizations.of(context)!.companyname,
                    hintText: '',
                    textEditingController: visitorCompanyNameController,
                    textInputType: TextInputType.text),
                // subject ExpansionTile
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: ExpansionTileCustom(
                    isForm: true,
                    subTitile: AppLocalizations.of(context)!.meetingsubject,
                    title: meetingEditState.selectedSubject.id != null
                        ? meetingEditState.selectedSubject.text ?? ''
                        : meetingEditState.onePrivateMeetingModel![widget.id]!
                                .subject!.subject ??
                            '',
                    widgets: <Widget>[
                      CheckBoxInTile(
                        text: AppLocalizations.of(context)!.newsubject,
                        onTap: () async {
                          await showDialog(
                            context: context, // این باید کانتکست فعلی باشد
                            builder: (BuildContext context) {
                              return AddSubjectDiolog();
                            },
                          );
                        },
                        hasIcon: true,
                        backColor: Colors.white,
                        textColor: Colors.black.withOpacity(.5),
                      ),
                      Column(
                        children: globalState.subjectsModel!.map((subject) {
                          bool isSelected =
                              meetingEditState.selectedSubject.id == subject.id;
                          return CheckBoxInTile(
                            backColor:
                                isSelected ? Color(0xff06CF64) : Colors.white,
                            textColor: isSelected ? Colors.white : Colors.black,
                            text: subject.subject ?? '',
                            hasIcon: false,
                            onTap: () {
                              setState(() {
                                meetingEditState.selectedSubject = ItemSelected(
                                    text: subject.subject ?? '',
                                    id: subject.id ??
                                        0); // Update selected location
                              });
                            },
                          );
                        }).toList(),
                      ),
                    ],
                  ),
                ),

                // Date Picker
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: PickerCustom(
                    showDate: meetingEditState.fromDate != null
                        ? meetingEditState.fromDate ?? ''
                        : itemInOneMeeting.dateJalali ?? '',
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) {
                          return Dialog(
                            child: Tools.shamsiDateCalendarWidget(
                              context,
                              (newDate) {
                                String fromDateString =
                                    '${newDate.year}/${newDate.month}/${newDate.day}';
                                meetingEditState.setFromDate(
                                    fromDateString); // Update the selected date
                              },
                            ),
                          );
                        },
                      );
                    },
                    isForm: true,
                    title: AppLocalizations.of(context)!.date,
                  ),
                ),

                // From and To time Range Pickers
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 15.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      PickerCustom(
                        showDate: meetingEditState.selectedStartTime != null
                            ? Tools.formatTime(
                                meetingEditState.selectedStartTime!.hour,
                                meetingEditState.selectedStartTime!.minute)
                            : itemInOneMeeting.azHour ?? '',
                        onTap: () async {
                          TimeOfDay? picked = await showTimePicker(
                            context: context,
                            initialTime: meetingEditState.selectedStartTime!,
                          );
                          if (picked != null &&
                              picked != meetingEditState.selectedStartTime)
                            setState(() {
                              meetingEditState.selectedStartTime = picked;
                            });
                        },
                        isForm: true,
                        icon: Icons.access_time_outlined,
                        title: AppLocalizations.of(context)!.clock,
                      ),
                      Text(AppLocalizations.of(context)!.to),
                      PickerCustom(
                        showDate: meetingEditState.selectedEndTime != null
                            ? Tools.formatTime(
                                meetingEditState.selectedEndTime!.hour,
                                meetingEditState.selectedEndTime!.minute)
                            : itemInOneMeeting.taHour ?? '',
                        isForm: true,
                        icon: Icons.access_time_outlined,
                        onTap: () async {
                          TimeOfDay? picked = await showTimePicker(
                            context: context,
                            initialTime: meetingEditState.selectedEndTime!,
                          );
                          if (picked != null &&
                              picked != meetingEditState.selectedEndTime)
                            setState(() {
                              meetingEditState.selectedEndTime = picked;
                            });
                        },
                      ),
                    ],
                  ),
                ),

                // Location ExpansionTile
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: ExpansionTileCustom(
                    isForm: true,
                    subTitile: AppLocalizations.of(context)!.location,
                    title: meetingEditState.selectedLocation.id != null
                        ? meetingEditState.selectedLocation.text ?? ''
                        : itemInOneMeeting.location!.address ?? '',
                    widgets: <Widget>[
                      CheckBoxInTile(
                        text: AppLocalizations.of(context)!.newlocation,
                        onTap: () async {
                          await showDialog(
                            context: context, // این باید کانتکست فعلی باشد
                            builder: (BuildContext context) {
                              return AddLocationDiolog();
                            },
                          );
                        },
                        hasIcon: true,
                        backColor: Colors.white,
                        textColor: Colors.black.withOpacity(.5),
                      ),
                      Column(
                        children: globalState.locationsModel!.map((location) {
                          bool isSelected =
                              meetingEditState.selectedLocation.id ==
                                  location.id;
                          return CheckBoxInTile(
                            backColor:
                                isSelected ? Color(0xff06CF64) : Colors.white,
                            textColor: isSelected ? Colors.white : Colors.black,
                            text: location.address ?? '',
                            hasIcon: false,
                            onTap: () {
                              setState(() {
                                meetingEditState.selectedLocation =
                                    ItemSelected(
                                        text: location.address,
                                        id: location
                                            .id); // Update selected location
                              });
                            },
                          );
                        }).toList(),
                      ),
                    ],
                  ),
                ),

                // Final ExpansionTile if required
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                  child: ExpansionTileCustom(
                    isForm: true,
                    subTitile: AppLocalizations.of(context)!.meetingmanager,
                    title: meetingEditState.selectedManager.id != null
                        ? meetingEditState.selectedManager.text ?? ''
                        : itemInOneMeeting.manager!.name ?? '',
                    widgets: <Widget>[
                      Column(
                        children:
                            globalState.meetingsManagerModel!.map((manager) {
                          bool isSelected =
                              meetingEditState.selectedManager.id == manager.id;
                          return CheckBoxInTile(
                            backColor:
                                isSelected ? Color(0xff06CF64) : Colors.white,
                            textColor: isSelected ? Colors.white : Colors.black,
                            text: manager.name ?? '',
                            hasIcon: false,
                            onTap: () {
                              setState(() {
                                meetingEditState.selectedManager = ItemSelected(
                                    id: manager.id,
                                    text: manager
                                        .name); // Update selected manager
                              });
                            },
                          );
                        }).toList(),
                      ),
                    ],
                  ),
                ),

                // Submit Button
                SizedBox(
                  height: 60,
                ),
                submit(context)
              ],
            ),
          ),
        ),
      );
    } else if (itemOnePrivateMeetingStatus == Status.loading ||
        globalState.allFiltersStatus == Status.loading) {
      return const LoadingWidget();
    } else if (itemOnePrivateMeetingStatus == Status.error ||
        globalState.allFiltersStatus == Status.error) {
      return CustomErrorWidget(
        onPressed: () async {
          await privateMeetingEditState.getOnePrivateMeeting(
              id: widget.id, refresh: true);
          await globalState.getAllFiltersItems(refresh: true);
        },
      );
    } else if (itemOnePrivateMeetingStatus == Status.empty ||
        globalState.allFiltersStatus == Status.empty) {
      return EmptyStateWidget();
    } else {
      return Container();
    }
  }

  CustomButton submit(BuildContext context) {
    switch (privateMeetingEditState.statusEditPrivateMeeting) {
      case Status.loading:
        return CustomButton(
            width: double.infinity,
            hieght: 50,
            fontSize: 16,
            onPressed: null,
            text: AppLocalizations.of(context)!.loading);

      default:
        return CustomButton(
            width: double.infinity,
            hieght: 50,
            fontSize: 16,
            onPressed: () async {
              final status = await privateMeetingEditState.editPrivateMeeting(
                  id: widget.id,
                  locationId: privateMeetingEditState.selectedLocation.id ?? -1,
                  subjectId: privateMeetingEditState.selectedSubject.id ?? -1,
                  managerId: privateMeetingEditState.selectedManager.id ?? -1,
                  fromHour: Tools.formatTime(
                      privateMeetingEditState.selectedStartTime!.hour,
                      privateMeetingEditState.selectedStartTime!.minute),
                  toHour: Tools.formatTime(
                      privateMeetingEditState.selectedEndTime!.hour,
                      privateMeetingEditState.selectedEndTime!.minute),
                  dateMeeting: privateMeetingEditState.fromDate ?? '',
                  visitorRole: visitorName.text,
                  visitorCompany: visitorCompanyNameController.text,
                  visitorMobile: visitorPhoneController.text,
                  visitorName: visitorName.text);
              if (status == Status.ready) {
                context.pop();
                Tools.showCustomSnackBar(
                  text: AppLocalizations.of(context)!.editdone,
                  isError: false,
                  context,
                );
              } else {
                Tools.showCustomSnackBar(
                  text: privateMeetingEditState.errorsEditPrivateMeeting == null
                      ? privateMeetingEditState.messageEditPrivateMeeting ??
                          AppLocalizations.of(context)!.haserror
                      : Tools.combineErrorMessages(
                          privateMeetingEditState.errorsEditPrivateMeeting ??
                              {}),
                  isError: true,
                  context,
                );
              }
            },
            text: AppLocalizations.of(context)!.submit);
    }
  }
}
