// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/screens/private_meeting/state.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/widgets/ExpansionTileCustom.dart';
import 'package:qadirneyriz/widgets/error_widget.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/utils/tools/tools.dart';
import 'package:qadirneyriz/widgets/picker.dart';
import 'package:qadirneyriz/widgets/loading_widget.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

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

  @override
  State<DiologPrivateMeetingsFilters> createState() =>
      _DiologPrivateMeetingsFiltersState();
}

class _DiologPrivateMeetingsFiltersState
    extends State<DiologPrivateMeetingsFilters> {
  PrivateMeetingsState? privateMeetingsState;
  GlobalState? globalState;
  @override
  void initState() {
    privateMeetingsState =
        Provider.of<PrivateMeetingsState>(context, listen: false);
    globalState = Provider.of<GlobalState>(context, listen: false);
    Future.delayed(Duration.zero, () async {
      await globalState!.getAllFiltersItems();

      // print(status);
    });
    privateMeetingsState!.setAllFiltersForThen();
    super.initState();
  }

  @override
  void dispose() {
    // بررسی تغییرات فیلترها
    if (privateMeetingsState!.isAnyChangesInFilters()) {
      Future.microtask(() async {
        await privateMeetingsState!.getPrivateMeetings(
          refresh: true,
          toDate: privateMeetingsState!.toDate,
          fromDate: privateMeetingsState!.fromDate,
          location: privateMeetingsState!.selectedLocationId,
          subject: privateMeetingsState!.selectedSubjectId,
          meetingManager: privateMeetingsState!.selectedManagersId,
          meetingStatus: privateMeetingsState!.selectedStatusId,
        );
      });
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
        initialChildSize: .7,
        expand: false,
        snap: false,
        builder: (context, scrollController) {
          //  statuses meetings
          List<MeetingsStatus> meetingStatuses = [
            MeetingsStatus(
                id: 1, title: AppLocalizations.of(context)!.donemeetings),
            MeetingsStatus(
                id: 2, title: AppLocalizations.of(context)!.adjournedmeetings),
            MeetingsStatus(
                id: 3, title: AppLocalizations.of(context)!.canceldmeetings),
            MeetingsStatus(
                id: 4,
                title: AppLocalizations.of(context)!.meetingswaitingtobeheld),
          ];
          return Consumer2<PrivateMeetingsState, GlobalState>(
            builder: (context, privateMeetingsState, globalState, child) {
              switch (globalState.allFiltersStatus) {
                case Status.ready:
                  return Column(
                    children: [
                      LineButtomSheet(),
                      Expanded(
                        child: SingleChildScrollView(
                          controller: scrollController,
                          child: Column(
                            children: [
                              Column(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 25, horizontal: 15),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          AppLocalizations.of(context)!
                                              .searchFor,
                                        ),
                                        GestureDetector(
                                            onTap: () {
                                              privateMeetingsState
                                                  .clearFilters();
                                            },
                                            child: privateMeetingsState
                                                    .hasActiveFilters()
                                                ? Icon(
                                                    Icons.delete_outline,
                                                    color: Colors.red,
                                                  )
                                                : Icon(
                                                    Icons.delete_outline,
                                                    color: Colors.black
                                                        .withOpacity(.3),
                                                  ))
                                      ],
                                    ),
                                  ),
                                  Divider(),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  ExpansionTileCustom(
                                    title: AppLocalizations.of(context)!.date,
                                    widgets: <Widget>[
                                      Padding(
                                        padding: const EdgeInsets.all(20.0),
                                        child: Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            PickerCustom(
                                              showDate: privateMeetingsState
                                                      .fromDate.isNotEmpty
                                                  ? privateMeetingsState
                                                      .fromDate
                                                  : AppLocalizations.of(
                                                          context)!
                                                      .selectdate, // Show selected date or prompt
                                              onTap: () {
                                                showDialog(
                                                  context: context,
                                                  builder: (context) {
                                                    return Dialog(
                                                      child: Tools
                                                          .shamsiDateCalendarWidget(
                                                        context,
                                                        (newDate) {
                                                          String
                                                              fromDateString =
                                                              '${newDate.year}/${newDate.month}/${newDate.day}';
                                                          privateMeetingsState
                                                              .setFromDates(
                                                                  fromDateString); // Update the selected date
                                                        },
                                                      ),
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                            Text(
                                              AppLocalizations.of(context)!.to,
                                            ),
                                            PickerCustom(
                                              showDate: privateMeetingsState
                                                      .toDate.isNotEmpty
                                                  ? privateMeetingsState.toDate
                                                  : AppLocalizations.of(
                                                          context)!
                                                      .selectdate, // Show selected date or prompt
                                              onTap: () {
                                                showDialog(
                                                  context: context,
                                                  builder: (context) {
                                                    return Dialog(
                                                      child: Tools
                                                          .shamsiDateCalendarWidget(
                                                        context,
                                                        (newDate) {
                                                          String toDateString =
                                                              '${newDate.year}/${newDate.month}/${newDate.day}';
                                                          privateMeetingsState
                                                              .setToDates(
                                                                  toDateString); // Update the selected date
                                                        },
                                                      ),
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                  ExpansionTileCustom(
                                    title:
                                        AppLocalizations.of(context)!.location,
                                    widgets: <Widget>[
                                      ListView.builder(
                                        primary: false,
                                        physics: NeverScrollableScrollPhysics(),
                                        shrinkWrap: true,
                                        itemCount:
                                            globalState.locationsModel!.length,
                                        itemBuilder:
                                            (BuildContext context, int index) {
                                          final items = globalState
                                              .locationsModel![index];
                                          return RadioListTile<int>(
                                            toggleable: true,
                                            groupValue: privateMeetingsState
                                                .selectedLocationId,
                                            value: items.id ?? -1,
                                            title: Text(
                                              items.address ?? '',
                                              maxLines: 1,
                                              style: TextStyle(
                                                  fontWeight: FontWeight.w100,
                                                  fontSize: 14),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            activeColor: config.ui.secendGreen,
                                            onChanged: (int? newValue) {
                                              privateMeetingsState
                                                  .selectLocation(
                                                      newValue ?? null);
                                            },
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                  if (setting.userLocalDb.getUser().role != 1)
                                    ExpansionTileCustom(
                                      title: AppLocalizations.of(context)!
                                          .meetingmanager,
                                      widgets: <Widget>[
                                        ListView.builder(
                                          primary: false,
                                          physics:
                                              NeverScrollableScrollPhysics(),
                                          shrinkWrap: true,
                                          itemCount: globalState
                                              .meetingsManagerModel!.length,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            final items = globalState
                                                .meetingsManagerModel![index];
                                            return RadioListTile<int>(
                                              toggleable: true,
                                              groupValue: privateMeetingsState
                                                  .selectedManagersId,
                                              value: items.id ?? -1,
                                              title: Text(
                                                items.name ?? '',
                                                style: TextStyle(
                                                    fontWeight: FontWeight.w100,
                                                    fontSize: 14),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                              activeColor:
                                                  config.ui.secendGreen,
                                              onChanged: (int? newValue) {
                                                privateMeetingsState
                                                    .selectManager(
                                                        newValue ?? null);
                                              },
                                            );
                                          },
                                        ),
                                      ],
                                    ),
                                  ExpansionTileCustom(
                                    title:
                                        AppLocalizations.of(context)!.subject,
                                    widgets: <Widget>[
                                      ListView.builder(
                                        primary: false,
                                        physics: NeverScrollableScrollPhysics(),
                                        shrinkWrap: true,
                                        itemCount:
                                            globalState.subjectsModel!.length,
                                        itemBuilder:
                                            (BuildContext context, int index) {
                                          final items =
                                              globalState.subjectsModel![index];
                                          return RadioListTile<int>(
                                            toggleable: true,
                                            groupValue: privateMeetingsState
                                                .selectedSubjectId,
                                            value: items.id ?? -1,
                                            title: Text(
                                              items.subject ?? '',
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  fontWeight: FontWeight.w100,
                                                  fontSize: 14),
                                            ),
                                            activeColor: config.ui.secendGreen,
                                            onChanged: (int? newValue) {
                                              privateMeetingsState
                                                  .selectSubject(
                                                      newValue ?? null);
                                            },
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Divider(),
                                  Column(
                                    children: [
                                      SizedBox(
                                        height: 250,
                                        child: ListView.builder(
                                          physics:
                                              NeverScrollableScrollPhysics(),
                                          shrinkWrap: true,
                                          primary: false,
                                          itemCount: meetingStatuses.length,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            final items =
                                                meetingStatuses[index];
                                            return RadioListTile<int>(
                                              toggleable: true,
                                              groupValue: privateMeetingsState
                                                  .selectedStatusId,
                                              value: items.id,
                                              title: Text(
                                                items.title,
                                                maxLines: 1,
                                                style: TextStyle(
                                                    fontWeight: FontWeight.w100,
                                                    fontSize: 14),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                              activeColor:
                                                  config.ui.secendGreen,
                                              onChanged: (int? newValue) {
                                                privateMeetingsState
                                                    .selectStatusMeeting(
                                                        newValue ?? null);
                                              },
                                            );
                                          },
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  );
                case Status.loading:
                  return const LoadingWidget();
                case Status.error:
                  return CustomErrorWidget(
                    onPressed: () async {
                      await globalState.getAllFiltersItems(refresh: true);
                    },
                  );
                default:
                  return Container();
              }
            },
          );
        });
  }
}

class LineButtomSheet extends StatelessWidget {
  const LineButtomSheet({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 8.0),
      width: 30.0,
      height: 3.0,
      decoration: BoxDecoration(
        color: Colors.grey.shade400,
        borderRadius: BorderRadius.circular(24.0),
      ),
    );
  }
}

class MeetingsStatus {
  int id;
  String title;
  MeetingsStatus({
    required this.id,
    required this.title,
  });
}
