<script setup lang="ts">
import type { ScheduleDetail } from '@/stores/schedules'

type ScheduleDay = ScheduleDetail['days'][number]

const props = defineProps<{
  completionErrors: Record<number, string>
  days: ScheduleDay[]
  mode: 'remaining' | 'completed'
  pendingAssignmentIds: number[]
  today: string
}>()

const emit = defineEmits<{
  setCompleted: [assignmentId: number, completed: boolean]
}>()

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

function formatCompletionTime(value: string): string {
  return new Intl.DateTimeFormat('en', {
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(new Date(value))
}

function dayAssignmentSummary(day: ScheduleDay): string {
  if (day.assignments.length === 0) {
    return '0 assigned'
  }

  const assignmentLabel = props.mode === 'remaining' ? 'remaining' : 'completed'

  return `${day.assignments.length} ${assignmentLabel}`
}

function isOverdue(day: ScheduleDay): boolean {
  return props.mode === 'remaining' && day.assignments.length > 0 && day.date < props.today
}

function isPending(assignmentId: number): boolean {
  return props.pendingAssignmentIds.includes(assignmentId)
}
</script>

<template>
  <ol
    class="schedule-days"
    :class="{ 'schedule-days--completed': mode === 'completed' }"
    :aria-label="
      mode === 'remaining'
        ? 'Remaining assignments by scheduled date'
        : 'Completed assignments by scheduled date'
    "
  >
    <li
      v-for="day in 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 class="schedule-day__summary">
          <span v-if="isOverdue(day)" class="overdue-label">Overdue</span>
          <span>{{ dayAssignmentSummary(day) }}</span>
        </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"
          :class="{ 'is-completed': assignment.completedAt !== null }"
          :data-schedule-assignment="assignment.id"
        >
          <div class="assignment-description">
            <span class="assignment-path">
              {{ assignment.element.path.join(' / ') }}
            </span>
            <span class="assignment-kind">{{ assignment.element.kind }}</span>
          </div>
          <div class="assignment-completion">
            <p v-if="assignment.completedAt !== null" class="assignment-completion__status">
              Completed
              <time :datetime="assignment.completedAt">
                {{ formatCompletionTime(assignment.completedAt) }}
              </time>
            </p>
            <p v-else class="assignment-completion__status">Not completed</p>
            <button
              type="button"
              class="assignment-completion-button"
              :aria-label="
                assignment.completedAt === null
                  ? `Mark ${assignment.element.path.join(' / ')} complete`
                  : `Reopen ${assignment.element.path.join(' / ')}`
              "
              :disabled="isPending(assignment.id)"
              @click="emit('setCompleted', assignment.id, assignment.completedAt === null)"
            >
              {{
                isPending(assignment.id)
                  ? 'Saving...'
                  : assignment.completedAt === null
                    ? 'Mark complete'
                    : 'Reopen'
              }}
            </button>
            <p
              v-if="completionErrors[assignment.id] !== undefined"
              class="assignment-completion__error"
              role="alert"
            >
              {{ completionErrors[assignment.id] }}
            </p>
          </div>
        </li>
      </ul>
    </li>
  </ol>
</template>

<style scoped>
.schedule-days {
  display: grid;
  gap: 1rem;
  margin: 1.4rem 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-days--completed .schedule-day {
  background: rgb(248 248 241 / 78%);
  box-shadow: none;
}

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

.schedule-days--completed .schedule-day__header {
  background: rgb(220 235 224 / 34%);
}

.schedule-day__summary {
  display: inline-flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0.55rem;
}

.overdue-label {
  padding: 0.25rem 0.45rem;
  border-radius: 999px;
  color: #8f382d;
  background: #f4dcd5;
  font-size: 0.62rem;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.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: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: start;
  gap: 1rem;
  padding: 1rem;
}

.assignment-list li.is-completed {
  background: rgb(220 235 224 / 24%);
}

.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-description {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  min-width: 0;
}

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

.assignment-completion {
  display: grid;
  justify-items: end;
  gap: 0.55rem;
  min-width: 12rem;
}

.assignment-completion__status,
.assignment-completion__error {
  margin: 0;
  font-size: 0.74rem;
  font-weight: 700;
  text-align: right;
}

.assignment-completion__status {
  color: #5e7067;
}

.assignment-completion__status time {
  display: block;
  margin-top: 0.2rem;
  color: #344e45;
}

.assignment-completion__error {
  max-width: 14rem;
  color: #9b3f32;
}

.assignment-completion-button {
  min-height: 2.4rem;
  padding: 0.55rem 0.8rem;
  border: 1px solid rgb(24 58 49 / 28%);
  border-radius: 0.65rem;
  color: #183a31;
  background: #fffdf7;
  font-size: 0.75rem;
  font-weight: 800;
  cursor: pointer;
}

.is-completed .assignment-completion-button {
  color: #5e7067;
  background: transparent;
}

.assignment-completion-button:hover:not(:disabled) {
  border-color: #285c4e;
  background: #f9f5e9;
}

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

@media (max-width: 37.5rem) {
  .schedule-day__header {
    align-items: flex-start;
  }

  .schedule-day__summary {
    flex-wrap: wrap;
  }

  .assignment-list li {
    grid-template-columns: 1fr;
  }

  .assignment-description {
    align-items: flex-start;
  }

  .assignment-completion {
    justify-items: start;
    min-width: 0;
  }

  .assignment-completion__status,
  .assignment-completion__error {
    text-align: left;
  }
}
</style>
