import 'package:flutter/material.dart';
import 'package:gymlink_module_web/components/app_bar.dart';
import 'package:gymlink_module_web/components/heading.dart';
import 'package:gymlink_module_web/tools/prefs.dart';

//TODO: Сделать получение инфы через объект
class DetailPage extends StatefulWidget {
  final String name;
  final String description;
  final String price;
  final String id;
  final Image image;
  const DetailPage({
    super.key,
    required this.name,
    required this.description,
    required this.price,
    required this.id,
    required this.image,
  });

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  bool isInCart = false;
  int quantity = 0;

  @override
  void initState() {
    super.initState();
    getCart().then((value) {
      setState(() {
        isInCart = value.any((element) => element['id'] == widget.id);
        if (isInCart) {
          quantity = value
              .firstWhere((element) => element['id'] == widget.id)['count'];
        }
      });
    });
  }

  Widget _buildRowOrCol(
      {required List<Widget> children,
      required BuildContext context,
      MainAxisAlignment mainAxisAlignment = MainAxisAlignment.spaceAround,
      CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center}) {
    // if (false && MediaQuery.of(context).size.width > 600) {
    //   return Row(
    //       mainAxisAlignment: mainAxisAlignment,
    //       crossAxisAlignment: crossAxisAlignment,
    //       children: children);
    // }
    return Column(
        mainAxisAlignment: mainAxisAlignment,
        crossAxisAlignment: crossAxisAlignment,
        children: children);
  }

  Widget _buildButton() {
    if (!isInCart) {
      return ElevatedButton(
        onPressed: () async {
          await addItemToCart(widget.id);
          setState(() {
            isInCart = true;
            quantity = 1;
          });
        },
        style: ElevatedButton.styleFrom(
            backgroundColor: Theme.of(context).primaryColor,
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(50)),
            ),
            foregroundColor: Colors.white,
            padding: const EdgeInsetsDirectional.fromSTEB(34, 10, 34, 10)),
        child: const Text('Добавить в корзину'),
      );
    } else {
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          IconButton(
            icon: const Icon(Icons.remove),
            onPressed: () async {
              await removeItemFromCart(widget.id);
              setState(() {
                if (quantity > 1) {
                  quantity--;
                } else {
                  isInCart = false;
                  quantity = 0;
                }
              });
            },
          ),
          const SizedBox(width: 10),
          Text('$quantity'),
          const SizedBox(width: 10),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              await addItemToCart(widget.id);
              setState(() {
                quantity++;
              });
            },
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const GymLinkAppBar(),
      body: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
        GymLinkHeader(title: widget.name),
        Expanded(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: SizedBox(
                width: MediaQuery.sizeOf(context).width,
                // height: MediaQuery.sizeOf(context).height,
                child: _buildRowOrCol(
                  context: context,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    widget.image,
                    Padding(
                      padding: const EdgeInsetsDirectional.all(30),
                      child: ConstrainedBox(
                        constraints: const BoxConstraints(
                          minWidth: 340,
                          maxWidth: 340,
                          maxHeight: 600,
                        ),
                        child: Card(
                          elevation: 4,
                          color: Theme.of(context).scaffoldBackgroundColor,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: SingleChildScrollView(
                            child: Padding(
                              padding: const EdgeInsetsDirectional.all(15),
                              child: ConstrainedBox(
                                constraints: const BoxConstraints(
                                  minHeight: 100,
                                ),
                                child: Text(
                                  widget.description,
                                  style: Theme.of(context).textTheme.bodyMedium,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Align(
                      alignment: const AlignmentDirectional(0, -1),
                      child: Padding(
                        padding:
                            const EdgeInsetsDirectional.fromSTEB(0, 30, 0, 0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              'Стоимость ${widget.price}',
                              style: Theme.of(context).textTheme.bodyLarge,
                            ),
                            _buildButton()
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ]),
    );
  }
}
