// ignore_for_file: use_super_parameters, non_constant_identifier_names, avoid_print, use_build_context_synchronously, unused_import, unused_element

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:http/http.dart' as http;
import 'package:printing/printing.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../constants.dart';

import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

class PurchaseHistoryInvoice extends StatefulWidget {
  final int? id;
  final String? createdAt;
  final String? courseTitle;
  final String? paymentType;
  final String? currency;
  final double? amount;
  final bool autoPrint;

  const PurchaseHistoryInvoice({
    Key? key,
    this.id,
    this.createdAt,
    this.courseTitle,
    this.paymentType,
    this.currency,
    this.amount,
    this.autoPrint = false,
  }) : super(key: key);

  @override
  State<PurchaseHistoryInvoice> createState() => _PurchaseHistoryInvoiceState();
}

class _PurchaseHistoryInvoiceState extends State<PurchaseHistoryInvoice> {
  bool _printedOnce = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    if (widget.autoPrint && !_printedOnce) {
      _printedOnce = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Invoice',
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _infoRow("ID", widget.id.toString()),
            _infoRow("Date", widget.createdAt ?? ""),
            _infoRow("Item", widget.courseTitle ?? ""),
            _infoRow("Payment Method", widget.paymentType ?? ""),
            _infoRow(
              "Total Amount",
              "${widget.currency ?? ''} ${widget.amount ?? ''}",
            ),
          ],
        ),
      ),
    );
  }

  Widget _infoRow(String title, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 14),
      child: LayoutBuilder(
        builder: (context, constraints) {
          double keyWidth = constraints.maxWidth * 0.40;
          return Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: keyWidth,
                child: Text(
                  title,
                  style: const TextStyle(fontWeight: FontWeight.normal),
                ),
              ),
              const Text(" : "),
              Expanded(
                child: Text(
                  value,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
