import 'dart:convert';

import 'package:aman_kassa_flutter/core/entity/Voucher.dart';
import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/check_image_modal.dart';
import 'package:aman_kassa_flutter/core/models/card_data.dart';
import 'package:aman_kassa_flutter/core/models/check_data.dart';
import 'package:aman_kassa_flutter/core/models/halyk/close_day_data.dart';
import 'package:aman_kassa_flutter/core/route_names.dart';
import 'package:aman_kassa_flutter/core/services/DbService.dart';
import 'package:aman_kassa_flutter/core/services/navigator_service.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:aman_kassa_flutter/views/check/image_show_container.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class HistoryView extends StatefulWidget {
  HistoryView();

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

class _HistoryViewState extends State<HistoryView> {
  DateFormat dateFormat = DateFormat("dd.MM.yyyy HH:mm:ss");
  DbService _dbService = locator<DbService>();
  NavigatorService _navigatorService = locator<NavigatorService>();
  List<Voucher> data = [];
  @override
  void initState() {
    super.initState();
    load();
  }

  load() async {
    List<Map> list = await _dbService.queryAllRowsOrderBy(
        Voucher_tableName, '$Voucher_columnDateTime desc');
    setState(() {
      data = list.map((e) => Voucher.fromMap(e)).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('История чеков'),
        actions: <Widget>[
          TextButton(
              child: Text(
                'Очистить',
                style: TextStyle(
                    color: whiteColor,
                    fontSize: 15,
                    fontWeight: FontWeight.bold),
              ),
              onPressed: () async {
                await _dbService.deleteAll(Voucher_tableName);
                await this.load();
              })
        ],
      ),
      body: ListView.separated(
        itemCount: data.length,
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
        itemBuilder: (BuildContext context, int index) {
          Voucher voucher = data[index];
          CardData? cardData;
          CloseDayData? closeDayData;
          if( voucher.type == VoucherTypeCloseDayPosReport ) {
            closeDayData = CloseDayData.fromJson(json.decode(voucher.data!));
          } else if( voucher.data !=null ) {
            CheckData checkData = CheckData.fromJson(json.decode(voucher.data!));
            cardData = checkData.cardData;
          }

 			String? base64Data = voucher.base64Data;
          CheckImageModal checkImageData;
          if(base64Data !=null && base64Data.startsWith('{')){
            checkImageData = CheckImageModal.fromJson(jsonDecode(base64Data));
          } else {
            checkImageData = new CheckImageModal(base64Data: base64Data);
          }
          return ListTile(
            onTap: () {

              if( voucher.type == VoucherTypeCloseDayPosReport ) {
                _navigatorService.push(CloseDayShowRoute,
                    arguments: closeDayData);
              } else {
                _navigatorService.push(ImageShowRoute,
                    arguments: ImageShowModel(
                      data: checkImageData,
                      title: voucher.name ?? '',
                      url: voucher.url,
                      cardData: cardData,
                      voucher: voucher,
                    ));
              }
            },
            title: buildText(voucher),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(dateFormat.format(voucher.dateTime!)),
                cardData != null ? Text('№ ${cardData.cardNumber} holder: ${cardData.cardholderName}') : Text(''),
              ],
            ),
            trailing: Icon(Icons.arrow_right),
            leading: voucher.type == VoucherTypePayment
                ? Icon(
                    MdiIcons.cashRegister,
                    size: 40,
                  )
                : voucher.type == VoucherTypeReturnPay ? 
                 Icon(
                    MdiIcons.backupRestore,
                    size: 40,
                  )
                : voucher.type == VoucherTypeCloseDayPosReport ?
                  Icon(
                    Icons.phonelink_lock_outlined,
                    size: 40,
                  )
                : Icon(
                    Icons.description,
                    size: 40,
                  ),
          );
        },
      ),
    );
  }

  Text buildText(Voucher voucher) {
    if (voucher.type == VoucherTypePayment || voucher.type == VoucherTypeReturnPay) {
      return Text(
          '${voucher.name} на сумму: ${voucher.total?.toStringAsFixed(2)}');
    }
    return Text('${voucher.name}');
  }
}
