<template>
  <main>
    <div>
      <button class="btn btn--primary" style="margin-left: 2rem; margin-top: 2rem;" @click="goBack">
        👈 back
      </button>
      <h1 style="text-align: center; font-size: 2.5rem;">
        {{ selectedOrig.municipality }} 🛩 {{ selectedDest.municipality }}
      </h1>
    </div>
    <ul class="schedule-grid">
      <li
        v-for="schedule in schedules"
        :key="schedule.fields.Record_ID"
        class="grid__row"
      >
        <pre>
          {{ schedule.fields.Flight_Number }}
        </pre>
        <div class="grid__field">
          <label> Local Airline </label>
          <div class="field__content">
            {{ schedule.fields.Carrier_Name }}
          </div>
        </div>
        <div class="grid__field">
          <label> Days of the Week </label>
          <div class="field__content">
            <div class="dow-grid">
              <div
                v-for="day in daysList(schedule.fields.Frequency_Convert)"
                :key="day.name"
                :class="['dow-grid__day', 'day--' + day.name]"
              >
                <span> {{ day.name }} </span>
              </div>
            </div>
          </div>
        </div>
        <div class="grid__field">
          <label> Departing </label>
          <div class="field__content">
            {{ schedule.fields.Departure_TimeL }}
          </div>
        </div>
        <div class="grid__field">
          <label> Arriving </label>
          <div class="field__content">
            {{ schedule.fields.Arrival_TimeL }}
          </div>
        </div>
        <div class="grid__field">
          <label> Available Until </label>
          <div class="field__content">
            {{ schedule.fields.Effective_End }}
          </div>
        </div>
        <div class="grid__field">
          <div class="field__content">
            {{ schedule.fields.Price_USD }}
          </div>
          <button class="btn btn--primary" @click="book(schedule)">
            {{ schedule.fields.IsExpedia[0] === 'true' ? 'book it!' : 'see flights' }}
          </button>
        </div>
      </li>
    </ul>
  </main>
</template>

<script>
export default {
  data () {
    return {
      schedules: [],
      startingDate: '',
      selectedSchedule: {},
      selectedDays: [],
      selectedOrig: {},
      selectedDest: {}
    }
  },
  async fetch () {
    // console.log(this.$route.params.o)

    const today = new Date().toLocaleDateString('en-CA')

    // function addDays (date, days) {
    //   const result = new Date(date)
    //   result.setDate(result.getDate() + days)
    //   return result
    // }

    // const tomorrow = addDays(new Date(), 1).toLocaleDateString('en-CA')

    const scheduleFetchFilterFormula = `AND(Is_Current="Yes",Origin_IATA="${this.$route.params.o}",Destination_IATA="${this.$route.params.d}",Effective_End>"${today}",SEARCH("${new Date(this.$route.params.departure).getDay()}",Frequency)>0)`
    // console.log(scheduleFetchFilterFormula)
    const scheduleFetchSort = '&sort[0][field]=DepartureTimeFormatted&sort[0][direction]=asc'

    const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Schedule?filterByFormula=${scheduleFetchFilterFormula}${scheduleFetchSort}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Bearer keyJ2ht64ZSN57AG1'
      }
    })

    const data = await response.json()

    // console.log(data)

    this.schedules = [...data.records]
  },
  computed: {

  },
  created () {
    // console.log(this.$route.path)

    if (this.$route && this.$route.params && this.$route.params.o) {
      this.fetchSingleAirport(this.$route.params.o, true)
    }
    if (this.$route && this.$route.params && this.$route.params.d) {
      this.fetchSingleAirport(this.$route.params.d, false)
    }
  },
  methods: {
    daysList (days) {
      const list = days.split(', ').map((day) => {
        const name = day.toLowerCase().slice(0, -1)

        let num
        switch (name) {
          case 'su':
            num = 0
            break

          case 'mo':
            num = 1
            break

          case 'tu':
            num = 2
            break

          case 'we':
            num = 3
            break

          case 'th':
            num = 4
            break

          case 'fr':
            num = 5
            break

          case 'sa':
            num = 6
            break

          default:
            break
        }
        return {
          name,
          num
        }
      })

      return list.sort(function (a, b) {
        return a.num - b.num
      })
    },
    goBack () {
      this.$router.go(-1)
    },
    book (schedule) {
      if (schedule.fields.IsExpedia[0] === 'true') {
        this.startingDate = new Date()
        this.selectedSchedule = schedule.fields
        this.selectedDays = this.daysList(schedule.fields.Frequency_Convert)
      } else {
        window.open(schedule.fields['BookingLink (from Carriers_Alaska)'][0])
      }
    },
    clearSelectedSchedule () {
      console.log('clear')
      this.startingDate = ''
      this.selectedSchedule = {}
    },
    async fetchSingleAirport (iata, isOrig) {
      const airportFetchFilterFormula =
        isOrig
          ? `AND(Is_Origin=1,{IsCurrent-AsOrigin}="Yes",Airport_IATA="${iata}")`
          : `AND(Is_Destination=1,{IsCurrent-AsDest}="Yes",Airport_IATA="${iata}")`

      const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${airportFetchFilterFormula}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: 'Bearer keyJ2ht64ZSN57AG1'
        }
      })

      const mapData = await response.json()

      const thisAirport = {
        iata: mapData.records[0].fields.Airport_IATA,
        lat: mapData.records[0].fields.Latitude_Deg,
        long: mapData.records[0].fields.Longitude_Deg,
        icon: mapData.records[0].fields.Icon_Url,
        name: mapData.records[0].fields.Airport_Name,
        municipality: mapData.records[0].fields.Municipality,
        type: mapData.records[0].fields.Type,
        search: mapData.records[0].fields.Search_Field
      }

      switch (isOrig) {
        case true:
          this.selectedOrig = { ...thisAirport }
          break

        case false:
          this.selectedDest = { ...thisAirport }
          break

        default:
          break
      }
    }
  }
}
</script>

<style lang="scss">
.schedule-grid {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin: 2rem;
}

.grid__row {
  display: grid;
  grid-template-columns: 2fr 2fr 1fr 1fr 2fr 1fr;
  grid-template-rows: auto;
  gap: 1rem;
  padding: 1rem;
}

@media only screen and (max-width: 768px) {
  .grid__row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto;
  }
}

.grid__row:nth-child(2n) {
  background: #eee;
}

// .grid__field {

// }

label {
  font-size: 0.75rem;
  font-weight: 700;
  color: gray;
  display: block;
}

.field__content {
  font-size: 1.5rem;
}

.dow-grid {
  width: 200px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  gap: 0.5rem;
}

.dow-grid__day {
  font-size: 0.8rem;
  border: 1px solid #ccc !important;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px !important;
  text-transform: capitalize;
}

.day--su {
  grid-column: 1 / span 1;
}

.day--mo {
  grid-column: 2 / span 1;
}

.day--tu {
  grid-column: 3 / span 1;
}

.day--we {
  grid-column: 4 / span 1;
}

.day--th {
  grid-column: 5 / span 1;
}

.day--fr {
  grid-column: 6 / span 1;
}

.day--sa {
  grid-column: 7 / span 1;
}
</style>
