import 'package:ambito/src/entity/entities.dart';
import 'package:ambito/src/entity/measure/details/measure_details.dart';
import 'package:ambito/src/entity/measure/types_details/measure_types_details.dart';
import 'package:ambito/src/extensions/extensions.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/combined_card.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/gallery_card.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/simple_text_card.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/sublevel_months_card.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/sublevel_text_card.dart';
import 'package:ambito/src/pages/measure/detail/cards/main/unordered_list_card.dart';
import 'package:animated_segmented_tab_control/animated_segmented_tab_control.dart';
import 'package:expansion_tile_card/expansion_tile_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_breadcrumb/flutter_breadcrumb.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';

import '../../../config/config.dart';
import '../../../consts/consts.dart';
import '../../../entity/measure/complete/measure_complete.dart';
import '../../../packages/ambito_theme/ambito_theme.dart';
import '../../../widgets/appbar/ambito_appbar.dart';
import '../../ambito_page.dart';
import 'cards/_cards.dart';

final Map<String, GlobalKey<ExpansionTileCardState>> globalKeys = {};

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

  @override
  final String path = 'massnahme';
  @override
  final String title = 'Maßname';

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

class MeasureDetailPageState extends State<MeasureDetailPage> {
  final ScrollController scrollController = ScrollController();
  final ScrollController itemScrollController = ScrollController();

  bool showBackToTopButton = false;
  final Map<String, GlobalKey<ExpansionTileCardState>> expansionKeys = {};
  MeasureGeneral? measureGeneral;
  MeasureDetails? measureDetails;
  MeasureTypes? measureType;
  MeasureTypesDetails? measureTypesDetails;
  List<Widget> contentItems = [];
  final Set<String> visibleItems = {};
  bool collapsed = false;
  int? id;

  MeasureComplete? measure;

  @override
  void initState() {
    super.initState();

    // Parse ID from parameters

    // Initialize combined map with ID
    //Map<String, dynamic> combined = {'id': id};

    // Retrieve measureGeneral data
    /* measureGeneral = isar.measureGenerals.where().idEqualTo(id!).findFirst();

    if (measureGeneral != null) {
      // Fetch related details and types
      measureDetails = MeasureDetailsRepository()
          .getDetailsForMeasure(measureGeneral!.name!);
      measureType = MeasureRepository().getTypeByName(
          measureGeneral!.measureType!.map((el) => el.value).first!);
      measureTypesDetails = MeasureTypesDetailsRepository()
          .getTypeDetailsForType(measureType!.measureType!);
    }

    // Save preferences and populate combined map
    prefs.setBool('extended_json', true).then((_) {
      _mergeToCombinedMap(combined, measureGeneral?.toJson());
      _mergeToCombinedMap(combined, measureDetails?.toJson());
      _mergeToCombinedMap(combined, measureType?.toJson());
      _mergeToCombinedMap(combined, measureTypesDetails?.toJson());
      setState(() {
        measure = MeasureComplete.fromJson(combined);
      });

      logger.d(measure!.toJson());
    });*/

    // Add scroll listener for the back-to-top button
    scrollController.addListener(() {
      const showOffset = 10.0;
      setState(() {
        showBackToTopButton = scrollController.offset > showOffset;
      });
    });
  }

// Utility function to merge data into combined map, excluding 'id'
  void _mergeToCombinedMap(
      Map<String, dynamic> combined, Map<String, dynamic>? data) {
    data?.forEach((key, value) {
      if (key != 'id') {
        combined[key] = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final AmbitoTheme theme = getTheme(context);

    id = int.tryParse(Get.parameters['id'] ?? '0') ?? 0;

    MeasureComplete? measure =
        isar.measureCompletes.where().idEqualTo(id!).findFirst()!;

    return Scaffold(
      appBar: AmbitoAppbar(
        links: const ['dashboard', 'massnahmen'],
        breakpoint: Breakpoint.fromContext(context),
        theme: theme,
      ),
      body: (context.breakpoint != myBreakpoints.sm)
          ? _buildInfoPage(context, measure)
          : _tabbedInfoPage(context, measure),
      floatingActionButton: (context.breakpoint != myBreakpoints.sm)
          ? AnimatedOpacity(
              duration: const Duration(milliseconds: 1000),
              opacity: showBackToTopButton ? 1.0 : 0.0,
              child: FloatingActionButton(
                shape: const CircleBorder(),
                elevation: 0,
                onPressed: () => scrollController.animateTo(
                  0,
                  duration: const Duration(milliseconds: 500),
                  curve: Curves.fastOutSlowIn,
                ),
                backgroundColor: theme.currentColorScheme.primary,
                child: Icon(Icons.arrow_upward,
                    color: theme.currentColorScheme.onPrimary),
              ),
            )
          : null,
    );
  }

  Widget _tabbedInfoPage(BuildContext context, MeasureComplete? massnahme) {
    final AmbitoTheme theme = getTheme(context);

    if (massnahme == null) {
      return const Center(child: CircularProgressIndicator());
    }

    return Padding(
      padding: context.breakpoint.padding,
      child: DefaultTabController(
        length: 2,
        child: Column(
          children: [
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                massnahme.measureType!,
                style: theme.currentThemeData.textTheme.headlineMedium,
              ),
            ),
            theme.verticalSpacerSmall,
            SegmentedTabControl(
              tabTextColor: theme.currentColorScheme.secondary,
              selectedTabTextColor: theme.currentColorScheme.onSecondary,
              barDecoration: BoxDecoration(
                color: theme.currentColorScheme.onSecondary,
                border: Border.all(
                  width: 1.0,
                  color: theme.currentColorScheme.secondary,
                ),
                borderRadius: const BorderRadius.all(
                  Radius.circular(
                    8.0,
                  ),
                ),
              ),
              indicatorDecoration:
                  BoxDecoration(color: theme.currentColorScheme.secondary),
              tabs: [
                SegmentTab(
                    label:
                        context.translate('page.actionDetailPage.tabs.info')),
                SegmentTab(
                    label:
                        context.translate('page.actionDetailPage.tabs.misc')),
              ],
            ),
            theme.verticalSpacerSmall,
            Expanded(
              child: TabBarView(
                children: [
                  SingleChildScrollView(
                    child: Column(children: _buildContentItems(massnahme)),
                  ),
                  /*SingleChildScrollView(
                    child: Column(
                      children: _buildSidebarItems(context, theme, massnahme),
                    ),
                  ),*/
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoPage(BuildContext context, MeasureComplete? measure) {
    final AmbitoTheme theme = getTheme(context);

    if (measure == null) {
      return const Center(child: CircularProgressIndicator());
    }

    contentItems = _buildContentItems(measure);

    return Column(
      children: [
        //_buildBreadcrumb(context, theme, massnahme),
        SizedBox(
            width: double.infinity, height: 300, child: measure.getFullImage()),
        Expanded(
          child: SingleChildScrollView(
            controller: scrollController,
            child: SizedBox(
              width: 1152,
              child: Column(
                children: [
                  theme.verticalSpacer,
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      measure.name!,
                      style: theme.currentThemeData.textTheme.headlineMedium,
                    ),
                  ),
                  theme.verticalSpacer,
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Column(children: [
                          ListView.builder(
                              controller: itemScrollController,
                              itemCount: contentItems.length,
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              itemBuilder: (context, index) {
                                return contentItems[index];
                              }),
                        ]),
                      ),
                      theme.horizontalSpacer,
                      SizedBox(
                        width: 300,
                        child: Column(
                          children: _buildSidebarItems(context, theme, measure),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBreadcrumb(
      BuildContext context, AmbitoTheme theme, MeasureTypes massnahme) {
    return Align(
      alignment: Alignment.centerLeft,
      child: BreadCrumb(
        items: [
          BreadCrumbItem(
            content: TextButton(
              onPressed: () => Get.offAndToNamed('/'),
              child: Text('Massnahmenkategorien', style: theme.bodyMedium),
            ),
          ),
          BreadCrumbItem(
            content: TextButton(
              onPressed: () => Get.offAndToNamed('/massnahmendatenbank'),
              child: Text('Maßnamentypen', style: theme.bodyMedium),
            ),
          ),
          BreadCrumbItem(
            content: TextButton(
              onPressed: () => Get.offAndToNamed('/massnahmendatenbank'),
              child:
                  Text(massnahme.measureGroup!.value!, style: theme.bodyMedium),
            ),
          ),
          BreadCrumbItem(
              content:
                  Text(massnahme.measureType ?? '', style: theme.bodyMedium)),
        ],
        divider: const Icon(Icons.chevron_right),
      ),
    );
  }

  List<Widget> _buildContentItems(MeasureComplete measure) {
    final AmbitoTheme theme = getTheme(context);

    List<Widget> elements = [];

    void addCard({
      required String title,
      required Widget widget,
    }) {
      if (widget != const SizedBox()) {
        visibleItems.add(title);
        elements.add(widget);
        elements.add(theme.verticalSpacer);
      }
    }

    addCard(
      title: 'Beschreibung',
      widget: SimpleTextCard(
        title: 'Beschreibung',
        text: measure.description,
      ),
    );

    addCard(
      title: 'Zielsetzung',
      widget: SimpleTextCard(
        title: 'Zielsetzung',
        text: measure.target,
      ),
    );

    addCard(
      title: 'Förderprogramme',
      widget: UnorderedListCard(
        title: 'Förderprogramme',
        text: measure.fundingPrograms,
      ),
    );

    addCard(
      title: 'Größe / Fläche',
      widget: UnorderedListCard(
        title: 'Größe / Fläche',
        text: measure.sizeOrArea,
      ),
    );

    addCard(
      title: 'Wuchs / Krone',
      widget: SimpleTextCard(
        title: 'Wuchs / Krone',
        text: measure.growth,
      ),
    );

    addCard(
      title: 'Klima',
      widget: SimpleTextCard(
        title: 'Klima',
        text: measure.climate,
      ),
    );

    addCard(
      title: 'Bodenwasser',
      widget: SimpleTextCard(
        title: 'Bodenwasser',
        text: measure.soilWater,
      ),
    );

    addCard(
      title: 'Region',
      widget: SimpleTextCard(
        title: 'Region',
        text: measure.region?.join(', '),
      ),
    );

    addCard(
      title: 'Standort',
      widget: SimpleTextCard(
        title: 'Standort',
        text: measure.location,
      ),
    );

    addCard(
      title: 'Fachgerechte Umsetzung',
      widget: CombinedCard(
        title: 'Fachgerechte Umsetzung',
        elements: [
          SublevelTextCard(
            title: 'Kosten',
            text: measure.applyCosts,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Zeit',
            text: measure.applyDuration,
          ),
        ],
      ),
    );

    addCard(
      title: 'Anlage',
      widget: CombinedCard(
        title: 'Anlage',
        elements: [
          SublevelMonthsCard(
            title: 'Zeitrahmen',
            items: measure.applyMonths,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Zusatzinformationen',
            text: measure.applyAdditionalInfos,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Arbeitsschritte',
            text: measure.applySteps,
          ),
        ],
      ),
    );

    addCard(
      title: 'Galerie',
      widget: GalleryCard(
        title: 'Galerie',
        widgets: measure.getGalleryThumbnails(),
      ),
    );

    addCard(
      title: 'Pflege',
      widget: CombinedCard(
        title: 'Pflege',
        elements: [
          SublevelMonthsCard(
            title: 'Zeitrahmen',
            items: measure.maintenanceMonths,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Zusatzinformationen',
            text: measure.maintenanceAdditionalInfos,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Frequenz',
            text: measure.maintenanceFrequency,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Arbeitsschritte',
            text: measure.maintenanceSteps,
          ),
          const Divider(),
          SublevelTextCard(
            title: 'Besonderheiten',
            text: measure.maintenanceSpecialFeatures,
          ),
        ],
      ),
    );

    addCard(
      title: 'Quellen',
      widget: SimpleTextCard(
        title: 'Quellen',
        text: measure.sources,
      ),
    );

    return [
      Align(
        alignment: Alignment.centerRight,
        child: TextButton(
          onPressed: () {
            globalKeys.forEach((key, value) {
              if (collapsed == false) {
                value.currentState?.collapse();
              } else {
                value.currentState?.expand();
              }
            });
            setState(() {
              collapsed = !collapsed;
            });
          },
          child: Text(
            context.translate((collapsed == false)
                ? 'page.actionDetailPage.expanded.collapse_all'
                : 'page.actionDetailPage.expanded.expand_all'),
            style: theme.bodyLarge.copyWith(
              color: theme.currentColorScheme.onSurface,
              decoration: TextDecoration.underline,
            ),
          ),
        ),
      ),
      theme.verticalSpacer,
      ...elements,
    ];
  }

  List<Widget> _buildSidebarItems(
      BuildContext context, AmbitoTheme theme, MeasureComplete massnahme) {
    return [
      if (visibleItems.isNotEmpty && context.breakpoint != myBreakpoints.sm)
        TocCard(
          massnahme: massnahme,
          items: visibleItems.toList(),
          scrollController: itemScrollController,
        ),
      if (visibleItems.isNotEmpty && context.breakpoint != myBreakpoints.sm)
        theme.verticalSpacer,
      AdvisorCard(massnahme: massnahme),
      theme.verticalSpacer,
      MaterialCard(massnahme: massnahme),
      theme.verticalSpacer,
      FactsheetCard(massnahme: massnahme),
      theme.verticalSpacer,
    ];
  }
}
