import 'package:ambito/src/config/config.dart';
import 'package:ambito/src/entity/_general/filter/item_filter.dart';
import 'package:ambito/src/entity/measure/measure_repository.dart';
import 'package:ambito/src/packages/ambito_notifier/notifier/theme_manager.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';

import '../../consts/consts.dart';
import '../../packages/ambito_theme/ambito_theme.dart';
import '../../widgets/appbar/ambito_appbar.dart';

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

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

class CalendarPageYearState extends State<CalendarPageYear> {
  List<TableRow> rowsBody = <TableRow>[];
  List<TableRow> rowsHeader = <TableRow>[];

  Set<String> displayFilterSet = {'creation', 'maintenance'};

  List<FilterChip> displayFilters = [];
  List<ItemFilter>? monthFilter = [];

  @override
  void initState() {
    ThemeManager().addListener(_updateState);

    super.initState();
  }

  void _updateState() {
    setState(() {});
  }

  initDataSource(BuildContext context, AmbitoTheme theme) {
    List<TableCell> cells = [
      TableCell(
        child: Padding(
          padding: const EdgeInsets.all(8),
          child: Text(
            'Maßnahme',
            style: largeTheme.currentThemeData.textTheme.titleMedium
                ?.copyWith(fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      ),
    ];
    for (String month in months) {
      cells.add(
        TableCell(
          verticalAlignment: TableCellVerticalAlignment.middle,
          child: Text(
            textAlign: TextAlign.center,
            (context.breakpoint.breakpoint == myBreakpoints.sm!.breakpoint)
                ? month.substring(0, 1)
                : (context.breakpoint.breakpoint ==
                        myBreakpoints.md!.breakpoint)
                    ? month.substring(0, 3)
                    : month,
            style: theme.titleMedium
                .copyWith(fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      );
    }
    rowsHeader.add(TableRow(
        decoration: BoxDecoration(color: theme.currentColorScheme.secondary),
        children: cells));
    var massnahmen = MeasureRepository().getAllOrdered();
    for (var massnahme in massnahmen) {
      if (massnahme.measureType != null && massnahme.measureType!.isNotEmpty) {
        cells = [
          TableCell(
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: TextButton(
                onPressed: () {
                  Get.toNamed('/massnahme/${massnahme.id}');
                },
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    textAlign: TextAlign.start,
                    massnahme.measureType!,
                    style: theme.bodySmall,
                  ),
                ),
              ),
            ),
          ),
        ];
        for (String month in months) {
          if (massnahme.applyTimeFrame!
              .where((ele) => ele.value == month)
              .isNotEmpty) {
            cells.add(
              TableCell(
                child: Container(
                  width: double.infinity,
                  height: 44,
                  color: theme.currentColorScheme.secondary,
                ),
              ),
            );
          } else {
            cells.add(
              TableCell(
                child: Container(
                  width: double.infinity,
                  height: 44,
                  color: Colors.transparent,
                ),
              ),
            );
          }
        }
        rowsBody.add(
          TableRow(
            children: cells,
          ),
        );
      }
    }
  }

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

    rowsHeader = [];
    rowsBody = [];

    initDataSource(context, theme);

    double fixedWidth = 120;
    return Scaffold(
      appBar: AmbitoAppbar(
        links: const ['dashboard', 'massnahmen'],
        breakpoint: Breakpoint.fromContext(context),
        theme: theme,
      ),
      body: Card(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 32, left: 32, right: 32),
              child: _buildTableHeader(fixedWidth),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding:
                      const EdgeInsets.only(bottom: 32, left: 32, right: 32),
                  child: _buildTableBody(fixedWidth),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Table _buildTableHeader(double fixedWidth) {
    TableBorder tableBorder = TableBorder(
      top: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      left: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      right: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      bottom: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      horizontalInside: BorderSide(
        width: 1,
        color: Colors.black..withValues(alpha: .6),
      ),
      verticalInside: const BorderSide(
        width: 0,
        color: Colors.transparent,
      ),
    );
    return _getTable(fixedWidth, tableBorder, rowsHeader);
  }

  Table _buildTableBody(double fixedWidth) {
    TableBorder tableBorder = TableBorder(
      top: const BorderSide(
        width: 0,
        color: Colors.black,
      ),
      left: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      right: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      bottom: const BorderSide(
        width: 2,
        color: Colors.black,
      ),
      horizontalInside: BorderSide(
        width: 1,
        color: Colors.black..withValues(alpha: .6),
      ),
      verticalInside: const BorderSide(
        width: 0,
      ),
    );
    return _getTable(fixedWidth, tableBorder, rowsBody);
  }

  Table _getTable(
      double fixedWidth, TableBorder tableBorder, List<TableRow> rows) {
    return Table(
      border: tableBorder,
      columnWidths: <int, TableColumnWidth>{
        0: const FlexColumnWidth(300),
        1: FlexColumnWidth(fixedWidth),
        2: FlexColumnWidth(fixedWidth),
        3: FlexColumnWidth(fixedWidth),
        4: FlexColumnWidth(fixedWidth),
        5: FlexColumnWidth(fixedWidth),
        6: FlexColumnWidth(fixedWidth),
        7: FlexColumnWidth(fixedWidth),
        8: FlexColumnWidth(fixedWidth),
        9: FlexColumnWidth(fixedWidth),
        10: FlexColumnWidth(fixedWidth),
        11: FlexColumnWidth(fixedWidth),
        12: FlexColumnWidth(fixedWidth),
        13: FlexColumnWidth(fixedWidth),
      },
      children: rows,
    );
  }
}
