// ignore_for_file: deprecated_member_use

import 'package:didvan/constants/assets.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/widgets/search_field.dart';
import 'package:didvan/views/home/home_state.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/views/widgets/didvan/checkbox.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:didvan/views/widgets/date_picker_button.dart';
import 'package:didvan/views/widgets/ai_chat_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:provider/provider.dart';

class HomeAppBar extends StatelessWidget {
  final bool showBackButton;
  final String? title;
  final bool showSearchField;
  final Function(String)? onSearchChanged;
  final VoidCallback? onFilterPressed;
  final FocusNode? searchFocusNode;
  final bool? isFiltered;
  final String? searchValue;

  const HomeAppBar({
    super.key,
    this.showBackButton = false,
    this.title,
    this.showSearchField = false,
    this.onSearchChanged,
    this.onFilterPressed,
    this.searchFocusNode,
    this.isFiltered,
    this.searchValue,
  });

  @override
  Widget build(BuildContext context) {
    final homeState =
        (onSearchChanged == null) ? context.watch<HomeState>() : null;

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              if (showBackButton)
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.surface,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: Theme.of(context)
                            .colorScheme
                            .outline
                            .withOpacity(0.2),
                      ),
                    ),
                    child: Center(
                      child: Icon(
                        Icons.arrow_back_ios_new,
                        size: 20,
                        color: Theme.of(context).colorScheme.title,
                      ),
                    ),
                  ),
                )
              else
                SvgPicture.asset(
                  Assets.horizontalLogoWithText,
                  height: 60,
                  color: Theme.of(context).colorScheme.title,
                ),
              if (title != null && showBackButton)
                Expanded(
                  child: Center(
                    child: Text(
                      title!,
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).colorScheme.title,
                          ),
                    ),
                  ),
                ),
              Row(
                children: [
                  IconButton(
                    icon: SvgPicture.asset(
                        'lib/assets/icons/hugeicons_telescope-01.svg'),
                    onPressed: () {
                      Navigator.of(context).pushNamed(Routes.bookmarks);
                    },
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, Routes.profile);
                    },
                    child: SizedBox(
                      width: 44,
                      height: 44,
                      child: Center(
                        child: SvgPicture.asset(
                          'lib/assets/icons/New_Profile.svg',
                          width: 30,
                          height: 30,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        )
            .animate()
            .fadeIn(duration: 500.ms)
            .slideY(begin: -0.5, duration: 500.ms),
        if (showSearchField)
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
            child: SearchField(
              title: title ?? 'دیدوان',
              focusNode: searchFocusNode ??
                  context.read<HomeState>().searchFieldFocusNode,
              onChanged: (value) {
                if (onSearchChanged != null) {
                  onSearchChanged!(value);
                } else {
                  final state = context.read<HomeState>();
                  if (value.length >= 2) {
                    state.onSearchChanged(value);
                  } else if (value.isEmpty) {
                    state.clearSearch();
                  }
                }
              },
              onFilterButtonPressed: () {
                if (onFilterPressed != null) {
                  onFilterPressed!();
                } else {
                  showFilterBottomSheet(context);
                }
              },
              isFiltered: isFiltered ?? homeState?.filtering ?? false,
              value: searchValue ?? homeState?.search,
              extraIconPath: 'lib/assets/icons/live ai.svg',
              onExtraIconPressed: () {
                showDialog(
                  context: context,
                  barrierDismissible: true,
                  builder: (context) => const AiChatDialog(),
                );
              },
            ),
          ).animate().fadeIn(delay: 200.ms, duration: 500.ms),
      ],
    );
  }

  Future<void> showFilterBottomSheet(BuildContext context) async {
    final state = Provider.of<HomeState>(context, listen: false);

    ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        title: 'فیلتر جستجو',
        titleIconWidget: SvgPicture.asset(
          'lib/assets/icons/document-filter.svg',
          width: 24,
          height: 24,
        ),
        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
                    ?.copyWith(fontWeight: FontWeight.bold),
                iconWidget: 'lib/assets/icons/calendar.svg',
                color: const Color.fromARGB(255, 27, 60, 89),
              ),
              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: 'دسته بندی',
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(fontWeight: FontWeight.bold),
              iconWidget: 'lib/assets/icons/ion_extension-puzzle-outline.svg',
              color: const Color.fromARGB(255, 27, 60, 89),
            ),
            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]);
                            return;
                          }
                          state.selectedCats.remove(state.categoryFilters[i]);
                        },
                      ),
                    ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
