import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signature/signature.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';
import 'package:path_provider/path_provider.dart';

class SignatureAndIds extends StatefulWidget {
  final OfflineProfile offlineProfile;
  Function function;
  SignatureAndIds(this.offlineProfile, this.function);

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

class _SignatureAndIds extends State<SignatureAndIds> {
  List<File> _images = []; // List to hold multiple images
  final ImagePicker _picker = ImagePicker();
  SignatureController? _signatureController;

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

  @override
  void dispose() {
    _signatureController!.dispose();
    super.dispose();
  }

// Function to pick multiple images from the gallery
  Future<void> _pickImages() async {
    final List<XFile>? pickedFiles = await _picker.pickMultiImage();

    // Ensure picked files are within the limit
    if (pickedFiles != null && pickedFiles.length + _images.length <= 6) {
      // Convert to unique File instances and add to _images
      List<File> newImages =
          pickedFiles.map((pickedFile) => File(pickedFile.path)).toList();

      setState(() {
        _images.addAll(newImages);
      });

      // Save each image individually
      for (var imageFile in newImages) {
        await _saveImageToDatabase(imageFile);
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('You can only select up to 6 images.'),
      ));
    }
  }

// Function to save image information to the database
  Future<void> _saveImageToDatabase(File imageFile) async {
    int? bldgapprDetailsId = await _getBldgapprDetailsId();
    String dateNw = DateTime.now().toIso8601String();

    ValidIds validID = ValidIds(
      bldgapprDetailsId: bldgapprDetailsId,
      validIds: imageFile.path, // Image path
      dateCreated: dateNw, // Current date
      genCode: "5TH", // Fixed gen code
    );

    await _saveOrUpdateValidIds(bldgapprDetailsId!, validID);
  }

// Function to check whether to create or update the database record
  Future<void> _saveOrUpdateValidIds(
      int bldgapprDetailsId, ValidIds validID) async {
    final List<Map<String, dynamic>> existingIds =
        await SQLServices.instance.getValidIds(bldgapprDetailsId);

    print('existng IDS');
    print(existingIds.length);

    await SQLServices.instance.createValidIds(validID);
  }

  // Function to capture multiple images (up to 5) from the camera
  Future<void> _captureImage() async {
    if (_images.length < 6) {
      final XFile? image = await _picker.pickImage(source: ImageSource.camera);

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

        await _saveImageToDatabase(File(image.path));
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('You can only select up to 6 images.'),
      ));
    }
  }

  // Function to save image information to the database
  // Future<void> _saveImageToDatabase(File imageFile) async {
  //   int? bldgapprDetailsId = await _getBldgapprDetailsId();
  //   String dateNw = DateTime.now().toIso8601String();

  //   ValidIds validID = ValidIds(
  //     bldgapprDetailsId: bldgapprDetailsId,
  //     validIds: imageFile.path, // Image path
  //     dateCreated: dateNw, // Current date
  //     genCode: "5TH", // Fixed gen code
  //   );

  //   await _saveOrUpdateValidIds(bldgapprDetailsId!, validID);
  // }

  // // Function to check whether to create or update the database record
  // Future<void> _saveOrUpdateValidIds(
  //     int bldgapprDetailsId, ValidIds validID) async {
  //   final List<Map<String, dynamic>> existingIds =
  //       await SQLServices.instance.getValidIds(bldgapprDetailsId);

  //     await SQLServices.instance.createValidIds(validID);

  // }

  Future<int?> _getBldgapprDetailsId() async {
    final prefs = await SharedPreferences.getInstance();
    final tempID = prefs.getInt('tempid');
    return tempID;
  }

  Future<String?> _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.png';

        final File imgFile = File(path);
        await imgFile.writeAsBytes(pngBytes);
        print('Signature saved at: $path');

        int? bldgapprDetailsId = await _getBldgapprDetailsId();
        String dateNw = DateTime.now().toIso8601String();

        final ESignature eSignature = ESignature(
          bldgapprDetailsId: bldgapprDetailsId,
          signAttachment: path, // Use the saved signature path
          dateCreated: dateNw,
          dateModified: dateNw,
          genCode: "5TH",
        );

        await SQLServices.instance.createESignature(eSignature);
        return path;
      } catch (e) {
        print('Error saving signature: $e');
        return null;
      }
    }
    return null;
  }

  @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(
                'ID AND SIGNATUREs',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                textAlign: TextAlign.left,
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.45,
                        height: MediaQuery.of(context).size.height * 0.6,
                        child: _images.isNotEmpty
                            ? ListView.builder(
                                itemCount: _images.length,
                                itemBuilder: (context, index) {
                                  return Image.file(_images[index]);
                                },
                              )
                            : Image.asset('assets/pngs/id-card.png'),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                            onPressed: () {
                              _pickImages();
                            },
                            icon: const Icon(Icons.image, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: () {
                              _captureImage();
                            },
                            icon:
                                const Icon(Icons.camera_alt, color: Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.45,
                        height: MediaQuery.of(context).size.height * 0.6,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                    color: Colors.black,
                                    width: 0.1,
                                  ),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.grey.withOpacity(0.5),
                                      spreadRadius: 1,
                                      blurRadius: 5,
                                      offset: Offset(0, 1),
                                    ),
                                  ],
                                ),
                                child: Signature(
                                  controller: _signatureController!,
                                  backgroundColor: Colors.white,
                                ),
                              ),
                            ),
                            Container(
                              width: double.infinity,
                              padding: EdgeInsets.all(8.0),
                              color: Colors.grey[300],
                              child: const Text(
                                'Signature',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          IconButton(
                            onPressed: () {
                              _saveSignature();
                            },
                            icon: const Icon(Icons.check, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: () {
                              _signatureController?.undo();
                            },
                            icon: const Icon(Icons.undo, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: () {
                              _signatureController?.redo();
                            },
                            icon: const Icon(Icons.redo, color: Colors.red),
                          ),
                          IconButton(
                            onPressed: () {
                              _signatureController?.clear();
                            },
                            icon: const Icon(Icons.clear_rounded,
                                color: Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Center(
              child: Container(
                margin: EdgeInsets.only(top: 30.0),
                width: MediaQuery.of(context).size.width * 0.75,
                height: 50,
                child: ElevatedButton(
                  onPressed: () {
                    widget.function();
                  },
                  child: Text("SUBMIT"),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
