import 'package:ambito/src/entity/cart/cart_element.dart';
import 'package:ambito/src/entity/entities.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

import '../../packages/ambito_theme/ambito_theme.dart';

class CartDataSource extends DataGridSource {
  CartDataSource(
      {required this.cartElements,
      required this.context,
      required this.controller}) {
    dataGridRows = cartElements
        .map<DataGridRow>(
          (dataGridRow) => DataGridRow(
            cells: [
              DataGridCell<String>(
                columnName: 'Material',
                value: dataGridRow.name,
              ),
              DataGridCell<String>(
                columnName: 'Menge',
                value: dataGridRow.amount,
              ),
              DataGridCell<List<IdValue>>(
                columnName: 'Anbieter',
                value: dataGridRow.provider,
              ),
              DataGridCell<String>(
                columnName: 'Richtpreis',
                value: dataGridRow.price.toString(),
              ),
            ],
          ),
        )
        .toList();
  }

  final BuildContext context;
  final List<CartElement> cartElements;

  List<DataGridRow> dataGridRows = [];
  final DataGridController controller;

  dynamic newCellValue;

  /// Helps to control the editable text in the [TextField] widget.
  TextEditingController editingController = TextEditingController();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    final AmbitoTheme theme = getTheme(context);

    double completePrice = double.tryParse(row
            .getCells()
            .where((cell) => cell.columnName == 'Richtpreis')
            .first
            .value
            .toString()) ??
        0;

    int amount = int.tryParse(row
            .getCells()
            .where((cell) => cell.columnName == 'Menge')
            .first
            .value
            .toString()) ??
        0;

    if (amount > 1) {
      completePrice = completePrice * amount;
    }

    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>(
      (dataGridCell) {
        if (dataGridCell.columnName == 'Anbieter') {
          final providerString =
              dataGridCell.value.map((ele) => ele.value).toList().join(', ');
          return Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              providerString,
              overflow: TextOverflow.ellipsis,
              style: theme.bodyMedium.copyWith(
                color: theme.currentColorScheme.primary,
              ),
            ),
          );
        }

        if (dataGridCell.columnName == 'Richtpreis') {
          final priceString = amount == 1
              ? '${dataGridCell.value ?? '0'}€'
              : '${completePrice.toStringAsFixed(2)}€ (${dataGridCell.value ?? '0'}€ pro Stk.)';
          return Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              priceString,
              overflow: TextOverflow.ellipsis,
              style: theme.bodyMedium.copyWith(
                color: theme.currentColorScheme.primary,
              ),
            ),
          );
        }
        if (dataGridCell.columnName == 'Menge') {
          return Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              dataGridCell.value,
              textAlign: TextAlign.center,
              style: theme.bodyMedium,
            ),
          );
        }
        return Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.symmetric(horizontal: 10.0),
          child: Text(
            dataGridCell.value.toString(),
            overflow: TextOverflow.ellipsis,
            style: theme.bodyMedium.copyWith(
              color: theme.currentColorScheme.primary,
            ),
          ),
        );
      },
    ).toList());
  }

  @override
  Widget? buildEditWidget(DataGridRow dataGridRow,
      RowColumnIndex rowColumnIndex, GridColumn column, CellSubmit submitCell) {
    // Text going to display on editable widget
    final String displayText = dataGridRow
            .getCells()
            .firstWhereOrNull((DataGridCell dataGridCell) =>
                dataGridCell.columnName == column.columnName)
            ?.value
            ?.toString() ??
        '';

    // The new cell value must be reset.
    // To avoid committing the [DataGridCell] value that was previously edited
    // into the current non-modified [DataGridCell].
    newCellValue = null;

    final int dataRowIndex = dataGridRows.indexOf(dataGridRow);

    final bool isNumericType = column.columnName == 'Menge';

    return Container(
      padding: const EdgeInsets.all(0),
      alignment: isNumericType ? Alignment.centerRight : Alignment.centerLeft,
      child: SpinBox(
        min: 1,
        max: 100,
        value: double.parse(displayText),
        onChanged: (value) {
          //cartElements[dataRowIndex].amount = value.toString();
        },
      ),
      /*NumberInputWithIncrementDecrement(
        controller: editingController,
        buttonArrangement: ButtonArrangement.incRightDecLeft,
        min: 1,
        initialValue: int.parse(displayText),
        enableMinMaxClamping: true,
        incIcon: Icons.add,
        decIcon: Icons.remove,
        onChanged: (value) {
          logger.d('changed to $value');
        },
        onSubmitted: (value) {
          logger.i('submitted $value');
        },
      ),*/
    );
  }
}
