import 'package:ambito/src/domain/entity/massnahme/massnahme.dart';
import 'package:ambito/src/packages/ambito_db/base_db.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:expandable_text/expandable_text.dart';
import 'package:flutter/material.dart';

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

class ActionsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ActionsPageState();
}

class ActionsPageState extends State<ActionsPage> {
  final GlobalKey<FormFieldState> _keyType = GlobalKey<FormFieldState>();
  final GlobalKey<FormFieldState> _keyAreaType = GlobalKey<FormFieldState>();

  Map<int, bool> visible = {};
  List<String> effort = [];
  List<String> effect = [];
  List<String> type = [];
  String? filterType;
  List<String> areaType = [];
  String? filterAreaType;
  List<String> region = [];
  List<String> support = [];

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

  @override
  Widget build(BuildContext context) {
    List<Massnahme> massnahmen = BaseDB.getAll('Maßnahme');

    List<Widget> actionCards = [];
    for (var massnahme in massnahmen) {
      //logger.d(massnahme.toJson());
      if (massnahme.actionGroup != null &&
          !type.contains(massnahme.actionGroup!.value)) {
        setState(() {
          type.add(massnahme.actionGroup!.value!);
        });
      }
      if (massnahme.factsheetAreaType != null) {
        for (var aType in massnahme.factsheetAreaType!) {
          if (!areaType.contains(aType.value)) {
            setState(() {
              areaType.add(aType.value!);
            });
          }
        }
      }
    }

    for (var massnahme in massnahmen) {
      bool myVisibility = true;
      if (filterType != null) {
        if (massnahme.actionGroup == null ||
            massnahme.actionGroup!.value != filterType) {
          myVisibility = false;
        }
      }
      if (filterAreaType != null) {
        if (massnahme.factsheetAreaType != null) {
          myVisibility = false;
          for (var aType in massnahme.factsheetAreaType!) {
            if (aType.value == filterAreaType) {
              myVisibility = true;
            }
          }
        }
      }
      setState(() {
        visible[massnahme.id] = myVisibility;
      });
      actionCards.add(getCard(context, massnahme));
    }

    logger.d(visible);
    //logger.d(areaType);

    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(),
          getFilter(context),
          getSpacer(),
          Expanded(
            child: SingleChildScrollView(
              child: Wrap(
                children: actionCards,
              ),
            ),
          ),
        ],
      ),
    );
  }

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

  Widget getFilter(BuildContext context) {
    return Row(
      children: [
        DropdownMenu(
          key: _keyAreaType,
          initialSelection: filterAreaType,
          leadingIcon: (filterAreaType != null)
              ? IconButton(
                  onPressed: () {
                    _keyAreaType.currentState!.didChange(null);
                    _keyAreaType.currentState!.reset();
                    setState(() {
                      filterAreaType = null;
                    });
                  },
                  icon: const Icon(Icons.delete),
                )
              : null,
          onSelected: (String? selection) {
            setState(() {
              filterAreaType = selection;
            });
          },
          dropdownMenuEntries:
              areaType.map<DropdownMenuEntry<String>>((String entry) {
            return DropdownMenuEntry<String>(
              value: entry,
              label: entry,
            );
          }).toList(),
        ),
        DropdownMenu(
          key: _keyType,
          leadingIcon: (filterType != null)
              ? IconButton(
                  onPressed: () {
                    setState(() {
                      filterType = null;
                    });
                    _keyType.currentState!.reset();
                  },
                  icon: const Icon(Icons.delete),
                )
              : null,
          onSelected: (String? selection) {
            setState(() {
              filterType = selection;
            });
          },
          dropdownMenuEntries:
              type.map<DropdownMenuEntry<String>>((String entry) {
            return DropdownMenuEntry<String>(
              value: entry,
              label: entry,
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget getCard(BuildContext context, Massnahme massnahme) {
    Color background = Colors.white;
    switch (massnahme.actionGroup?.value) {
      case 'Baulelemente':
        background = const Color(0xffFFD269);
        break;
      case 'Begrünung':
        background = const Color(0xff40DD74);
        break;
      case 'Bewirtschaftung':
        background = const Color(0xffBF72ED);
        break;
      case 'Nisthilfe':
        background = const Color(0xffDAE3FD);
        break;
      case 'Pflanzung':
        background = const Color(0xff40D6E9);
        break;
      case 'Sondermaßnahmen':
        background = const Color(0xff689EF1);
        break;
    }

    var image;
    if (massnahme.files != null && massnahme.files!.isNotEmpty) {
      if (massnahme.files![0].thumbnails?.card_cover?.url != null) {
        image = CachedNetworkImage(
          imageUrl: massnahme.files![0].thumbnails!.card_cover!.url!,
          placeholder: (context, url) => const CircularProgressIndicator(),
          errorWidget: (context, url, error) => const Icon(Icons.error),
        );
      }
    }

    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',
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
