import 'dart:async';

import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/category.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/home/home_state.dart';
import 'package:didvan/views/widgets/date_picker_button.dart';
import 'package:didvan/views/widgets/didvan/checkbox.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:didvan/views/widgets/search_field.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SearchAppBar extends StatelessWidget implements PreferredSizeWidget {
  const SearchAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size(double.infinity, 144);

  @override
  Widget build(BuildContext context) {
    final state = context.read<HomeState>();
    final MediaQueryData d = MediaQuery.of(context);
    return Container(
      height: 144,
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(20)),
        color: Theme.of(context).colorScheme.surface,
        boxShadow: state.filtering
            ? null
            : [
                BoxShadow(
                  color: const Color(0XFF1B3C59).withValues(alpha: 0.15),
                  blurRadius: 8,
                  spreadRadius: 0,
                  offset: const Offset(0, 8),
                )
              ],
      ),
      margin: EdgeInsets.only(top: d.padding.top),
      padding: const EdgeInsets.all(16),
      alignment: Alignment.centerRight,
      child: Column(
        children: [
          Consumer<HomeState>(
            builder: (context, state, child) => SearchField(
              key: state.search.isEmpty ? ValueKey(state.search) : null,
              value: state.search,
              title: 'دیدوان',
              onChanged: (value) => _onChanged(value, context),
              focusNode: state.searchFieldFocusNode,
              onFilterButtonPressed: () => _showFilterBottomSheet(context),
              isFiltered: state.filtering,
              onGoBack: state.filtering
                  ? () {
                      state.resetFilters(false);
                      FocusScope.of(context).unfocus();
                    }
                  : null,
            ),
          ),
        ],
      ),
    );
  }

  void _onChanged(String value, BuildContext context) {
    final state = context.read<HomeState>();

    if (value.length >= 2) {
      state.onSearchChanged(value);
    } else if (value.isEmpty) {
      state.clearSearch();
    }
  }

  Future<void> _showFilterBottomSheet(BuildContext context) async {
    final state = context.read<HomeState>();
    await ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        title: 'فیلتر جستجو',
        smallDismissButton: true,
        titleIcon: DidvanIcons.filter_regular,
        dismissTitle: 'حذف فیلتر',
        confrimTitle: 'نمایش نتایج',
        onDismissed: () => state.resetFilters(false),
        onConfirmed: () => state.searchAll(page: 1),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (state.currentPageIndex != 9) ...[
              ItemTitle(
                title: 'تاریخ ایجاد',
                style: Theme.of(context).textTheme.bodyMedium,
                icon: DidvanIcons.calendar_range_regular,
              ),
              const SizedBox(height: 8),
              StatefulBuilder(
                builder: (context, setState) => Row(
                  children: [
                    DatePickerButton(
                      initialValue: state.startDate,
                      emptyText: 'از تاریخ',
                      onPicked: (date) =>
                          setState(() => state.startDate = date),
                      lastDate: state.endDate,
                    ),
                    const SizedBox(width: 8),
                    DatePickerButton(
                      initialValue: state.endDate,
                      emptyText: 'تا تاریخ',
                      onPicked: (date) => setState(() => state.endDate = date),
                      firstDate: state.startDate,
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 28),
            ],
            ItemTitle(
              title: 'دسته بندی',
              icon: DidvanIcons.category_regular,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: 12),
            Wrap(
              children: [
                for (var i = 0; i < state.categoryFilters.length; i++)
                  if (state.categoryFilters[i].label != 'هوشان')
                    SizedBox(
                      width: (MediaQuery.of(context).size.width - 40) / 2,
                      child: DidvanCheckbox(
                        title: state.categoryFilters[i].label,
                        value: state.selectedCats
                            .contains(state.categoryFilters[i]),
                        onChanged: (value) {
                          if (value) {
                            state.selectedCats.add(state.categoryFilters[i]);
                            if (state.categoryFilters[i].id == 3) {
                              state.selectedCats
                                  .add(CategoryData(id: 4, label: 'پادکست'));
                            }
                            return;
                          }
                          state.selectedCats.remove(state.categoryFilters[i]);
                          if (state.categoryFilters[i].id == 3) {
                            state.selectedCats
                                .remove(CategoryData(id: 4, label: 'پادکست'));
                          }
                        },
                      ),
                    ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // void _handleMenuOpen(BuildContext context) {
  //   ActionSheetUtils.showBottomSheet(
  //     data: ActionSheetData(
  //       content: Column(
  //         children: [
  //           Row(
  //             crossAxisAlignment: CrossAxisAlignment.center,
  //             children: [
  //               SvgPicture.asset(
  //                 Assets.strategicRadarIcon,
  //                 width: 48,
  //                 height: 48,
  //               ),
  //               const SizedBox(width: 4),
  //               DidvanText(
  //                 'سامانه رادارهای استراتژیک',
  //                 style: Theme.of(context).textTheme.titleMedium,
  //               ),
  //             ],
  //           ),
  //           const SizedBox(height: 16),
  //           _BottomSheetItem(
  //             icon: Assets.progressRadarIcon,
  //             title: 'رادار روند',
  //             enabled: true,
  //             onTap: () {
  //               launchUrlString(
  //                 'https://trend.didvan.app/',
  //                 mode: LaunchMode.inAppWebView,
  //               );
  //             },
  //           ),
  //           const SizedBox(height: 16),
  //           _BottomSheetItem(
  //             icon: Assets.techRadarIcon,
  //             title: 'رادار تکنولوژی',
  //             onTap: () {},
  //           ),
  //           const SizedBox(height: 16),
  //           _BottomSheetItem(
  //             icon: Assets.riskRadarIcon,
  //             title: 'رادار ریسک',
  //             enabled: true,
  //             onTap: () {
  //               launchUrlString(
  //                 'https://risk.didvan.app/',
  //                 mode: LaunchMode.inAppWebView,
  //               );
  //             },
  //           ),
  //           const SizedBox(height: 16),
  //           _BottomSheetItem(
  //             icon: Assets.startupRadarIcon,
  //             title: 'رادار استارت‌آپ',
  //             onTap: () {},
  //           ),
  //         ],
  //       ),
  //       hasConfirmButton: false,
  //       hasDismissButton: false,
  //     ),
  //   );
  // }
}

// class _BottomSheetItem extends StatelessWidget {
//   final String icon;
//   final String title;
//   final bool enabled;
//   final VoidCallback onTap;
//   const _BottomSheetItem({
//     required this.icon,
//     required this.title,
//     this.enabled = false,
//     required this.onTap,
//   });

//   @override
//   Widget build(BuildContext context) {
//     return GestureDetector(
//       onTap: enabled ? onTap : null,
//       child: Container(
//         color: Colors.transparent,
//         child: Row(
//           crossAxisAlignment: CrossAxisAlignment.center,
//           children: [
//             SvgPicture.asset(
//               icon,
//               theme: SvgTheme(
//                 currentColor: enabled
//                     ? Theme.of(context).colorScheme.title
//                     : Theme.of(context).colorScheme.disabledText,
//               ),
//             ),
//             const SizedBox(width: 8),
//             DidvanText(
//               title,
//               color: enabled
//                   ? Theme.of(context).colorScheme.title
//                   : Theme.of(context).colorScheme.disabledText,
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }
