import 'dart:typed_data';

import 'package:hl_lieferservice/model/customer.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:signature/signature.dart';

class SignatureView extends StatefulWidget {
  const SignatureView({
    super.key,
    required this.onSigned,
    required this.customer,
  });

  final Customer customer;

  /// Callback that is called when the user has signed.
  /// The parameter stores the path to the image file of the signature.
  final void Function(Uint8List customerSignaturePng, Uint8List driverSignaturePng) onSigned;

  @override
  State<StatefulWidget> createState() => _SignatureViewState();
}

class _SignatureViewState extends State<SignatureView> {
  final SignatureController _customerController = SignatureController(
    penStrokeWidth: 5,
    penColor: Colors.black,
    exportBackgroundColor: Colors.white,
  );

  final SignatureController _driverController = SignatureController(
    penStrokeWidth: 5,
    penColor: Colors.black,
    exportBackgroundColor: Colors.white,
  );

  bool _isDriverSigning = false;
  bool _customerAccepted = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _customerController.dispose();
    super.dispose();
  }

  Widget _signatureField() {
    return Signature(
      controller: _isDriverSigning ? _driverController : _customerController,
      backgroundColor: Colors.white,
    );
  }

  @override
  Widget build(BuildContext context) {
    String formattedDate = DateFormat("dd.MM.yyyy").format(DateTime.now());

    return Scaffold(
      appBar: AppBar(
        title:
            !_isDriverSigning
                ? const Text("Unterschrift des Kunden")
                : const Text("Unterschrift des Fahrers"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: SizedBox(
                width: double.infinity,
                child: DecoratedBox(
                  decoration: const BoxDecoration(color: Colors.white),
                  child: Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "Lieferung an: ${widget.customer.name}",
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Expanded(child: _signatureField()),
                            ],
                          ),
                        ),
                        const Divider(),
                        Text(
                          "${widget.customer.address.city}, den $formattedDate",
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            !_isDriverSigning
                ? Padding(
                  padding: const EdgeInsets.only(top: 25.0, bottom: 25.0),
                  child: Row(
                    children: [
                      Checkbox(
                        value: _customerAccepted,
                        onChanged: (value) {
                          setState(() {
                            _customerAccepted = value!;
                          });
                        },
                      ),
                      const Flexible(
                        child: Text(
                          "Ich bestätige, dass ich die Ware im ordnungsgemäßen Zustand erhalten habe und, dass die Aufstell- und Einbauarbeiten korrekt durchgeführt wurden.",
                          overflow: TextOverflow.fade,
                        ),
                      ),
                    ],
                  ),
                )
                : Container(),
            Padding(
              padding: const EdgeInsets.only(top: 25.0, bottom: 25.0),
              child: Center(
                child: FilledButton(
                  onPressed:
                      !_customerAccepted
                          ? null
                          : () async {
                            if (!_isDriverSigning) {
                              setState(() {
                                _isDriverSigning = true;
                              });
                            } else {
                              widget.onSigned(
                                (await _customerController.toPngBytes())!,
                                (await _driverController.toPngBytes())!,
                              );
                            }
                          },
                  child:
                      !_isDriverSigning
                          ? const Text("Weiter")
                          : const Text("Absenden"),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
