<script setup lang="ts">
import Input from '@/components/form/Input.vue';
import TextArea from '@/components/form/TextArea.vue';
import Color from '@/components/form/Color.vue';
import SadFace from '@/icons/SadFace.vue';
import { randomLabel } from '@/lib/randomlabel';
import { useCover } from '@/stores/cover';
import { storeToRefs } from 'pinia';
import { ref } from 'vue';

const store = useCover();
const { customer, prefix, color, number } = storeToRefs(store);

const possibleLabels = [
  'Hit it!',
  'Let it rain!',
  '💰💰💰',
  '🤑🤑🤑',
  'Make Rutte Proud',
  'Kaching!',
  'Rosebud',
  'You show that customer',
  'Do it for Berend',
];
const label = randomLabel(possibleLabels);

const renderError = ref<string | null>(null);

function doRender() {
  try {
    renderError.value = null;
    store.render();
  } catch (e) {
    if (e instanceof Error) {
      renderError.value = e.message;
    } else if (typeof e === 'string') {
      renderError.value = e;
    } else {
      renderError.value = 'An unknown error occurred';
      console.error(e);
    }
  }
}

function onClick() {
  label.update();
  doRender();
}
</script>

<template>
  <div class="p-4 flex flex-col gap-4">
    <h2 class="text-lg font-medium">Settings</h2>
    <TextArea v-model="customer" label="Customer" />
    <Input v-model="prefix" label="Prefix" />
    <Input v-model="number" label="Number" />
    <Color v-model="color" label="Highlight Color" />

    <div
      v-if="renderError !== null"
      class="flex bg-red-100 rounded-lg p-4 mb-4 text-sm text-red-700 items-center gap-2"
      role="alert"
    >
      <SadFace />
      <div><span class="font-medium">Error:</span> {{ renderError }}</div>
    </div>

    <button
      class="px-4 py-2 bg-blue-500 rounded-lg hover:bg-blue-600 text-white border-2 active:border-blue-500 focus:outline focus:outline-2 focus:outline-blue-500"
      @click="onClick"
    >
      {{ label.label.value }}
    </button>
  </div>
</template>