<template>
  <div>
    <Vue3Signature
      ref="signatureRef"
      :sigOption="options"
      @save="onSave"
      style="border: 1px solid #ccc; width: 100%; height: 200px"
    />
    <div class="mt-4 flex justify-end">
      <button @click="clear" class="px-4 py-2 bg-red-500 rounded">Clear</button>
      <button @click="save" class="px-4 py-2 bg-green-500 rounded ml-2">
        Save
      </button>
    </div>

    <div style="position: fixed; top: 20px; right: 20px; z-index: 9999">
      <Snackbar
        v-model="messageSnackbar"
        :text="message"
        :color="messageColor"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from "vue";
import Vue3Signature from "vue3-signature";

const props = defineProps({
  modelValue: String,
  hideToast: {
    type: Boolean,
    default: false,
  }
});

const emit = defineEmits(["update:modelValue"]);

const signatureRef = ref();

const options = {
  penColor: "black",
  backgroundColor: "white",
};

// Snackbar control
const message = ref("");
const messageColor = ref("");
const messageSnackbar = ref(false);

function showMessage(msg: string, color: string) {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

function onSave(data: string) {
  emit("update:modelValue", data);
  if(!props.hideToast) {
    showMessage("Signature saved successfully.", "success");
  }
}

function save() {
  const signatureData = signatureRef.value?.save("image/jpeg");
  if (signatureData) {
    emit("update:modelValue", signatureData);
      if(!props.hideToast) {
        showMessage("Signature saved successfully.", "success");
      }
  } else {
    if(!props.hideToast) {
      showMessage("No signature to save.", "error");
    }
  }
}

function clear() {
  signatureRef.value?.clear();
  if(!props.hideToast) {
    showMessage("Signature cleared.", "success");
  }
}
</script>
