import 'dart:convert';

import 'package:ambito/src/entity/measure/months/measure_months.dart';
import 'package:ambito/src/entity/measure/months/measure_months_datasource.dart';
import 'package:ambito/src/packages/ambito_theme/ambito_theme.dart';
import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:toggle_switch/toggle_switch.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../consts/consts.dart';
import '../../widgets/buttons/print_button.dart';
import '../../widgets/page/base_page.dart';

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

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

class CalendarPageState extends State<CalendarPage> {
  int display = 0;

  String type = 'maintenance';

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

  @override
  Widget build(BuildContext context) {
    List<MeasureMonths> mm = isar.measureMonths.where().sortByName().findAll();

    final AmbitoTheme theme = getTheme(context);

    final GlobalKey<SfDataGridState> key = GlobalKey<SfDataGridState>();

    return BasePage().getPage(
        context,
        SingleChildScrollView(
          child: Expanded(
            child: Align(
              alignment: Alignment.topCenter,
              child: Padding(
                padding: context.breakpoint.padding,
                child: SizedBox(
                  width: 1152,
                  height: MediaQuery.of(context).size.height - 80,
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 40),
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        theme.verticalSpacerMax,
                        Text(
                          'Kalender',
                          textAlign: TextAlign.start,
                          style: theme.headlineLarge.copyWith(
                            color: theme.currentColorScheme.onSurface,
                          ),
                        ),
                        theme.verticalSpacer,
                        Row(
                          children: [
                            ToggleSwitch(
                              initialLabelIndex: display,
                              totalSwitches: 2,
                              minWidth: 200,
                              borderWidth: 1,
                              labels: const ['Pflege', 'Maßnahme'],
                              activeBgColor: [
                                theme.currentColorScheme.secondary
                              ],
                              borderColor: [theme.currentColorScheme.secondary],
                              inactiveBgColor: Colors.white,
                              activeFgColor:
                                  theme.currentColorScheme.onSecondary,
                              customTextStyles: [theme.bodyMedium],
                              onToggle: (index) {
                                setState(() {
                                  display = index ?? 0;
                                  if (display == 0) {
                                    type = 'maintenance';
                                  } else {
                                    type = 'apply';
                                  }
                                });
                              },
                            ),
                            Spacer(),
                            PrintButton(
                              onPressed: () async {
                                PdfDocument document =
                                    key.currentState!.exportToPdfDocument(
                                  headerFooterExport:
                                      (DataGridPdfHeaderFooterExportDetails
                                          headerFooterExport) {
                                    final double width = headerFooterExport
                                        .pdfPage
                                        .getClientSize()
                                        .width;
                                    final PdfPageTemplateElement header =
                                        PdfPageTemplateElement(
                                            Rect.fromLTWH(0, 0, width, 65));
                                    header.graphics.drawString(
                                      'Dingens"',
                                      PdfStandardFont(
                                          PdfFontFamily.helvetica, 13,
                                          style: PdfFontStyle.bold),
                                      bounds:
                                          const Rect.fromLTWH(0, 25, 400, 60),
                                    );
                                    headerFooterExport.pdfDocumentTemplate.top =
                                        header;
                                  },
                                  cellExport: (details) {},
                                  fitAllColumnsInOnePage: true,
                                );
                                final List<int> bytes = document.saveSync();
                                launchUrl(Uri.parse(
                                    "data:application/octet-stream;base64,${base64Encode(bytes)}"));
                              },
                            ),
                          ],
                        ),
                        theme.verticalSpacer,
                        Expanded(
                          child: gridWidget(
                            mm,
                            key,
                          ),
                        ),
                        theme.verticalSpacerMax,
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ));
  }

  Widget gridWidget(List<MeasureMonths> mm, GlobalKey<SfDataGridState> key) {
    final AmbitoTheme theme = getTheme(context);

    return SizedBox(
      width: 1152,
      child: SfDataGridTheme(
        data: SfDataGridThemeData(
          headerColor: theme.currentColorScheme.primaryContainer,
          sortIcon: Icon(
            Icons.keyboard_arrow_down,
            color: theme.currentColorScheme.primary,
          ),
        ),
        child: SfDataGrid(
          isScrollbarAlwaysShown: true,
          key: key,
          allowSorting: false,
          source:
              MeasureMonthsDatasource(areas: mm, context: context, type: type),
          columnWidthMode: ColumnWidthMode.fill,
          columns: [
            GridColumn(
              columnName: 'Bezeichnung',
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Bezeichnung',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Jan',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Jan',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Feb',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Feb',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Mär',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Mär',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Apr',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Apr',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Mai',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Mai',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Jun',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Jun',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Jul',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Jul',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Aug',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Aug',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Sep',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Sep',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Okt',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Okt',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Nov',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Nov',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
            GridColumn(
              columnName: 'Dez',
              maximumWidth: 70,
              label: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Dez',
                  overflow: TextOverflow.ellipsis,
                  style: theme.bodyMedium.copyWith(
                    color: theme.currentColorScheme.primary,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
