import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:signature/signature.dart';
import 'package:path_provider/path_provider.dart';
import 'package:unit2/model/offline/offline_profile.dart';
import 'package:unit2/model/passo/esignature.dart';
import 'package:unit2/model/passo/valid_ids.dart';
import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';
import 'dart:ui' as ui;
import 'dart:typed_data';

class EditSignatureAndIds extends StatefulWidget {
  final OfflineProfile offlineProfile;
  final Function function;
  final int faasId; // Assuming widget.faas.id! is of type int

  EditSignatureAndIds(this.offlineProfile, this.function, this.faasId);

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

class _EditSignatureAndIds extends State<EditSignatureAndIds> {
  bool _isEditingSignature = false; // State for editing signature
  File? _image;
  SignatureController? _signatureController;
  final ImagePicker _picker = ImagePicker();

  ValidIds? _validIds; // For storing fetched ValidIds record
  ESignature? _eSignature; // For storing fetched ESignature record

  @override
  void initState() {
    super.initState();
    _signatureController = SignatureController(
      penStrokeWidth: 3,
      penColor: Colors.black87,
      exportBackgroundColor: Colors.white,
    );

    _loadValidIdsAndSignature(widget.faasId);
  }

  Future<void> _loadValidIdsAndSignature(int faasId) async {
    try {
      // Fetch ValidIds using faasId
      List<Map<String, dynamic>> validIdsList =
          await SQLServices.instance.getValidIds(faasId);
      if (validIdsList.isNotEmpty) {
        setState(() {
          _validIds = ValidIds.fromJson(validIdsList.first);
          _image = File(_validIds!.validIds!); // Load the image if it exists
        });
      }

      // Fetch ESignature using faasId
      List<Map<String, dynamic>> signatureList =
          await SQLServices.instance.getESignature(faasId);
      if (signatureList.isNotEmpty) {
        setState(() {
          _eSignature = ESignature.fromJson(signatureList.first);
        });
      }
    } catch (e) {
      print("Error loading ValidIds or Signature: $e");
    }
  }

  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() {
        _image = File(image.path);
      });

      // Update the ValidIds record
      if (_validIds != null) {
        _validIds!.validIds = image.path;

        // You may also want to update the database at this point
        await SQLServices.instance
            .updateValidIds(_validIds!.bldgapprDetailsId ?? 0, _validIds!);
      }
    }
  }

  Future<void> _captureImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.camera);

    if (image != null) {
      setState(() {
        _image = File(image.path);
      });

      // Update the ValidIds record
      if (_validIds != null) {
        _validIds!.validIds = image.path;

        // You may also want to update the database at this point
        await SQLServices.instance
            .updateValidIds(_validIds!.bldgapprDetailsId ?? 0, _validIds!);
      }
    }
  }

  Future<void> _saveSignature() async {
    if (_signatureController!.isNotEmpty) {
      try {
        final ui.Image? image = await _signatureController?.toImage();
        final ByteData? byteData =
            await image?.toByteData(format: ui.ImageByteFormat.png);
        final Uint8List pngBytes = byteData!.buffer.asUint8List();

        final directory = await getApplicationDocumentsDirectory();
        final String path = '${directory.path}/signature_${widget.faasId}.png';

        final File imgFile = File(path);
        await imgFile.writeAsBytes(pngBytes);

        // Update or create the signature record in the database
        if (_eSignature != null) {
          _eSignature!.signAttachment = path; // Update existing signature
          await SQLServices.instance
              .updateESignature(widget.faasId, _eSignature!);
        } else {
          // Create a new signature if not exists
          final ESignature newSignature = ESignature(
            bldgapprDetailsId: widget.faasId,
            signAttachment: path,
            dateCreated: DateTime.now().toIso8601String(),
            dateModified: DateTime.now().toIso8601String(),
            genCode: "5TH",
          );
          await SQLServices.instance.createESignature(newSignature);
        }
      } catch (e) {
        print('Error saving signature: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin:
                  const EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 10),
              child: const Text(
                'EDIT ID AND SIGNATURE',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                textAlign: TextAlign.left,
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      // ID section
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.45,
                        height: MediaQuery.of(context).size.height * 0.6,
                        child: _image != null
                            ? Image.file(_image!)
                            : Image.asset('assets/pngs/id-card.png'),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                            onPressed: _pickImage,
                            icon: const Icon(Icons.image, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: _captureImage,
                            icon:
                                const Icon(Icons.camera_alt, color: Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    children: [
                      // Signature section
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.45,
                        height: MediaQuery.of(context).size.height * 0.6,
                        child: _isEditingSignature
                            ? Signature(
                                controller: _signatureController!,
                                backgroundColor: Colors.white,
                              )
                            : (_eSignature != null &&
                                    _eSignature!.signAttachment != null)
                                ? Image.file(File(_eSignature!.signAttachment!))
                                : Container(
                                    color: Colors.grey[300],
                                    child: const Center(
                                      child: Text('No Signature Available'),
                                    ),
                                  ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                            onPressed: () {
                              if (_isEditingSignature) {
                                _saveSignature(); // Save the signature if editing
                              }
                              setState(() {
                                _isEditingSignature =
                                    !_isEditingSignature; // Toggle editing state
                                if (!_isEditingSignature) {
                                  _signatureController
                                      ?.clear(); // Clear the signature pad
                                }
                              });
                            },
                            icon: const Icon(Icons.edit, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: () {
                              _signatureController
                                  ?.clear(); // Clear the signature pad
                            },
                            icon: const Icon(Icons.clear, color: Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Center(
              child: Container(
                margin: const EdgeInsets.only(top: 30.0),
                width: MediaQuery.of(context).size.width * 0.75,
                height: 50,
                child: ElevatedButton(
                  onPressed: () {
                    widget.function(); // Call the passed function
                  },
                  child: const Text("SUBMIT"),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
