<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useSchemasStore } from '../stores/schemas'
import Icon from '../components/Icon.vue'

const router = useRouter()
const store = useSchemasStore()

const form = ref({
  name: '',
  status: 'active',
  taskStatus: 'active',
  repeatType: 'none',
  date: '',
  start: '',
  end: '',
  weekly: Array(7).fill(false),
  monthly: Array(31).fill(false),
  days: [],
})

const submitting = ref(false)
const error = ref(null)

const weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']

function buildPayload() {
  const data = {
    name: form.value.name,
    status: form.value.status,
    taskStatus: form.value.taskStatus,
  }

  if (form.value.repeatType === 'none') {
    data.date = form.value.date || null
  } else {
    data.start = form.value.start || null
    data.end = form.value.end || null

    if (form.value.repeatType === 'daily') {
      data.repeat = { daily: true }
    } else if (form.value.repeatType === 'weekly') {
      data.repeat = { weekly: [...form.value.weekly] }
    } else if (form.value.repeatType === '2week') {
      data.repeat = { '2week': [...form.value.weekly] }
    } else if (form.value.repeatType === '4week') {
      data.repeat = { '4week': [...form.value.weekly] }
    } else if (form.value.repeatType === 'monthly') {
      data.repeat = { monthly: [...form.value.monthly] }
    } else if (form.value.repeatType === 'days') {
      data.repeat = { days: form.value.days.filter(d => d) }
    }
  }

  return data
}

async function onSave() {
  submitting.value = true
  error.value = null
  try {
    await store.create(buildPayload())
    router.push('/schemas')
  } catch (e) {
    error.value = e.message
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <form class="schema-form" @submit.prevent="onSave">
    <div class="field">
      <label for="name">Name</label>
      <input id="name" v-model="form.name" type="text" required />
    </div>

    <div class="field-row">
      <div class="field">
        <label for="status">Schema Status</label>
        <select id="status" v-model="form.status">
          <option value="active">active</option>
          <option value="inactive">inactive</option>
        </select>
      </div>
      <div class="field">
        <label for="taskStatus">Task Status</label>
        <select id="taskStatus" v-model="form.taskStatus">
          <option value="active">active</option>
          <option value="done">done</option>
          <option value="inactive">inactive</option>
        </select>
      </div>
    </div>

    <div class="field">
      <label for="repeatType">Wiederholung</label>
      <select id="repeatType" v-model="form.repeatType">
        <option value="none">Keine (Einmalig)</option>
        <option value="daily">Täglich</option>
        <option value="weekly">Wöchentlich</option>
        <option value="2week">2-Wöchentlich</option>
        <option value="4week">4-Wöchentlich</option>
        <option value="monthly">Monatlich</option>
        <option value="days">Mehrere Tage</option>
      </select>
    </div>

    <div v-if="form.repeatType === 'none'" class="field">
      <label for="date">Datum</label>
      <input id="date" v-model="form.date" type="date" />
    </div>

    <div v-if="['weekly', '2week', '4week'].includes(form.repeatType)" class="field">
      <label>Wochentage</label>
      <div class="day-grid">
        <label v-for="(day, i) in weekdays" :key="i" class="day-label" :class="{ selected: form.weekly[i] }">
          <input type="checkbox" v-model="form.weekly[i]" class="sr-only" />
          {{ day }}
        </label>
      </div>
    </div>

    <div v-if="form.repeatType === 'monthly'" class="field">
      <label>Monatstage</label>
      <div class="day-grid">
        <label v-for="d in 31" :key="d" class="day-label" :class="{ selected: form.monthly[d - 1] }">
          <input type="checkbox" v-model="form.monthly[d - 1]" class="sr-only" />
          {{ d }}
        </label>
      </div>
    </div>

    <div v-if="form.repeatType === 'days'" class="field">
      <label>Termine</label>
      <div v-for="(d, i) in form.days" :key="i" class="days-row">
        <input type="date" v-model="form.days[i]" />
        <button type="button" class="icon-btn" @click="form.days.splice(i, 1)" title="Entfernen">
          <Icon name="trash" />
        </button>
      </div>
      <button type="button" class="add-termin" @click="form.days.push('')">+ Termin</button>
    </div>

    <div v-if="!['none', 'days'].includes(form.repeatType)" class="field-row">
      <div class="field">
        <label for="start">Start</label>
        <input id="start" v-model="form.start" type="date" />
      </div>
      <div class="field">
        <label for="end">Ende</label>
        <input id="end" v-model="form.end" type="date" />
      </div>
    </div>

    <p v-if="error" class="error">{{ error }}</p>

    <div class="form-actions">
      <button type="submit" :disabled="submitting || !form.name">Erstellen</button>
      <button type="button" @click="router.back()">Abbrechen</button>
    </div>
  </form>
</template>

<style scoped>
.schema-form {
  max-width: 480px;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.field-row {
  display: flex;
  gap: 1rem;
}

.field-row .field {
  flex: 1;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.field label {
  font-size: 0.85rem;
  color: var(--text-muted);
}

.field input,
.field select {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border);
  border-radius: 0.375rem;
  font-size: 1rem;
  font-family: inherit;
  color: var(--text);
  background: var(--bg);
}

.day-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0.25rem;
}

.day-label {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.375rem;
  border: 1px solid var(--border);
  border-radius: 0.25rem;
  font-size: 0.85rem;
  cursor: pointer;
  user-select: none;
}

.day-label.selected {
  background: var(--text);
  color: var(--bg);
  border-color: var(--text);
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

.form-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

button {
  padding: 0.5rem 1rem;
  border: 1px solid var(--border);
  border-radius: 0.375rem;
  background: var(--breadcrumb-bg);
  color: var(--text);
  font-family: inherit;
  cursor: pointer;
}

button[type='submit'] {
  background: var(--text);
  color: var(--bg);
  border-color: var(--text);
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.days-row {
  display: flex;
  gap: 0.5rem;
}

.days-row input {
  flex: 1;
}

.icon-btn {
  width: 2.5rem;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  background: transparent;
  border: 1px solid var(--border);
  border-radius: 0.375rem;
  cursor: pointer;
}

.icon-btn:hover {
  background: var(--breadcrumb-bg);
}

.add-termin {
  align-self: flex-start;
}

.error {
  color: #dc2626;
}
</style>
