<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { computed, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { z } from 'zod'

import AuthenticatedHeader from '@/components/AuthenticatedHeader.vue'
import { useSchedulesStore } from '@/stores/schedules'
import { useSetLayoutStore } from '@/stores/setLayout'

type ScheduleField = 'levelId' | 'startDate' | 'targetDate'
type ScheduleFieldErrors = Partial<Record<ScheduleField, string>>

const route = useRoute()
const router = useRouter()
const setLayoutStore = useSetLayoutStore()
const schedulesStore = useSchedulesStore()
const { layout, loading, error, notFound } = storeToRefs(setLayoutStore)
const { creating, createError } = storeToRefs(schedulesStore)
const currentSetId = ref<number | null>(null)
const form = reactive({
  levelId: null as number | null,
  startDate: '',
  targetDate: '',
})
const fieldErrors = ref<ScheduleFieldErrors>({})

const levels = computed(() =>
  (layout.value?.levels ?? []).filter((level) => level.elementCount > 0),
)

const scheduleFormSchema = z
  .object({
    levelId: z.number('Choose a level to schedule.').int().positive(),
    startDate: z.string().min(1, 'Choose a start date.'),
    targetDate: z.string().min(1, 'Choose a target date.'),
  })
  .superRefine((value, context) => {
    if (value.startDate !== '' && value.targetDate !== '' && value.targetDate < value.startDate) {
      context.addIssue({
        code: 'custom',
        path: ['targetDate'],
        message: 'Target date cannot be before the start date.',
      })
    }
  })

watch(
  () => route.params.setId,
  async (setIdParameter) => {
    const rawSetId = Array.isArray(setIdParameter) ? setIdParameter[0] : setIdParameter
    const setId = Number(rawSetId)
    currentSetId.value = setId

    if (layout.value?.set.id !== setId) {
      await setLayoutStore.fetchSetLayout(setId)
    }
  },
  { immediate: true },
)

async function submit(): Promise<void> {
  fieldErrors.value = {}
  const result = scheduleFormSchema.safeParse(form)
  if (!result.success) {
    const errors: ScheduleFieldErrors = {}
    for (const issue of result.error.issues) {
      const field = issue.path[0]
      if (
        (field === 'levelId' || field === 'startDate' || field === 'targetDate') &&
        errors[field] === undefined
      ) {
        errors[field] = issue.message
      }
    }
    fieldErrors.value = errors

    return
  }

  if (
    currentSetId.value === null ||
    !levels.value.some((level) => level.id === result.data.levelId)
  ) {
    fieldErrors.value = {
      levelId: 'Choose an available level to schedule.',
    }

    return
  }

  const schedule = await schedulesStore.createSchedule({
    setId: currentSetId.value,
    ...result.data,
  })
  if (schedule !== null) {
    await router.push({
      name: 'schedule-detail',
      params: { scheduleId: schedule.id },
    })
  }
}

async function retry(): Promise<void> {
  if (currentSetId.value !== null) {
    await setLayoutStore.fetchSetLayout(currentSetId.value)
  }
}
</script>

<template>
  <main class="schedule-form-page">
    <AuthenticatedHeader />

    <section class="schedule-form-shell">
      <RouterLink
        class="back-link"
        :to="{ name: 'set-layout', params: { setId: currentSetId ?? undefined } }"
      >
        <span aria-hidden="true">←</span>
        Back to set
      </RouterLink>

      <p v-if="loading" class="page-state" role="status">Loading scheduling options...</p>

      <div v-else-if="notFound" class="page-state page-state--error" role="alert">
        <h1>Set not found</h1>
        <p>The set you want to schedule is not available.</p>
      </div>

      <div v-else-if="error !== null" class="page-state page-state--error" role="alert">
        <p>{{ error }}</p>
        <button type="button" class="secondary-button" @click="retry">Try again</button>
      </div>

      <template v-else-if="layout !== null">
        <header class="schedule-form__introduction">
          <p class="eyebrow">Create schedule</p>
          <h1>Schedule {{ layout.set.name }}</h1>
          <p>Choose one level of the set and a date range. Every matching item will be included.</p>
        </header>

        <form class="schedule-form" novalidate @submit.prevent="submit">
          <div class="form-field">
            <label for="schedule-level">Level</label>
            <select
              id="schedule-level"
              v-model="form.levelId"
              :aria-invalid="fieldErrors.levelId !== undefined"
              :aria-describedby="fieldErrors.levelId ? 'schedule-level-error' : undefined"
              :disabled="creating"
            >
              <option :value="null">Choose a level</option>
              <option v-for="level in levels" :key="level.id" :value="level.id">
                {{ level.kind }} ({{ level.elementCount }})
              </option>
            </select>
            <p v-if="fieldErrors.levelId" id="schedule-level-error" class="field-error">
              {{ fieldErrors.levelId }}
            </p>
          </div>

          <div class="date-fields">
            <div class="form-field">
              <label for="schedule-start-date">Start date</label>
              <input
                id="schedule-start-date"
                v-model="form.startDate"
                type="date"
                :aria-invalid="fieldErrors.startDate !== undefined"
                :aria-describedby="fieldErrors.startDate ? 'schedule-start-date-error' : undefined"
                :disabled="creating"
              />
              <p v-if="fieldErrors.startDate" id="schedule-start-date-error" class="field-error">
                {{ fieldErrors.startDate }}
              </p>
            </div>

            <div class="form-field">
              <label for="schedule-target-date">Target date</label>
              <input
                id="schedule-target-date"
                v-model="form.targetDate"
                type="date"
                :aria-invalid="fieldErrors.targetDate !== undefined"
                :aria-describedby="
                  fieldErrors.targetDate ? 'schedule-target-date-error' : undefined
                "
                :disabled="creating"
              />
              <p v-if="fieldErrors.targetDate" id="schedule-target-date-error" class="field-error">
                {{ fieldErrors.targetDate }}
              </p>
            </div>
          </div>

          <p v-if="createError !== null" class="form-error" role="alert">{{ createError }}</p>

          <button type="submit" class="primary-button" :disabled="creating">
            {{ creating ? 'Creating schedule...' : 'Create schedule' }}
          </button>
        </form>
      </template>
    </section>
  </main>
</template>

<style scoped>
.schedule-form-page {
  min-height: 100vh;
  min-height: 100svh;
  padding: 2rem clamp(1.5rem, 6vw, 5rem) 5rem;
  color: #183029;
  background: #f4f1e7;
}

.schedule-form-shell {
  width: min(100%, 46rem);
  margin: clamp(3.5rem, 8vh, 5.5rem) auto 0;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 0.45rem;
  border-radius: 0.35rem;
  color: #5e7067;
  font-size: 0.84rem;
  font-weight: 750;
  text-decoration: none;
}

.back-link:focus-visible,
.primary-button:focus-visible,
.secondary-button:focus-visible,
select:focus-visible,
input:focus-visible {
  outline: 3px solid rgb(86 127 112 / 34%);
  outline-offset: 0.25rem;
}

.schedule-form__introduction {
  margin-top: 2.75rem;
}

.eyebrow {
  margin: 0 0 1rem;
  color: #926044;
  font-size: 0.72rem;
  font-weight: 800;
  letter-spacing: 0.14em;
  text-transform: uppercase;
}

h1 {
  margin: 0;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: clamp(2.75rem, 7vw, 4.8rem);
  font-weight: 500;
  line-height: 1;
  letter-spacing: -0.05em;
}

.schedule-form__introduction > p:last-child {
  max-width: 38rem;
  margin: 1.4rem 0 0;
  color: #68776f;
  line-height: 1.7;
}

.schedule-form {
  display: grid;
  gap: 1.5rem;
  margin-top: 2.75rem;
  padding: clamp(1.3rem, 4vw, 2rem);
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  background: rgb(255 253 247 / 82%);
  box-shadow: 0 1rem 2.5rem rgb(40 62 52 / 8%);
}

.form-field {
  display: grid;
  gap: 0.55rem;
}

.date-fields {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 1rem;
}

label {
  font-size: 0.78rem;
  font-weight: 800;
}

select,
input {
  width: 100%;
  min-height: 3rem;
  padding: 0.7rem 0.8rem;
  border: 1px solid rgb(24 58 49 / 22%);
  border-radius: 0.7rem;
  color: #183029;
  background: #fffdf7;
}

select[aria-invalid='true'],
input[aria-invalid='true'] {
  border-color: #a64b3c;
}

.field-error,
.form-error {
  margin: 0;
  color: #934033;
  font-size: 0.76rem;
  line-height: 1.4;
}

.primary-button,
.secondary-button {
  min-height: 2.8rem;
  padding: 0.7rem 1.1rem;
  border-radius: 0.7rem;
  font-weight: 750;
  cursor: pointer;
}

.primary-button {
  justify-self: start;
  border: 0;
  color: #fffdf7;
  background: #183a31;
}

.primary-button:disabled {
  cursor: wait;
  opacity: 0.65;
}

.secondary-button {
  border: 1px solid rgb(24 58 49 / 28%);
  color: #183a31;
  background: #fffdf7;
}

.page-state {
  display: grid;
  min-height: 10rem;
  place-items: center;
  margin-top: 2.75rem;
  padding: 2rem;
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  color: #68776f;
  background: rgb(255 253 247 / 72%);
  text-align: center;
}

.page-state--error {
  align-content: center;
  gap: 1rem;
}

.page-state--error p {
  margin: 0;
}

@media (max-width: 37.5rem) {
  .schedule-form-page {
    padding: 1.4rem 1.1rem 3rem;
  }

  .schedule-form-shell {
    margin-top: 3rem;
  }

  .date-fields {
    grid-template-columns: 1fr;
  }
}
</style>
