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

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

const route = useRoute()
const schedulesStore = useSchedulesStore()
const { activeSchedule, detailLoading, detailError, detailNotFound } = storeToRefs(schedulesStore)
const currentScheduleId = ref<number | null>(null)

watch(
  () => route.params.scheduleId,
  async (scheduleIdParameter) => {
    const rawScheduleId = Array.isArray(scheduleIdParameter)
      ? scheduleIdParameter[0]
      : scheduleIdParameter
    const scheduleId = Number(rawScheduleId)
    currentScheduleId.value = scheduleId

    if (activeSchedule.value?.id !== scheduleId) {
      await schedulesStore.fetchSchedule(scheduleId)
    }
  },
  { immediate: true },
)

async function retry(): Promise<void> {
  if (currentScheduleId.value !== null) {
    await schedulesStore.fetchSchedule(currentScheduleId.value)
  }
}

function formatDate(value: string): string {
  return new Intl.DateTimeFormat('en', {
    dateStyle: 'medium',
    timeZone: 'UTC',
  }).format(new Date(`${value}T00:00:00Z`))
}
</script>

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

    <section class="schedule-shell">
      <RouterLink class="back-link" :to="{ name: 'dashboard' }">
        <span aria-hidden="true">←</span>
        Back to dashboard
      </RouterLink>

      <p v-if="detailLoading" class="page-state" role="status">Loading schedule...</p>

      <div v-else-if="detailNotFound" class="page-state page-state--error" role="alert">
        <h1>Schedule not found</h1>
        <p>This schedule is not available.</p>
      </div>

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

      <template v-else-if="activeSchedule !== null">
        <header class="schedule-introduction">
          <p class="eyebrow">
            <span class="schedule-kind">{{ activeSchedule.elementKind }}</span> plan
          </p>
          <h1>{{ activeSchedule.set.name }} schedule</h1>
          <p class="schedule-summary">
            {{ activeSchedule.assignmentCount }}
            {{ activeSchedule.elementKind }}
            {{ activeSchedule.assignmentCount === 1 ? 'assignment' : 'assignments' }} across
            {{ activeSchedule.days.length }}
            {{ activeSchedule.days.length === 1 ? 'day' : 'days' }}
          </p>
          <p class="schedule-range">
            {{ formatDate(activeSchedule.startDate) }} to
            {{ formatDate(activeSchedule.targetDate) }}
          </p>
        </header>

        <ol class="schedule-days" aria-label="Scheduled days">
          <li
            v-for="day in activeSchedule.days"
            :key="day.date"
            class="schedule-day"
            data-schedule-day
            :data-schedule-date="day.date"
          >
            <header class="schedule-day__header">
              <time :datetime="day.date">{{ formatDate(day.date) }}</time>
              <span>{{ day.assignments.length }} assigned</span>
            </header>

            <p v-if="day.assignments.length === 0" class="rest-day">Rest day</p>

            <ul v-else class="assignment-list">
              <li v-for="assignment in day.assignments" :key="assignment.id">
                <span class="assignment-path">{{ assignment.element.path.join(' / ') }}</span>
                <span class="assignment-kind">{{ assignment.element.kind }}</span>
              </li>
            </ul>
          </li>
        </ol>
      </template>
    </section>
  </main>
</template>

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

.schedule-shell {
  width: min(100%, 56rem);
  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,
.retry-button:focus-visible {
  outline: 3px solid rgb(86 127 112 / 34%);
  outline-offset: 0.25rem;
}

.schedule-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;
}

.schedule-kind {
  text-transform: none;
}

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

.schedule-summary {
  margin: 1.35rem 0 0;
  color: #344e45;
  font-weight: 750;
}

.schedule-range {
  margin: 0.5rem 0 0;
  color: #68776f;
}

.schedule-days {
  display: grid;
  gap: 1rem;
  margin: 3rem 0 0;
  padding: 0;
  list-style: none;
}

.schedule-day {
  overflow: hidden;
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  background: rgb(255 253 247 / 82%);
  box-shadow: 0 0.75rem 2rem rgb(40 62 52 / 6%);
}

.schedule-day__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.85rem 1rem;
  border-bottom: 1px solid rgb(24 48 41 / 10%);
  color: #5e7067;
  background: rgb(239 228 212 / 42%);
  font-size: 0.75rem;
  font-weight: 800;
}

.rest-day {
  margin: 0;
  padding: 1.2rem 1rem;
  color: #79877f;
  font-style: italic;
}

.assignment-list {
  display: grid;
  gap: 0;
  margin: 0;
  padding: 0;
  list-style: none;
}

.assignment-list li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 1rem;
}

.assignment-list li + li {
  border-top: 1px solid rgb(24 48 41 / 10%);
}

.assignment-path {
  min-width: 0;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: 1.05rem;
  overflow-wrap: anywhere;
}

.assignment-kind {
  flex: 0 0 auto;
  padding: 0.35rem 0.55rem;
  border-radius: 999px;
  color: #81533a;
  background: #efe4d4;
  font-size: 0.62rem;
  font-weight: 800;
  letter-spacing: 0.1em;
  text-transform: none;
}

.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 h1,
.page-state--error p {
  margin: 0;
}

.page-state--error h1 {
  font-size: clamp(2.25rem, 5vw, 3.6rem);
}

.retry-button {
  min-height: 2.65rem;
  padding: 0.65rem 1rem;
  border: 1px solid rgb(24 58 49 / 28%);
  border-radius: 0.7rem;
  color: #183a31;
  background: #fffdf7;
  font-size: 0.82rem;
  font-weight: 750;
  cursor: pointer;
}

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

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

  .assignment-list li {
    align-items: flex-start;
  }
}
</style>
