import 'package:ambito/src/config/config.dart';
import 'package:ambito/src/entity/funding_program/funding_program_repository.dart';
import 'package:ambito/src/entity/lists/list_display.dart';
import 'package:ambito/src/entity/lists/list_repository.dart';
import 'package:ambito/src/extensions/extensions.dart';
import 'package:ambito/src/pages/ambito_page.dart';
import 'package:ambito/src/widgets/form/fields/field_title.dart';
import 'package:ambito/src/widgets/form/form_widget.dart';
import 'package:ambito/src/widgets/form/form_widget_type.dart';
import 'package:ambito/src/widgets/page/base_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:highlight_text/highlight_text.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';

import '../../consts/consts.dart';
import '../../entity/measure/measure_repository.dart';
import '../../packages/ambito_notifier/notifier/filter_notifier.dart';
import '../../packages/ambito_theme/ambito_theme.dart';

class MeasuresPage extends AmbitoPage {
  const MeasuresPage({super.key});

  @override
  final String path = 'massnahmendatenbank';
  @override
  final String title = 'Maßnamendatenbank';

  @override
  State<StatefulWidget> createState() => MeasuresPageState();
}

class MeasuresPageState extends State<MeasuresPage> {
  Map<int, bool> visible = {};
  String preselectCategory = '';
  String preselectGroup = '';
  String preselectType = '';
  String searchText = '';
  Map<String, HighlightedWord> words = {};
  String filterCategory = '';
  String filterGroup = '';
  String filterType = '';

  List<ListDisplay> itemsToDisplay = [];

  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocusNode = FocusNode();

  @override
  void initState() {
    ambitoFilterNotifier.addListener(_changeListener);

    preselectCategory = Get.parameters['kategorie'] ?? '';
    if (preselectCategory != '') {
      setState(() {
        filterCategory = preselectCategory;
        ambitoFilterNotifier.setFilter('category', preselectCategory);
      });
    }

    preselectGroup = Get.parameters['group'] ?? '';
    if (preselectGroup != '') {
      setState(() {
        filterGroup = preselectGroup;
        ambitoFilterNotifier.setFilter('group', preselectGroup);
      });
    }

    preselectType = Get.parameters['type'] ?? '';
    if (preselectType != '') {
      setState(() {
        filterType = preselectType;
        ambitoFilterNotifier.setFilter('type', preselectType);
      });
    }

    if (filterGroup == '' && filterType == '') {
      setState(() {
        itemsToDisplay = ListRepository().getGroupsToDisplay(filterCategory);
      });
    } else if (filterGroup != '' && filterType == '') {
      setState(() {
        itemsToDisplay =
            ListRepository().getTypesToDisplay(filterCategory, filterGroup);
      });
    } else if (filterCategory != '' && filterGroup != '' && filterType != '') {
      setState(() {
        itemsToDisplay = ListRepository()
            .getMeasuresToDisplay(filterCategory, filterGroup, filterType);
      });
    }

    super.initState();
  }

  void _changeListener() {
    setState(() {
      filterCategory = ambitoFilterNotifier.getFilter('category') ?? '';
      filterGroup = ambitoFilterNotifier.getFilter('group') ?? '';
      filterType = ambitoFilterNotifier.getFilter('type') ?? '';
    });

    if (filterGroup == '' && filterType == '') {
      setState(() {
        itemsToDisplay = ListRepository().getGroupsToDisplay(filterCategory);
      });
    } else if (filterGroup != '' && filterType == '') {
      setState(() {
        itemsToDisplay =
            ListRepository().getTypesToDisplay(filterCategory, filterGroup);
      });
    } else if (filterCategory != '' && filterGroup != '' && filterType != '') {
      setState(() {
        itemsToDisplay = ListRepository()
            .getMeasuresToDisplay(filterCategory, filterGroup, filterType);
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _onSearchTextChanged(String value) {
    setState(() {
      searchText = value;
      words = {
        for (var word in value.split(' '))
          word: HighlightedWord(
              textStyle: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  color: Colors.white, backgroundColor: Colors.green.shade800))
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    final actionCards = itemsToDisplay.map((measure) {
      return getCard(context, measure);
    }).toList();

    final AmbitoTheme theme = getTheme(context);

    return BasePage().getPage(
      context,
      Align(
        alignment: Alignment.topCenter,
        child: SizedBox(
          width: 1152,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              theme.verticalSpacer,
              _buildSearchBar(),
              theme.verticalSpacerMax,
              Expanded(
                child: (context.breakpoint.breakpoint ==
                        myBreakpoints.sm!.breakpoint)
                    ? _smallPage(actionCards)
                    : _normalPage(actionCards),
              ),
              theme.verticalSpacer,
            ],
          ),
        ),
      ),
    );
  }

  Widget _normalPage(List<Widget> actionCards) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: 300, child: _buildFilter(context)),
        const SizedBox(width: 16),
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: actionCards,
            ),
          ),
        ),
      ],
    );
  }

  Widget _smallPage(List<Widget> actionCards) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: double.infinity, child: _buildFilter(context)),
        const SizedBox(width: 16),
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: actionCards,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSearchBar() {
    return Center(
      child: SearchBar(
        controller: _searchController,
        focusNode: _searchFocusNode,
        elevation: WidgetStateProperty.all(0.0),
        backgroundColor: WidgetStateProperty.all(Colors.white),
        side: WidgetStateProperty.all(const BorderSide(color: Colors.black)),
        leading: const Icon(Icons.search),
        trailing: [
          if (_searchFocusNode.hasFocus && _searchController.text.isNotEmpty)
            IconButton(
              onPressed: () {
                _searchController.clear();
                _searchFocusNode.unfocus();
                _onSearchTextChanged('');
              },
              icon: const Icon(Icons.clear, color: Colors.grey, size: 20),
            ),
        ],
        onChanged: _onSearchTextChanged,
      ),
    );
  }

  Widget _buildFilter(BuildContext context) {
    return FormWidget(
      type: FormWidgetType.vertical,
      fields: [
        FieldTitle(text: filterGroup.capitalizeFirst!),
        MeasureRepository().getGroupDropDownByCategory(preselectCategory),
        MeasureRepository().getTypeDropDownByCategoryAndGroup(
            preselectCategory, preselectGroup),
        FundingProgramRepository()
            .getDropDownByGroupAndType(preselectGroup, preselectType),
      ],
    );
  }

  Widget getCard(
    BuildContext context,
    ListDisplay measure,
  ) {
    final AmbitoTheme theme = getTheme(context);
    return InkWell(
      onTap: () async {
        if (measure.isMeasure == false && measure.hasChildren == true) {
          ambitoFilterNotifier.setFilter(
              'type', measure.title?.toLowerCase().replaceUmlauts());
          Get.toNamed(
              '/massnahmendatenbank/$filterCategory/$filterGroup/${measure.title!.toLowerCase().replaceUmlauts()}');
        } else if (measure.isMeasure == true) {
          logger.d(measure.id);
          Get.toNamed('/massnahme/${measure.id}');
        }
      },
      onHover: (measure.isMeasure == true || measure.hasChildren == true)
          ? (hovered) {}
          : null,
      highlightColor: Colors.transparent,
      splashColor: Colors.transparent,
      focusColor: Colors.transparent,
      hoverColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(bottom: 20),
        child: SizedBox(
          width: double.infinity,
          child: Card(
            elevation: 0,
            color: theme.currentColorScheme.outline..withValues(alpha: .1),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Align(
                  alignment: Alignment.topLeft,
                  child: ClipRRect(
                    borderRadius: const BorderRadius.all(Radius.circular(10.0)),
                    child: Container(
                        width: (context.breakpoint.breakpoint ==
                                myBreakpoints.sm!.breakpoint)
                            ? 150
                            : 272,
                        height: 158,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: measure.image),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        TextHighlight(
                          text: measure.title!,
                          words: words,
                          textStyle: theme.textTheme.headlineSmall,
                        ),
                        const SizedBox(height: 8),
                        TextHighlight(
                          text: measure.description ?? '',
                          words: words,
                          textStyle: theme.textTheme.bodyLarge,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
