import 'package:app_hit_a_wod/src/models/box.model.dart';
import 'package:app_hit_a_wod/src/models/box_order.model.dart';
import 'package:app_hit_a_wod/src/models/box_order_line.model.dart';
import 'package:app_hit_a_wod/src/pages/my_orders/my_orders.page.dart';
import 'package:app_hit_a_wod/src/utils/fontello/my_flutter_app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../styles.dart';

class MyOrderDetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Map<String, dynamic> arguments = ModalRoute.of(context).settings.arguments;
    final BoxOrder bo = arguments["bo"];
    final Box box = arguments["box"];

    return neuScaffoldDetail(
      context: context,
      title: Text("Detalle del pedido", style: Theme.of(context).textTheme.subhead.copyWith(fontWeight: FontWeight.w500, fontSize: 18)),
      action: FlatButton(
        child: shaderContainer(Image.asset('assets/icon/logo.png', height: 35, width: 35,),'in'),
        onPressed: () {
          Navigator.of(context).popUntil(ModalRoute.withName('home'));
        }
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(20),
          child: Column(children: <Widget>[
            MyOrdersPage.miniPedido(context, bo, box, clickable: false),
            SizedBox(height: 20),
            _paymentInformation(context, bo),
            SizedBox(height: 20),
            _downloadInvoice(context, bo), //ja te el sizedbox dins
            _infoBox(context, box),
            SizedBox(height: 20),
            contactButtons(context, box),
            SizedBox(height: 20),
            _detail(context, bo)
          ])
        ),
      )
    );
  }

  _paymentInformation(BuildContext context, BoxOrder bo) {
    return neuContainer(
      Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
        Text("Información de pago", style: Theme.of(context).textTheme.subtitle),
        SizedBox(height: 20),
        (
          bo.payment==null || !bo.payment.charged ?
          (Text("No se ha pagado todavía.", style: Theme.of(context).textTheme.body1)) :
          (Text("El pedido se cobró el día ${DateFormat('dd/MM/yyyy HH:mm').format(bo.payment.updated_at)} correctamente.", style: Theme.of(context).textTheme.body1))
        )
      ])
    );
  }

  _downloadInvoice(BuildContext context, BoxOrder bo) {
    if(bo.invoice==null) return Container();
    else return Column(children: <Widget>[
      neuButton(NeumorphicButton( //boto de iniciar suscripcio amb renovacio automatica
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          style: neuButtonStyle(),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
            Icon(Icons.receipt, size: 20, color: colors["white"]),
            SizedBox(width: 10),
            Text("Ver factura", style: Theme.of(context).textTheme.display2, textAlign: TextAlign.center, overflow: TextOverflow.ellipsis,)
          ]),
          onClick: () {  },
        ), colors: secondaryShadow, width: double.infinity, borderRadius: BorderRadius.all(Radius.circular(8)
      )),
      SizedBox(height: 20)
    ],);
  }

  _infoBox(BuildContext context, Box box) {
    return neuContainer(Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(box.name, style: Theme.of(context).textTheme.subtitle),
      SizedBox(height: 20),
      Text("${box.address}, ${box.postal_code} ${box.city}, ${box.county} ${box.country}", style: Theme.of(context).textTheme.body1),
      SizedBox(height: 20),
      Text("${box.phone}, ${box.email}", style: Theme.of(context).textTheme.body1),
    ]));
  }

  static contactButtons(BuildContext context, Box box) {
    return Row(children: <Widget>[
      Expanded(child: neuButton(NeumorphicButton( //boto de iniciar suscripcio amb renovacio automatica
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          style: neuButtonStyle(),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
            Icon(Icons.phone, size: 20, color: colors["white"]),
            SizedBox(width: 10),
            Text("Llamar", style: Theme.of(context).textTheme.display2, textAlign: TextAlign.left, overflow: TextOverflow.ellipsis,)
          ]),
          onClick: () async {
            final url = "tel:${box.phone}";
            if (await canLaunch(url)) {
              await launch(url);
            } else {
              throw 'Could not launch $url';
            }
          },
        ), colors: primaryColors, width: double.infinity, borderRadius: BorderRadius.all(Radius.circular(8)
      ))),
      SizedBox(width: 20),
      Expanded(child: neuButton(NeumorphicButton( //boto de iniciar suscripcio amb renovacio automatica
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          style: neuButtonStyle(),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
            Icon(Icons.email, size: 20, color: colors["white"]),
            SizedBox(width: 10),
            Text("Email", style: Theme.of(context).textTheme.display2, textAlign: TextAlign.left, overflow: TextOverflow.ellipsis,)
          ]),
          onClick: () async {
            final url = "mailto:${box.email}";
            if (await canLaunch(url)) {
              await launch(url);
            } else {
              throw 'Could not launch $url';
            }
          },
        ), colors: primaryColors, width: double.infinity, borderRadius: BorderRadius.all(Radius.circular(8)
      )))
    ]);
  }

  _detail(BuildContext context, BoxOrder bo) {
    return neuContainer(Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text("Detalle del pedido", style: Theme.of(context).textTheme.subtitle),
      SizedBox(height: 20),
      Text("Subtotal: ${bo.subtotal}€. IVA(${bo.vat}%). Total: ${bo.total}€.", style: Theme.of(context).textTheme.body1),
      SizedBox(height: 20),
      Text("A continuación puedes ver el detalle del pedido:", style: Theme.of(context).textTheme.body1),
      SizedBox(height: 20),
      ListView.builder(
        itemCount: bo.lines.length,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          final BoxOrderLine line = bo.lines[index];
          return Column(children: <Widget>[
            neuContainer(
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                Text(
                  (
                    line.user_subscription_id!=null ?
                    "Suscripción nº ${line.user_subscription_id}" :
                    (
                      line.box_product_variant_id!=null ?
                      "Producto nº ${line.box_product_variant_id}" : 
                      "Sin descripción de línea"
                    )
                  ),
                  style: Theme.of(context).textTheme.body1.copyWith(fontWeight: FontWeight.w500),
                  overflow: TextOverflow.clip,
                ),
                SizedBox(height: 10),
                Text("Cantidad: ${line.quantity}. Precio por unidad: ${line.price.toStringAsFixed(2)}€.", style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip),
                SizedBox(height: 10),
                Text("Subtotal: ${line.subtotal.toStringAsFixed(2)}€. Impuestos: ${line.vat.toStringAsFixed(2)}€. Total: ${line.total.toStringAsFixed(2)}€.", style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip)
              ]),
              width: double.infinity
            ),
            SizedBox(height: 20)
          ]);
        }
      )
    ]), width: double.infinity);
  }

}