import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/config/config.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/global/global_class/selected_item.dart';
import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/screens/meeting_add/state.dart';
import 'package:qadirneyriz/screens/private_meeting_add/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:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:qadirneyriz/widgets/custom_button.dart';
import 'package:qadirneyriz/widgets/custom_textfield.dart';
import 'package:qadirneyriz/widgets/ink_warpper.dart';
import 'package:qadirneyriz/widgets/loading_widget.dart';
import 'package:qadirneyriz/widgets/picker.dart';

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

  @override
  State<PrivateMeetingAddScreen> createState() =>
      _PrivateMeetingAddScreenState();
}

class _PrivateMeetingAddScreenState extends State<PrivateMeetingAddScreen> {
  bool isPrivateMeeting = false;
  final _formKey = GlobalKey<FormState>(); // Key for form validation
  // all states we have
  TextEditingController visitorName = TextEditingController();
  TextEditingController visitorPhoneController = TextEditingController();
  TextEditingController visitorRole = TextEditingController();
  TextEditingController visitorCompanyNameController = TextEditingController();
  late GlobalState globalState;

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

//set states

    globalState = Provider.of<GlobalState>(context, listen: false);
    Future.delayed(Duration.zero, () async {
      // get items
      await globalState.getAllFiltersItems();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          CustomAppbar(
            title: AppLocalizations.of(context)!.addnewprivatemeeting,
          ),
          SliverFillRemaining(child: content(context)),
        ],
      ),
    );
  }

  Widget content(BuildContext context) {
    return Consumer2<GlobalState, PrivateMeetingAddState>(
      builder: (context, stateGlobal, meetingAddState, child) {
        switch (stateGlobal.allFiltersStatus) {
          case Status.ready:
            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:
                              AppLocalizations.of(context)!.nameandfamilyname,
                          textInputAction: TextInputAction.next,
                          textEditingController: visitorName,
                          textInputType: TextInputType.text),
                      CustomTextField(
                          paddingHarizon: 0,
                          paddingVertical: 10,
                          label: AppLocalizations.of(context)!.visitorrole,
                          hintText: AppLocalizations.of(context)!.visitorrole,
                          textEditingController: visitorRole,
                          textInputAction: TextInputAction.next,
                          textInputType: TextInputType.text),
                      CustomTextField(
                          paddingHarizon: 0,
                          paddingVertical: 10,
                          label: AppLocalizations.of(context)!.phonenumber,
                          hintText: AppLocalizations.of(context)!.phonenumber,
                          textEditingController: visitorPhoneController,
                          textInputAction: TextInputAction.next,
                          textInputType: TextInputType.phone),
                      CustomTextField(
                          paddingHarizon: 0,
                          paddingVertical: 10,
                          label: AppLocalizations.of(context)!.companyname,
                          hintText: AppLocalizations.of(context)!.companyname,
                          textEditingController: visitorCompanyNameController,
                          textInputAction: TextInputAction.done,
                          textInputType: TextInputType.text),

                      // subject ExpansionTile
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: ExpansionTileCustom(
                          isForm: true,
                          subTitile:
                              AppLocalizations.of(context)!.meetingsubject,
                          title: meetingAddState.selectedSubject.id != null
                              ? meetingAddState.selectedSubject.text ?? ''
                              : AppLocalizations.of(context)!.selectsubject,
                          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 =
                                    meetingAddState.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(() {
                                      meetingAddState.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: meetingAddState.fromDate ??
                              AppLocalizations.of(context)!.selectdate,
                          onTap: () {
                            showDialog(
                              context: context,
                              builder: (context) {
                                return Dialog(
                                  child: Tools.shamsiDateCalendarWidget(
                                    context,
                                    (newDate) {
                                      setState(() {
                                        String fromDateString =
                                            '${newDate.year}/${newDate.month}/${newDate.day}';
                                        meetingAddState
                                            .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: Tools.formatTime(
                                  meetingAddState.selectedStartTime.hour,
                                  meetingAddState.selectedStartTime.minute),
                              onTap: () async {
                                TimeOfDay? picked = await showTimePicker(
                                  context: context,
                                  initialTime:
                                      meetingAddState.selectedStartTime,
                                );
                                if (picked != null &&
                                    picked != meetingAddState.selectedStartTime)
                                  setState(() {
                                    meetingAddState.selectedStartTime = picked;
                                  });
                              },
                              isForm: true,
                              icon: Icons.access_time_outlined,
                              title: AppLocalizations.of(context)!.clock,
                            ),
                            Text(AppLocalizations.of(context)!.to),
                            PickerCustom(
                              showDate: Tools.formatTime(
                                  meetingAddState.selectedEndTime.hour,
                                  meetingAddState.selectedEndTime.minute),
                              isForm: true,
                              icon: Icons.access_time_outlined,
                              onTap: () async {
                                TimeOfDay? picked = await showTimePicker(
                                  context: context,
                                  initialTime: meetingAddState.selectedEndTime,
                                );
                                if (picked != null &&
                                    picked != meetingAddState.selectedEndTime)
                                  setState(() {
                                    meetingAddState.selectedEndTime = picked;
                                  });
                              },
                            ),
                          ],
                        ),
                      ),

                      // Location ExpansionTile
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: ExpansionTileCustom(
                          isForm: true,
                          subTitile: AppLocalizations.of(context)!.location,
                          title: meetingAddState.selectedLocation.text ??
                              AppLocalizations.of(context)!.selectlocation,
                          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 =
                                    meetingAddState.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(() {
                                      meetingAddState.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 = meetingAddState
                                          .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) {
                                                meetingAddState
                                                    .selectedUsersItems
                                                    .remove(user.id);
                                              } else {
                                                meetingAddState
                                                    .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()
                                  : [],
                            ),
                          ],
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            isPrivateMeeting = !isPrivateMeeting;
                          });
                        },
                        child: Padding(
                          padding: const EdgeInsets.symmetric(vertical: 15),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                AppLocalizations.of(context)!
                                    .isprivateprivatemeeting,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontWeight: FontWeight.normal,
                                  fontSize: 13,
                                  color: Colors.black.withOpacity(.8),
                                ),
                              ),
                              Checkbox(
                                  value: isPrivateMeeting,
                                  onChanged: (f) {
                                    setState(() {
                                      isPrivateMeeting = f ?? false;
                                    });
                                  }),
                            ],
                          ),
                        ),
                      ),

                      // Final ExpansionTile if required
                      Visibility(
                        visible: !isPrivateMeeting,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(vertical: 10.0),
                          child: ExpansionTileCustom(
                            isForm: true,
                            subTitile:
                                AppLocalizations.of(context)!.meetingmanager,
                            title: meetingAddState.selectedManager.text ??
                                AppLocalizations.of(context)!
                                    .selectmeetingmanager,
                            widgets: <Widget>[
                              Column(
                                children: globalState.meetingsManagerModel!
                                    .map((manager) {
                                  bool isSelected =
                                      meetingAddState.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(() {
                                        meetingAddState.selectedManager =
                                            ItemSelected(
                                                id: manager.id,
                                                text: manager
                                                    .name); // Update selected manager
                                      });
                                    },
                                  );
                                }).toList(),
                              ),
                            ],
                          ),
                        ),
                      ),

                      // Submit Button

                      SizedBox(
                        height: 60,
                      ),
                      Consumer<PrivateMeetingAddState>(
                        builder: (context, value, child) {
                          return submit(context, value);
                        },
                      ),
                    ],
                  ),
                ),
              ),
            );
          case Status.loading:
            return const LoadingWidget();
          default:
            return Container();
        }
      },
    );
  }

  CustomButton submit(BuildContext context, PrivateMeetingAddState state) {
    switch (state.statusAddMeeting) {
      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 state.addPrivateMeeting(
                  locationId: state.selectedLocation.id,
                  subjectId: state.selectedSubject.id,
                  managerId:
                      !isPrivateMeeting ? state.selectedManager.id : null,
                  fromHour: Tools.formatTime(state.selectedStartTime.hour,
                      state.selectedStartTime.minute),
                  toHour: Tools.formatTime(
                      state.selectedEndTime.hour, state.selectedEndTime.minute),
                  dateMeeting: state.fromDate ?? '',
                  visitorName: visitorName.text,
                  visitorCompany: visitorCompanyNameController.text,
                  visitorMobile: visitorPhoneController.text,
                  visitorRole: visitorRole.text);
              if (status == Status.ready) {
                context.pushNamed('navigate', pathParameters: {'tab': '2'});
                Tools.showCustomSnackBar(
                  text: AppLocalizations.of(context)!.addprivatemeetingdone,
                  isError: false,
                  context,
                );
              } else {
                Tools.showCustomSnackBar(
                  text: state.errorsAddMeeting == null
                      ? state.messageAddMeeting ??
                          AppLocalizations.of(context)!.haserror
                      : Tools.combineErrorMessages(
                          state.errorsAddMeeting ?? {}),
                  isError: true,
                  context,
                );
              }
            },
            text: AppLocalizations.of(context)!.submit);
    }
  }
}
