import 'package:fcs/domain/entities/cargo_type.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/dialog_input.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

typedef OnRemove(CargoType cargoType);
typedef OnUpdate(CargoType cargoType);

class CargoTable extends StatefulWidget {
  final List<CargoType>? cargoTypes;
  final bool? isNew;
  final OnRemove? onRemove;
  final OnUpdate? onUpdate;

  const CargoTable(
      {Key? key, this.cargoTypes, this.isNew, this.onRemove, this.onUpdate})
      : super(key: key);

  @override
  _CargoTableState createState() => _CargoTableState();
}

class _CargoTableState extends State<CargoTable> {
  double totalWeight = 0;
  List<CargoType>? cargoTypes;

  @override
  void initState() {
    cargoTypes = widget.cargoTypes;
    if (!widget.isNew!) {
      totalWeight =
          cargoTypes!.fold(0, (previous, current) => previous + current.weight);
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("Cargotypes:${cargoTypes!.length}");

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        showCheckboxColumn: false,
        headingRowHeight: 40,
        columnSpacing: 40,
        columns: [
          DataColumn(
            label: LocalText(
              context,
              "cargo.type",
              color: Colors.grey,
            ),
          ),
          DataColumn(
            label: LocalText(
              context,
              "cargo.qty",
              color: Colors.grey,
            ),
          ),
          DataColumn(
            label: LocalText(
              context,
              "cargo.weight",
              color: Colors.grey,
            ),
          ),
        ],
        rows: getCargoRows(context),
      ),
    );
  }

  List<DataRow> getCargoRows(BuildContext context) {
    if (cargoTypes == null) {
      return [];
    }
    var rows = cargoTypes!.map((c) {
      return DataRow(
        onSelectChanged: (bool? selected) async {},
        cells: [
          DataCell(
            new Text(
              c.name ?? '',
              style: textStyle,
            ),
          ),
          DataCell(
            c.isCutomDuty!
                ? GestureDetector(
                    onTap: () async {
                      String _t = await showDialog(
                          context: context,
                          builder: (_) => DialogInput(
                              label: "cargo.qty", value: c.qty.toString()));

                      if (_t == null) return;
                      setState(() {
                        c.qty = int.tryParse(_t) ?? 0;
                      });
                      if (widget.onUpdate != null) widget.onUpdate!(c);
                    },
                    child: Center(
                      child: Container(
                        width: 40,
                        padding: const EdgeInsets.all(7.0),
                        decoration: BoxDecoration(
                          border: Border.all(color: primaryColor),
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        ),
                        child: new Text(
                          c.qty == null ? "" : c.qty.toString(),
                          style: textStyle,
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  )
                : Center(
                    child: new Text(
                      "-",
                      style: textStyle,
                    ),
                  ),
          ),
          DataCell(
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: () async {
                    if (this.totalWeight <= 0) {
                      showMsgDialog(
                          context, "Error", "Please insert total weight");
                      return;
                    }

                    String _t = await showDialog(
                        context: context,
                        builder: (_) => DialogInput(
                            label: "cargo.weight",
                            value: c.weight.toStringAsFixed(2)));

                    if (_t == null) return;
                    setState(() {
                      c.weight = double.tryParse(_t) ?? 0;
                    });
                    if (c.weight != 0) {
                      _cal();
                    }
                    if (widget.onUpdate != null) widget.onUpdate!(c);
                  },
                  child: Container(
                    padding: const EdgeInsets.all(7.0),
                    decoration: BoxDecoration(
                      border: Border.all(color: primaryColor),
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    ),
                    child: Text(
                        c.weight == null ? "0.00" : c.weight.toStringAsFixed(2),
                        style: textStyle),
                  ),
                ),
                widget.onRemove == null
                    ? SizedBox(
                        width: 50,
                      )
                    : IconButton(
                        icon: Icon(
                          Icons.remove_circle,
                          color: primaryColor,
                        ),
                        onPressed: () {
                          if (widget.onRemove != null) widget.onRemove!(c);
                        })
              ],
            ),
          ),
        ],
      );
    }).toList();

    var totalRow = DataRow(
      onSelectChanged: (bool? selected) {},
      cells: [
        DataCell(Align(
          alignment: Alignment.centerRight,
          child: LocalText(
            context,
            "shipment.cargo.total",
            color: Colors.black87,
            fontWeight: FontWeight.bold,
          ),
        )),
        DataCell(Text("")),
        DataCell(
          Padding(
            padding: const EdgeInsets.only(right: 48.0),
            child: Align(
                alignment: Alignment.centerRight,
                child: InkWell(
                  onTap: () async {
                    String _t = await showDialog(
                      context: context,
                      builder: (_) => DialogInput(
                          label: "shipment.cargo.total",
                          value: totalWeight.toStringAsFixed(2)),
                    );

                    if (_t == null) return;
                    setState(() {
                      totalWeight = double.tryParse(_t) ?? 0;
                    });
                    _cal();
                  },
                  child: Container(
                    padding: const EdgeInsets.all(7.0),
                    decoration: BoxDecoration(
                      border: Border.all(color: primaryColor),
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    ),
                    child: Text(totalWeight.toStringAsFixed(2),
                        style: TextStyle(fontWeight: FontWeight.bold)),
                  ),
                )),
          ),
        ),
      ],
    );
    rows.add(totalRow);
    return rows;
  }

  _cal() {
    var cargoType = autoCalWeight(cargoTypes!, totalWeight);
    if (cargoType == null) return;

    setState(() {
      cargoTypes!.remove(cargoType);
      cargoTypes!.add(cargoType);
    });

    if (widget.onUpdate != null) {
      widget.onUpdate!(cargoType);
    }
  }
}

CargoType? autoCalWeight(List<CargoType> cargoTypes, double total) {
  List<CargoType> noWeight = cargoTypes.where((c) => c.weight == 0).toList();
  if (noWeight.length != 1) return null;

  double _existing =
      cargoTypes.fold(0, (previous, current) => previous + current.weight);

  noWeight[0].weight = total - _existing;
  return noWeight[0];
}
