// 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/global/global_class/selected_item.dart';
import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/diologs/diolog_add_location.dart';
import 'package:qadirneyriz/diologs/diolog_add_subject.dart';
import 'package:qadirneyriz/diologs/diolog_add_user.dart';
import 'package:qadirneyriz/screens/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/ink_warpper.dart';
import 'package:qadirneyriz/widgets/loading_widget.dart';
import 'package:qadirneyriz/widgets/picker.dart';

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

  @override
  State<MeetingEditScreen> createState() => _MeetingEditScreenState();
}

class _MeetingEditScreenState extends State<MeetingEditScreen> {
  final _formKey = GlobalKey<FormState>(); // Key for form validation
// all states we have
  late MeetingEditState meetingEditState;
  late GlobalState globalState;

  @override
  void initState() {
    super.initState();

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

    Future.delayed(Duration.zero, () async {
      // get items
      await meetingEditState.getOneMeeting(id: widget.id);
      await globalState.getAllFiltersItems();
// set variables
      meetingEditState.setAllVariablesAtStart(id: widget.id);
    });
  }

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

  Widget content(BuildContext context, MeetingEditState meetingEditState,
      GlobalState globalState) {
    if (meetingEditState.oneMeetingStatus[widget.id] == Status.ready &&
        globalState.allFiltersStatus == Status.ready) {
      final itemInOneMeeting = meetingEditState.oneMeetingModel![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: [
                // 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
                                    .oneMeetingModel![widget.id]!.subject !=
                                null
                            ? meetingEditState.oneMeetingModel![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 != null
                            ? 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(),
                      ),
                    ],
                  ),
                ),

                // Another ExpansionTile for users
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: ExpansionTileCustom(
                    isForm: true,
                    subTitile: AppLocalizations.of(context)!.users,
                    title: AppLocalizations.of(context)!.selectusers,
                    widgets: <Widget>[
                      CheckBoxInTile(
                        text: AppLocalizations.of(context)!.newmember,
                        onTap: () async {
                          await showDialog(
                            context: context, // این باید کانتکست فعلی باشد
                            builder: (BuildContext context) {
                              return AddUserDiolog();
                            },
                          );
                        },
                        hasIcon: true,
                        backColor: Colors.white,
                        textColor: Colors.black.withOpacity(.5),
                      ),
                      Column(
                        children: globalState.usersModel != null
                            ? globalState.usersModel!.map((user) {
                                bool isSelected = meetingEditState
                                    .selectedUsersItems
                                    .contains(user.id);
                                return Container(
                                  margin: EdgeInsets.symmetric(
                                      vertical: 5.0, horizontal: 10),
                                  decoration: BoxDecoration(
                                    color: isSelected
                                        ? Color(0xff06CF64)
                                        : Colors.white,
                                    borderRadius: BorderRadius.circular(10),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black12,
                                        blurRadius: 8,
                                        offset: Offset(0, 4),
                                      ),
                                    ],
                                  ),
                                  child: InkWrapper(
                                    onTap: () {
                                      setState(() {
                                        if (isSelected) {
                                          meetingEditState.selectedUsersItems
                                              .remove(user.id);
                                        } else {
                                          meetingEditState.selectedUsersItems
                                              .add(user.id ?? 0);
                                        }
                                      });
                                    },
                                    child: Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Row(
                                        children: [
                                          Text(
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            user.name ?? '',
                                            style: TextStyle(
                                              fontSize: 12,
                                              color: isSelected
                                                  ? Colors.white
                                                  : Colors.black,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              }).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 != null
                            ? 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 (meetingEditState.oneMeetingStatus[widget.id] == Status.loading ||
        globalState.allFiltersStatus == Status.loading) {
      return const LoadingWidget();
    } else {
      return Container();
    }
  }

  CustomButton submit(BuildContext context) {
    switch (meetingEditState.statusEitMeeting) {
      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 meetingEditState.editMeeting(
                  id: widget.id,
                  locationId: meetingEditState.selectedLocation.id ?? -1,
                  subjectId: meetingEditState.selectedSubject.id ?? -1,
                  managerId: meetingEditState.selectedManager.id ?? -1,
                  fromHour: Tools.formatTime(
                      meetingEditState.selectedStartTime!.hour,
                      meetingEditState.selectedStartTime!.minute),
                  toHour: Tools.formatTime(
                      meetingEditState.selectedEndTime!.hour,
                      meetingEditState.selectedEndTime!.minute),
                  dateMeeting: meetingEditState.fromDate ?? '',
                  members: meetingEditState.selectedUsersItems);
              if (status == Status.ready) {
                context.pop();
                Tools.showCustomSnackBar(
                  text: AppLocalizations.of(context)!.editdone,
                  isError: false,
                  context,
                );
              } else {
                Tools.showCustomSnackBar(
                  text: meetingEditState.errorsEditMeeting == null
                      ? meetingEditState.messageEditMeeting ??
                          AppLocalizations.of(context)!.haserror
                      : Tools.combineErrorMessages(
                          meetingEditState.errorsEditMeeting ?? {}),
                  isError: true,
                  context,
                );
              }
            },
            text: AppLocalizations.of(context)!.submit);
    }
  }
}
