import 'package:ambito/src/domain/entity/id_value_color/id_value_color.dart';
import 'package:ambito/src/domain/entity/massnahme/massnahme.dart';
import 'package:ambito/src/extensions/extensions.dart';
import 'package:ambito/src/packages/ambito_db/base_db.dart';
import 'package:ambito/src/widgets/form/fields/field_dropdown.dart';
import 'package:ambito/src/widgets/form/fields/field_monthsrangepicker.dart';
import 'package:ambito/src/widgets/form/form_widget.dart';
import 'package:ambito/src/widgets/form/form_widget_type.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:expandable_text/expandable_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';

import '../../../main.dart';

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

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

class ActionsPageState extends State<ActionsPage> {
  Map<int, bool> visible = {};
  List<String> effort = [];
  List<String> effect = [];
  Set<String> type = {};
  String? filterType;
  Set<String> areaType = {};
  String? filterAreaType;
  List<String> region = [];
  String? filterSupport;
  Set<String> support = {};
  String? filterMonths;
  Set<String> months = {};

  @override
  void initState() {
    super.initState();
    effort = [];
    effect = [];
    type = {};
    areaType = {};
    region = [];
    support = {};
  }

  @override
  Widget build(BuildContext context) {
    List<Massnahme> massnahmen = BaseDB.getAll('Maßnahme');
    Set<String> updatedTypes = {};
    Set<String> updatedAreaTypes = {};
    Set<String> updatedSupports = {};
    Set<String> updatedMonths = {};

    for (var massnahme in massnahmen) {
      if (massnahme.actionGroup != null) {
        updatedTypes.add(massnahme.actionGroup!.value!);
      }
      if (massnahme.factsheetAreaType != null) {
        for (IdValueColor aType in massnahme.factsheetAreaType!) {
          updatedAreaTypes.add(aType.value!);
        }
      }
      if (massnahme.fundingPrograms != null) {
        for (IdValueColor aType in massnahme.fundingPrograms!) {
          updatedSupports.add(aType.value!);
        }
      }
      if (massnahme.timeFrame != null) {
        logger.d(massnahme.timeFrame);
        for (IdValueColor tfType in massnahme.timeFrame!) {
          updatedMonths.add(tfType.value!);
        }
      }
    }

    logger.d(updatedMonths);

    setState(() {
      type.addAll(updatedTypes);
      areaType.addAll(updatedAreaTypes);
      support.addAll(updatedSupports);
      months.addAll(updatedMonths.toList());
    });

    List<Widget> actionCards = massnahmen.map((massnahme) {
      bool typeMatches = filterType == null ||
          (massnahme.actionGroup != null &&
              massnahme.actionGroup!.value == filterType);

      bool areaTypeMatches = filterAreaType == null ||
          (massnahme.factsheetAreaType
                  ?.any((aType) => aType.value == filterAreaType) ??
              false);

      bool supportMatches = filterSupport == null ||
          (massnahme.fundingPrograms
                  ?.any((aType) => aType.value == filterSupport) ??
              false);

      // Update visibility based on the matches
      setState(() {
        visible[massnahme.id] =
            typeMatches && areaTypeMatches && supportMatches;
      });

      return getCard(context, massnahme);
    }).toList();

    return Padding(
      padding: const EdgeInsets.only(left: 32, right: 32),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            context.translate('page.actions.title'),
            style: Theme.of(context).textTheme.headlineLarge,
          ),
          getSpacer(),
          Text(
            context.translate('page.actions.intro'),
            style: Theme.of(context).textTheme.titleLarge,
          ),
          getSpacer(),
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(
                  width: 300,
                  child: getFilter(context),
                ),
                const SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: SingleChildScrollView(
                    child: Wrap(
                      direction: Axis.horizontal,
                      children: actionCards,
                    ),
                  ),
                ),
              ],
            ),
          ),
          getSpacer(),
        ],
      ),
    );
  }

  Widget getSpacer() {
    return const SizedBox(
      height: 8,
    );
  }

  Widget getFilter(BuildContext context) {
    List<FormWidgetField> fields = [];

    fields.add(
      FieldDropdown(
        name: 'ort',
        label: 'Ort der Maßnahme',
        filterValue: filterAreaType,
        onClear: () {
          setState(() {
            filterAreaType = null;
          });
        },
        onSelected: ((String? value) {
          setState(() {
            filterAreaType = value;
          });
        }),
        entries: areaType.toList(),
      ),
    );

    fields.add(
      FieldDropdown(
        name: 'art',
        label: 'Art der Maßnahme',
        filterValue: filterType,
        onClear: () {
          setState(() {
            filterType = null;
          });
        },
        onSelected: ((String? value) {
          setState(() {
            filterType = value;
          });
        }),
        entries: type.toList(),
      ),
    );

    fields.add(
      FieldDropdown(
        name: 'support',
        label: 'Förderprogramm',
        filterValue: filterSupport,
        onClear: () {
          setState(() {
            filterSupport = null;
          });
        },
        onSelected: ((String? value) {
          setState(() {
            filterSupport = value;
          });
        }),
        entries: support.toList(),
      ),
    );

    List<String> monthsSorted = [];

    for (int i = 1; i <= 12; i++) {
      monthsSorted
          .add(FlutterI18n.translate(context, 'general.lists.months.$i'));
    }

    /*var monthsSorted = months.toList();
    monthsSorted.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));*/

    /*fields.add(
      FieldDropdown(
        name: 'months',
        label: 'Beginn der Maßnahme',
        filterValue: filterMonths,
        onClear: () {
          setState(() {
            filterMonths = null;
          });
        },
        onSelected: ((String? value) {
          setState(() {
            filterMonths = value;
          });
        }),
        entries: monthsSorted,
      ),
    );*/

    logger.d(monthsSorted);
    fields.add(
      FieldMonthsRangepicker(
        name: 'months',
        label: 'Beginn der Maßnahme',
        filterValue: filterMonths,
        onClear: () {},
        onSelected: (String? value) {},
        entries: monthsSorted,
      ),
    );

    return FormWidget(type: FormWidgetType.vertical, fields: fields);

    /*return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        DropdownMenuWidget(
          formKey: _keyAreaType,
          label: 'Ort der Maßnahme',
          controller: _controllerAreaType,
          filterValue: filterAreaType,
          onClear: () {
            setState(() {
              filterAreaType = null;
            });
            _controllerAreaType.clear();
          },
          onSelected: (String? selection) {
            setState(() {
              filterAreaType = selection;
            });
          },
          entries: areaType.toList(),
        ),
        DropdownMenuWidget(
          formKey: _keyType,
          label: 'Art der Maßnahme',
          controller: _controllerType,
          filterValue: filterType,
          onClear: () {
            setState(() {
              filterType = null;
            });
            _controllerType.clear();
          },
          onSelected: (String? selection) {
            setState(() {
              filterType = selection;
            });
          },
          entries: type.toList(),
        ),
        DropdownMenuWidget(
          formKey: _keySupport,
          label: 'Förderprogramm',
          controller: _controllerSupport,
          filterValue: filterSupport,
          onClear: () {
            setState(() {
              filterSupport = null;
            });
            _controllerSupport.clear();
          },
          onSelected: (String? selection) {
            setState(() {
              filterSupport = selection;
            });
          },
          entries: support.toList(),
        ),
      ],
    );*/
  }

  Widget getCard(BuildContext context, Massnahme massnahme) {
    final Map<String, Color> actionGroupColors = {
      'Baulelemente': const Color(0xffFFD269),
      'Begrünung': const Color(0xff40DD74),
      'Bewirtschaftung': const Color(0xffBF72ED),
      'Nisthilfe': const Color(0xffDAE3FD),
      'Pflanzung': const Color(0xff40D6E9),
      'Sondermaßnahmen': const Color(0xff689EF1),
    };

    Color background =
        actionGroupColors[massnahme.actionGroup?.value] ?? Colors.white;

    CachedNetworkImage? image = massnahme.getThumbnail();

    return Visibility(
      visible: visible[massnahme.id] ?? false,
      child: SizedBox(
        width: 400,
        child: Card(
          color: background,
          child: Padding(
            padding: const EdgeInsets.all(32),
            child: Column(
              children: [
                if (image != null) image,
                const SizedBox(
                  height: 8,
                ),
                Text(massnahme.name!,
                    style: Theme.of(context).textTheme.headlineSmall),
                const SizedBox(
                  height: 8,
                ),
                ExpandableText(
                  massnahme.factsheetDefinition ?? '',
                  maxLines: 3,
                  expandText: 'mehr',
                  collapseText: 'weniger',
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
