// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/global_state/global_state.dart';
import 'package:qadirneyriz/widgets/ExpansionTileCustom.dart';
import 'package:qadirneyriz/widgets/error_widget.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/screens/meeting/state.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 DiologMeetingsFilters extends StatefulWidget {
  const DiologMeetingsFilters({
    super.key,
  });

  @override
  State<DiologMeetingsFilters> createState() => _DiologMeetingsFiltersState();
}

class _DiologMeetingsFiltersState extends State<DiologMeetingsFilters> {
  MeetingsState? meetingsState;
  GlobalState? globalState;
  @override
  void initState() {
    meetingsState = Provider.of<MeetingsState>(context, listen: false);
    globalState = Provider.of<GlobalState>(context, listen: false);
    Future.delayed(Duration.zero, () async {
      final status = await globalState!.getAllFiltersItems();

      print(status);
    });
    super.initState();
  }

  @override
  void dispose() {
    Future.delayed(Duration.zero, () async {
      await meetingsState!.getMeetings(
          refresh: true,
          toDate: meetingsState!.toDate,
          fromDate: meetingsState!.fromDate,
          location: meetingsState!.selectedLocationId,
          subject: meetingsState!.selectedSubjectId,
          meetingManager: meetingsState!.selectedManagersId,
          meetingStatus: meetingsState!.selectedStatusId);
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
        initialChildSize: .7,
        expand: false,
        snap: false,
        builder: (context, scrollController) {
          return Consumer2<MeetingsState, GlobalState>(
            builder: (context, meetingsState, 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: () {
                                              meetingsState.clearFilters();
                                            },
                                            child:
                                                meetingsState.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: meetingsState
                                                      .fromDate.isNotEmpty
                                                  ? meetingsState.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}';
                                                          meetingsState
                                                              .setFromDates(
                                                                  fromDateString); // Update the selected date
                                                        },
                                                      ),
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                            Text(
                                              AppLocalizations.of(context)!.to,
                                            ),
                                            PickerCustom(
                                              showDate: meetingsState
                                                      .toDate.isNotEmpty
                                                  ? meetingsState.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}';
                                                          meetingsState.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: meetingsState
                                                .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) {
                                              meetingsState.selectLocation(
                                                  newValue ?? null);
                                            },
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                  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: meetingsState
                                                .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) {
                                              meetingsState.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:
                                                meetingsState.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) {
                                              meetingsState.selectSubject(
                                                  newValue ?? null);
                                            },
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Divider(),
                                  Column(
                                    children: [
                                      SizedBox(
                                        height: 250,
                                        child: ListView.builder(
                                          physics:
                                              NeverScrollableScrollPhysics(),
                                          shrinkWrap: true,
                                          primary: false,
                                          itemCount: globalState
                                              .meetingStatuses.length,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            final items = globalState
                                                .meetingStatuses[index];
                                            return RadioListTile<int>(
                                              toggleable: true,
                                              groupValue: meetingsState
                                                  .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) {
                                                meetingsState
                                                    .selectStatusMeeting(
                                                        newValue ?? null);
                                              },
                                            );
                                          },
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  );
                case Status.loading:
                  return const LoadingWidget();
                case Status.error:
                  return CustomErrorWidget(
                    onPressed: () async {
                      // await meetingsState!.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,
  });
}
