<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'

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

const setsStore = useSetsStore()
const schedulesStore = useSchedulesStore()
const { sets, loading, error } = storeToRefs(setsStore)
const { schedules, listLoading, listError } = storeToRefs(schedulesStore)
const { assignmentsForDate, assignmentsLoading, assignmentsError } = storeToRefs(schedulesStore)
const todayDate = ref(browserDate(new Date()))

onMounted(async () => {
  await Promise.all([
    setsStore.fetchSets(),
    schedulesStore.fetchSchedules(),
    schedulesStore.fetchAssignmentsForDate(todayDate.value),
  ])
})

function browserDate(date: Date): string {
  const year = String(date.getFullYear()).padStart(4, '0')
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

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

async function completeAssignment(assignmentId: number): Promise<void> {
  await schedulesStore.setAssignmentCompleted(assignmentId, true)
}
</script>

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

    <section class="today-assignments" aria-labelledby="today-heading">
      <header class="today-assignments__introduction">
        <div>
          <p class="sets-catalog__eyebrow">Today's work</p>
          <h1 id="today-heading">Today</h1>
        </div>
        <time :datetime="todayDate" :data-today-date="todayDate">
          {{ formatDate(todayDate) }}
        </time>
      </header>

      <p v-if="assignmentsLoading" class="today-state" role="status">
        Loading today's assignments...
      </p>

      <div
        v-else-if="assignmentsError !== null"
        class="today-state today-state--error"
        role="alert"
      >
        <p>{{ assignmentsError }}</p>
        <button
          type="button"
          class="retry-button"
          @click="schedulesStore.fetchAssignmentsForDate(todayDate)"
        >
          Try again
        </button>
      </div>

      <p v-else-if="assignmentsForDate.length === 0" class="today-state" role="status">
        Nothing is assigned for today.
      </p>

      <ul v-else class="today-assignment-list" aria-label="Today's assignments">
        <li
          v-for="assignment in assignmentsForDate"
          :key="assignment.id"
          :data-today-assignment="assignment.id"
        >
          <article class="today-assignment">
            <RouterLink
              class="today-assignment-link"
              :to="{
                name: 'schedule-detail',
                params: { scheduleId: assignment.schedule.id },
              }"
            >
              <div class="today-assignment__heading">
                <p>{{ assignment.schedule.set.name }}</p>
                <span class="today-assignment__kind">{{ assignment.element.kind }}</span>
              </div>
              <p class="today-assignment__path">
                {{ assignment.element.path.join(' / ') }}
              </p>
              <span class="today-assignment__action">
                Open schedule
                <span aria-hidden="true">→</span>
              </span>
            </RouterLink>
            <div class="today-assignment__completion">
              <p
                v-if="schedulesStore.assignmentCompletionError(assignment.id) !== null"
                class="assignment-completion-error"
                role="alert"
              >
                {{ schedulesStore.assignmentCompletionError(assignment.id) }}
              </p>
              <button
                type="button"
                class="assignment-completion-button"
                :aria-label="`Mark ${assignment.element.path.join(' / ')} complete`"
                :disabled="schedulesStore.isAssignmentCompletionPending(assignment.id)"
                @click="completeAssignment(assignment.id)"
              >
                {{
                  schedulesStore.isAssignmentCompletionPending(assignment.id)
                    ? 'Completing...'
                    : 'Mark complete'
                }}
              </button>
            </div>
          </article>
        </li>
      </ul>
    </section>

    <section class="schedules-catalog" aria-labelledby="schedules-heading">
      <div class="schedules-catalog__heading">
        <div>
          <p class="sets-catalog__eyebrow">Your plans</p>
          <h2 id="schedules-heading">Your schedules</h2>
        </div>
        <p>Return to a plan and see what is assigned for each day.</p>
      </div>

      <p v-if="listLoading" class="catalog-state catalog-state--compact" role="status">
        Loading schedules...
      </p>

      <div
        v-else-if="listError !== null"
        class="catalog-state catalog-state--compact catalog-state--error"
        role="alert"
      >
        <p>{{ listError }}</p>
        <button type="button" class="retry-button" @click="schedulesStore.fetchSchedules">
          Try again
        </button>
      </div>

      <p
        v-else-if="schedules.length === 0"
        class="catalog-state catalog-state--compact"
        role="status"
      >
        You have not created a schedule yet.
      </p>

      <ul v-else class="schedule-grid" aria-label="Your schedules">
        <li v-for="schedule in schedules" :key="schedule.id">
          <RouterLink
            class="schedule-card-link"
            :to="{ name: 'schedule-detail', params: { scheduleId: schedule.id } }"
          >
            <article class="schedule-card">
              <div class="schedule-card__heading">
                <p class="schedule-card__kind">{{ schedule.elementKind }}</p>
                <span>{{ schedule.assignmentCount }} assignments</span>
              </div>
              <h3>{{ schedule.set.name }}</h3>
              <span class="schedule-card__dates">
                {{ formatDate(schedule.startDate) }} to {{ formatDate(schedule.targetDate) }}
              </span>
            </article>
          </RouterLink>
        </li>
      </ul>
    </section>

    <section class="sets-catalog" aria-labelledby="sets-heading">
      <div class="sets-catalog__introduction">
        <p class="sets-catalog__eyebrow">Your library</p>
        <h2 id="sets-heading">Available sets</h2>
        <p class="sets-catalog__description">
          Browse every set available in Attainly and find the collection that fits your next goal.
        </p>
      </div>

      <p v-if="loading" class="catalog-state" role="status">Loading sets...</p>

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

      <p v-else-if="sets.length === 0" class="catalog-state" role="status">
        No sets are available yet.
      </p>

      <ul v-else class="set-grid" aria-label="Available sets">
        <li v-for="availableSet in sets" :key="availableSet.id">
          <RouterLink
            class="set-card-link"
            :to="{ name: 'set-layout', params: { setId: availableSet.id } }"
          >
            <article class="set-card">
              <p>Set</p>
              <h2>{{ availableSet.name }}</h2>
              <span class="set-card__action">
                Explore layout
                <span aria-hidden="true">→</span>
              </span>
            </article>
          </RouterLink>
        </li>
      </ul>
    </section>
  </main>
</template>

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

.sets-catalog {
  width: min(100%, 72rem);
  margin: clamp(4.5rem, 10vh, 7rem) auto 0;
}

.today-assignments {
  width: min(100%, 72rem);
  margin: clamp(4.5rem, 10vh, 7rem) auto 0;
}

.today-assignments__introduction {
  display: flex;
  align-items: end;
  justify-content: space-between;
  gap: 2rem;
}

.today-assignments__introduction time {
  color: #68776f;
  font-size: 0.82rem;
  font-weight: 700;
}

.schedules-catalog {
  width: min(100%, 72rem);
  margin: clamp(3.5rem, 8vh, 5.5rem) auto 0;
}

.schedules-catalog__heading {
  display: flex;
  align-items: end;
  justify-content: space-between;
  gap: 2rem;
}

.schedules-catalog__heading h2 {
  margin: 0;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: clamp(2.25rem, 5vw, 3.5rem);
  font-weight: 500;
  line-height: 1;
  letter-spacing: -0.045em;
}

.schedules-catalog__heading > p {
  max-width: 24rem;
  margin: 0;
  color: #68776f;
  line-height: 1.6;
}

.sets-catalog__introduction {
  max-width: 44rem;
}

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

.today-assignments h1,
.sets-catalog__introduction h2 {
  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;
}

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

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

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

.today-assignment-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 20rem), 1fr));
  gap: 1rem;
  margin: 2rem 0 0;
  padding: 0;
  list-style: none;
}

.today-assignment-link {
  display: block;
  color: inherit;
  text-decoration: none;
}

.today-assignment {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 1.4rem;
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  background: linear-gradient(135deg, rgb(255 253 247 / 98%), rgb(244 238 225 / 86%));
  box-shadow: 0 0.75rem 2rem rgb(40 62 52 / 7%);
  transition:
    border-color 160ms ease,
    transform 160ms ease;
}

.today-assignment:hover {
  border-color: rgb(40 92 78 / 35%);
  transform: translateY(-2px);
}

.today-assignment-link:focus-visible {
  outline: 3px solid rgb(86 127 112 / 38%);
  outline-offset: 0.25rem;
}

.today-assignment__heading {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  color: #926044;
  font-size: 0.7rem;
  font-weight: 800;
  letter-spacing: 0.08em;
  text-transform: uppercase;
}

.today-assignment__heading p {
  margin: 0;
}

.today-assignment__kind {
  text-transform: none;
}

.today-assignment__path {
  margin: 1.75rem 0 0;
  color: #183029;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: 1.45rem;
  line-height: 1.2;
}

.today-assignment__action {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  margin-top: 1.25rem;
  color: #567064;
  font-size: 0.76rem;
  font-weight: 750;
}

.today-assignment__completion {
  display: grid;
  justify-items: start;
  gap: 0.65rem;
  margin-top: auto;
  padding-top: 1.15rem;
  border-top: 1px solid rgb(24 48 41 / 10%);
}

.assignment-completion-button {
  min-height: 2.5rem;
  padding: 0.6rem 0.9rem;
  border: 1px solid rgb(24 58 49 / 28%);
  border-radius: 0.7rem;
  color: #fffdf7;
  background: #285c4e;
  font-size: 0.78rem;
  font-weight: 800;
  cursor: pointer;
}

.assignment-completion-button:hover:not(:disabled) {
  background: #183a31;
}

.assignment-completion-button:focus-visible {
  outline: 3px solid rgb(86 127 112 / 34%);
  outline-offset: 0.25rem;
}

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

.assignment-completion-error {
  margin: 0;
  color: #9b3f32;
  font-size: 0.76rem;
  font-weight: 700;
}

.sets-catalog__description {
  max-width: 38rem;
  margin: 1.5rem 0 0;
  color: #68776f;
  line-height: 1.7;
}

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

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

.catalog-state--compact {
  min-height: 7rem;
  margin-top: 2rem;
}

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

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

.retry-button:hover {
  border-color: #285c4e;
  background: #f9f5e9;
}

.retry-button:focus-visible {
  outline: 3px solid rgb(86 127 112 / 34%);
  outline-offset: 0.25rem;
}

.set-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
  gap: 1rem;
  margin: 3rem 0 0;
  padding: 0;
  list-style: none;
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
  gap: 1rem;
  margin: 2rem 0 0;
  padding: 0;
  list-style: none;
}

.schedule-card-link {
  display: block;
  height: 100%;
  border-radius: 1rem;
  text-decoration: none;
}

.schedule-card {
  height: 100%;
  padding: 1.4rem;
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  background: rgb(255 253 247 / 88%);
  box-shadow: 0 0.75rem 2rem rgb(40 62 52 / 7%);
  transition:
    border-color 160ms ease,
    transform 160ms ease;
}

.schedule-card-link:hover .schedule-card {
  border-color: rgb(40 92 78 / 35%);
  transform: translateY(-2px);
}

.schedule-card-link:focus-visible {
  outline: 3px solid rgb(86 127 112 / 38%);
  outline-offset: 0.25rem;
}

.schedule-card__heading {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  color: #926044;
  font-size: 0.68rem;
  font-weight: 800;
  letter-spacing: 0.08em;
  text-transform: uppercase;
}

.schedule-card__heading p {
  margin: 0;
}

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

.schedule-card h3 {
  margin: 2rem 0 0;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: 1.8rem;
  font-weight: 500;
  line-height: 1.1;
}

.schedule-card__dates {
  display: block;
  margin-top: 1rem;
  color: #68776f;
  font-size: 0.78rem;
}

.set-card {
  height: 100%;
  min-height: 11rem;
  padding: 1.6rem;
  border: 1px solid rgb(24 48 41 / 12%);
  border-radius: 1rem;
  background: linear-gradient(135deg, rgb(255 253 247 / 96%), rgb(242 236 221 / 82%));
  box-shadow: 0 1rem 2.5rem rgb(40 62 52 / 8%);
  transition:
    border-color 160ms ease,
    box-shadow 160ms ease,
    transform 160ms ease;
}

.set-card-link {
  display: block;
  height: 100%;
  border-radius: 1rem;
  text-decoration: none;
}

.set-card-link:hover .set-card {
  border-color: rgb(40 92 78 / 35%);
  box-shadow: 0 1.25rem 2.75rem rgb(40 62 52 / 13%);
  transform: translateY(-3px);
}

.set-card-link:focus-visible {
  outline: 3px solid rgb(86 127 112 / 38%);
  outline-offset: 0.25rem;
}

.set-card p {
  margin: 0 0 2.4rem;
  color: #926044;
  font-size: 0.66rem;
  font-weight: 800;
  letter-spacing: 0.13em;
  text-transform: uppercase;
}

.set-card h2 {
  margin: 0;
  color: #183029;
  font-family: Georgia, 'Times New Roman', serif;
  font-size: clamp(1.65rem, 3vw, 2.1rem);
  font-weight: 500;
  line-height: 1.1;
  letter-spacing: -0.035em;
}

.set-card__action {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  margin-top: 1.4rem;
  color: #567064;
  font-size: 0.76rem;
  font-weight: 750;
}

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

  .sets-catalog {
    margin-top: 3.75rem;
  }

  .today-assignments {
    margin-top: 3.75rem;
  }

  .today-assignments__introduction {
    display: grid;
    gap: 1rem;
  }

  .schedules-catalog {
    margin-top: 3.75rem;
  }

  .schedules-catalog__heading {
    display: grid;
    gap: 1rem;
  }

  .set-grid {
    margin-top: 2.25rem;
  }
}
</style>
