import 'dart:convert';

import 'package:ambito/src/entity/_general/id_value/id_value.dart';
import 'package:ambito/src/entity/cart/cart.dart';
import 'package:ambito/src/entity/cart/cart_element.dart';
import 'package:ambito/src/extensions/extensions.dart';
import 'package:ambito/src/packages/ambito_api/base_api.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../consts/consts.dart';
import '../../../../entity/measure/complete/measure_complete.dart';
import '../../../../packages/ambito_theme/ambito_theme.dart';
import '../../../../widgets/buttons/text_button.dart';
import '../../../cart/cart_page.dart';
import '_sidebar_card.dart';

class MaterialCard extends StatelessWidget {
  MaterialCard({super.key, required this.massnahme});

  final MeasureComplete massnahme;

  final List<CartElement> elements = [];

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

    return SideBarCard(
      massnahme: massnahme,
      title: 'page.actionDetailPage.material.title',
      content: [
        _getSortedMaterials(context),
        theme.verticalSpacer,
        if (massnahme.costs != null)
          Text(
            '${context.translate('page.actionDetailPage.material.suggested_price')} ${massnahme.costs} €',
            style: theme.bodyMedium.copyWith(fontWeight: FontWeight.bold),
          ),
        theme.verticalSpacer,
        Align(
          alignment: Alignment.center,
          child: TextButtonElement(
            title: 'page.actionDetailPage.material.add_to_basket',
            onPressed: () async {
              prefs.setBool('extended_json', false).then((_) async {
                var cartId = isar.carts.autoIncrement();
                Cart newCart = Cart()
                  ..id = cartId
                  ..name = massnahme.name
                  ..business = [
                    (IdValue()..id = (prefs.getInt('currrentUser') ?? 100))
                  ];

                final cart = await BaseApi()
                    .postContent('cart', newCart.toJson(), false);
                newCart = Cart.fromJson(jsonDecode(cart));
                IdValue cartIdv = (IdValue()..id = newCart.id);
                List<CartElement> elements = [];
                final cartElement = CartElement()
                  ..id = isar.cartElements.autoIncrement()
                  ..cart = [cartIdv]
                  ..name = massnahme.name
                  ..amount = '1'
                  ..priceType = massnahme.costsUnit
                  ..provider = <IdValue>[]
                  ..price = massnahme.costs ?? '0.0';
                await BaseApi()
                    .postContent('cart_elements', cartElement.toJson(), false);
                elements.add(cartElement);
                for (var item in massnahme.applyMaterials ?? []) {
                  final addtionalElement = CartElement()
                    ..id = isar.cartElements.autoIncrement()
                    ..cart = [cartIdv]
                    ..name = item
                    ..amount = '1'
                    ..priceType = 'Stk'
                    ..provider = <IdValue>[]
                    ..price = '0.0';
                  await BaseApi().postContent(
                      'cart_elements', addtionalElement.toJson(), false);
                  elements.add(addtionalElement);
                }

                Get.to(() => CartPage(measure: massnahme));
              });
            },
          ),
        )
      ],
    );
  }

  _getSortedMaterials(BuildContext context) {
    final AmbitoTheme theme = getTheme(context);

    List<String> items = massnahme.applyMaterials ?? [];
    items.sort((a, b) => a.toString().compareTo(b.toString()));
    List<Widget> tiles = [];
    for (String item in items) {
      elements.add(
        CartElement()
          ..name = item
          ..amount = '1'
          ..price = massnahme.costs ?? '0.0',
      );
      tiles.add(
        Row(
          children: [
            const Icon(
              Icons.fiber_manual_record,
              size: 8,
            ),
            theme.horizontalSpacerSmall,
            Expanded(
              child: Text(
                item,
                style: theme.currentThemeData.textTheme.bodyLarge,
              ),
            )
          ],
        ),
      );
    }
    return Column(
      children: tiles,
    );
  }
}
