<template>
  <dialog ref="dialog" closedby="none">
    <div class="wrapper" ref="wrapper">
      <form method="dialog">
        <header class="flex-row">
          {{ currentCardIndex > -1 ? 'Bearbeiten' : 'Neues hinzufügen' }}
          <PpButton class="round text">
            <Icon name="uil:times" mode="svg" />
          </PpButton>
        </header>
      </form>
      <main v-if="currentCard">
        <div class="flex-col gap-default">
          <div class="flex-row gap-default">
            <PpFormTextField
              v-model="currentCard.name"
              id="card_name"
              label="Name"
              icon="uil:pricetag-alt"
              :placeholder="randomName"
              :class="{ error: !validFields.name }"
              :message="!validFields.name ? 'Feld darf nicht leer sein.' : ''"
              @input="validFields.name = true"
            />
            <PpFormTextField
              v-model="currentCard.price"
              id="card_price"
              label="Preis"
              placeholder="2,49"
              icon="uil:euro"
              mode="decimal"
              :class="{ error: !validFields.price }"
              :message="!validFields.price ? 'Muss eine Zahl sein.' : ''"
              @input="validFields.price = true"
            />
          </div>
          <div class="flex-row gap-default">
            <PpFormTextField
              v-model="currentCard.roles"
              id="card_roles"
              label="Rollen"
              placeholder="8"
              icon="uil:toilet-paper"
              mode="decimal"
              :class="{ error: !validFields.roles }"
              :message="!validFields.roles ? 'Muss eine Ganzzahl sein.' : ''"
              @input="validFields.roles = true"
            />
            <PpFormTextField
              v-model="currentCard.sheets"
              id="card_sheets"
              label="Blatt"
              placeholder="150"
              icon="uil:file-landscape"
              mode="decimal"
              :class="{ error: !validFields.sheets }"
              :message="!validFields.sheets ? 'Muss eine Ganzzahl sein.' : ''"
              @input="validFields.sheets = true"
            />
            <PpFormTextField
              v-model="currentCard.layers"
              id="card_layers"
              label="Lagen"
              placeholder="3"
              icon="uil:layer-group"
              mode="decimal"
              :class="{ error: !validFields.layers }"
              :message="!validFields.layers ? 'Muss eine Ganzzahl sein.' : ''"
              @input="validFields.layers = true"
            />
          </div>
        </div>
      </main>
      <footer class="flex-row">
        <form method="dialog">
          <PpButton class="danger text">
            <span>Abbrechen</span>
          </PpButton>
        </form>
        <PpButton class="raised" @click="validate">
          <span>{{ currentCardIndex > -1 ? 'Übernehmen' : 'Hinzufügen' }}</span>
        </PpButton>
      </footer>
    </div>
  </dialog>
</template>

<script setup lang="ts">
import type { Card } from '../../../shared/Card'

type Props = {
  currentCardIndex: number
  currentCard?: Card
}

const { currentCardIndex, currentCard } = defineProps<Props>()
const emit = defineEmits(['update'])

const dialog = useTemplateRef<HTMLDialogElement>('dialog')
const wrapper = useTemplateRef<HTMLElement>('wrapper')

const market = [
  'Lotl',
  'Olda',
  'Bäwä',
  'Brutto',
]

const product = [
  'Weichelig',
  'Sau Rauh',
  'Bissl Sanft',
  'Ganz ok',
  'Flauschi'
]

const generateRandomName = () => `${market[Math.floor(Math.random() * market.length)]} ${product[Math.floor(Math.random() * product.length)]}`

const randomName = useState('randomName', () => generateRandomName())

const checkPrice = () => {
  if (!currentCard) return false
  if (currentCard.price.length === 0) return false

  const price = +replaceComma(currentCard.price)
  return !isNaN(price)
}

const checkIfInteger = (toBeNumber: string) => {
  if (toBeNumber.length === 0) return false
  if (toBeNumber.includes(',') || toBeNumber.includes(',')) return false
  return !isNaN(+toBeNumber)
}

const validFields = reactive({
  name: true,
  price: true,
  roles: true,
  sheets: true,
  layers: true,
})

const validate = () => {
  if (!currentCard) return

  validFields.name = currentCard.name.length > 0
  validFields.price = checkPrice()
  validFields.roles = checkIfInteger(currentCard.roles)
  validFields.sheets = checkIfInteger(currentCard.sheets)
  validFields.layers = checkIfInteger(currentCard.layers)

  if (Object.values(validFields).every((value) => value)) {
    emit('update')
    dialog.value?.close()
  }
}

onMounted(() => {
  dialog.value?.addEventListener('close', () => {
    validFields.name = true
    validFields.price = true
    validFields.roles = true
    validFields.sheets = true
    validFields.layers = true
    randomName.value = generateRandomName()
  })

  onClickOutside(wrapper, () => dialog.value?.close())
})
</script>
