<script setup lang="ts">

import {onMounted, ref} from "vue";
import {Divider, ToggleSwitch, Button} from "primevue";
import {spaceService} from "@/services/space-service";
import {SettingType} from "@/models/enums";
import {useUserStore} from "@/stores/userStore";

const userStore = useUserStore()
const spacePeriodStarts = ref(10)
const spaceSubPeriodStarts = ref(25)

const isNotificationsEnabled = ref(true)
const days = ref([
  {key: 'Mon', isSelected: false},
  {key: 'Tue', isSelected: false},
  {key: 'Wed', isSelected: false},
  {key: 'Thu', isSelected: false},
  {key: 'Fri', isSelected: false},
  {key: 'Sat', isSelected: false},
  {key: 'Sun', isSelected: false}
]);
const selectDay = (day: string) => {
  let dayValue = days.value.find(i => i.key === day)
  if (dayValue) {
    dayValue.isSelected = !dayValue.isSelected
    settingChanged(SettingType.NOTIFICATIONS_DAYS)
  }
}
const selectAllDay = () => {
  if (days.value.filter(i => i.isSelected).length < 7) {
    days.value.forEach(i => i.isSelected = true)
  } else {
    days.value.forEach(i => i.isSelected = false)
  }
}


const fetchData = async () => {
  let settings: Record<string, string>[] = await spaceService.getSettings()
  let periodStartsSetting = settings.find((i) => i.key === "period-start")
  spacePeriodStarts.value = periodStartsSetting ? Number(periodStartsSetting.value) : 5
  let subPeriodStartsSetting = settings.find((i) => i.key === "sub-period-start")
  spaceSubPeriodStarts.value = subPeriodStartsSetting ? Number(subPeriodStartsSetting.value) : 20
  let notificationEnabledSetting = settings.find((i) => i.key === 'notifications-enabled')
  isNotificationsEnabled.value = notificationEnabledSetting ? notificationEnabledSetting.value == '1' : false
  let notificationsDaysSettings = settings.find((i) => i.key === 'notifications-days')
  if (notificationsDaysSettings) {
    notificationsDaysSettings.value.split(',').forEach((element) => {
      days.value.forEach((day) => {
        if (day.key == element) {
          day.isSelected = true
        }
      })
    })
  }
}

const settingChanged = async (setting: SettingType) => {
  let newValue;
  switch (setting) {
    case SettingType.PERIOD_START:
      newValue = spacePeriodStarts.value
      await spaceService.setSetting(SettingType.PERIOD_START, newValue)
      break
    case SettingType.SUB_PERIOD_START:

      newValue = spaceSubPeriodStarts.value
      await spaceService.setSetting(SettingType.SUB_PERIOD_START, newValue)

      break
    case SettingType.NOTIFICATIONS_ENABLED:
      newValue = isNotificationsEnabled.value ? '1' : '0'
      await spaceService.setSetting(SettingType.NOTIFICATIONS_ENABLED, newValue)

      break;
    case SettingType.NOTIFICATIONS_DAYS:
      newValue = Array.isArray(days.value)
          ? days.value.filter(day => day.isSelected).map(day => day.key).join(',')
          : '';

      await spaceService.setSetting(SettingType.NOTIFICATIONS_DAYS, newValue)

      break;
    case SettingType.NOTIFICATIONS_TIME:
      newValue = '19:30'
      await spaceService.setSetting(SettingType.NOTIFICATIONS_TIME, newValue)
  }

}

declare global {
  interface Window {
    google: any;
  }
}

const linkGoogleDrive = () => {
  if (typeof window.google === 'undefined') {
    console.error('Google client not loaded')
    return
  }

  const client = window.google.accounts.oauth2.initCodeClient({
    client_id: import.meta.env.VITE_GOOGLE_CLIENT_ID,
    scope: 'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly',
    ux_mode: 'popup',
    callback: async (response: any) => {
      if (response.code) {
        await userStore.linkGoogleDrive(response.code)
      }
    },
  });
  client.requestCode();
}

onMounted(async () => {
  await fetchData()
})

</script>

<template>
  <div class="flex !pb-4 !w-full">
    <div class="flex flex-col w-full gap-4">
      <div class="flex periods flex-col !w-full">
        <span class="text-sm !pl-2">Space period dates</span>
        <div class="flex card flex-col !w-full justify-between">
          <div class="flex flex-row !w-full  justify-between pl-2 pt-2">
            <span>Space period start</span>
            <select class="custom-select" v-model="spacePeriodStarts"
                    @change="settingChanged(SettingType.PERIOD_START)">
              <option v-for="i in 31">{{ i }}</option>
            </select>
          </div>
          <Divider/>
          <div class="flex flex-row !w-full  justify-between pl-2 pb-2">
            <span>Space sub-period start</span>
            <select class="custom-select" v-model="spaceSubPeriodStarts"
                    @change="settingChanged(SettingType.SUB_PERIOD_START)">
              <option v-for="i in 31">{{ i }}</option>
            </select>
          </div>
        </div>
      </div>
      <div class="flex notifications flex-col !w-full">
        <span class="text-sm !pl-2">Space notifications</span>
        <div class="flex card flex-col !w-full justify-between">
          <div class="flex flex-row !w-full  justify-between px-2 pt-2">
            <span>Notification enabled</span>
            <ToggleSwitch v-model="isNotificationsEnabled" @change="settingChanged(SettingType.NOTIFICATIONS_ENABLED)"/>
          </div>
          <Divider/>
          <div class="flex flex-row !w-full  justify-between px-2 pb-2 items-center">
            <span>Days reminders</span>
            <div class="flex flex-row  items-center gap-2">
              <button
                  @click="isNotificationsEnabled ? selectAllDay() : ''">
                All
              </button>
              <div class="flex gap-1">
                <button v-for="day in days" class="border border-gray-200 rounded-md shadow-sm p-1"
                        @click="isNotificationsEnabled ? selectDay(day.key): ''"
                        :class="isNotificationsEnabled ? day.isSelected ? 'bg-green-100' : '' : 'bg-gray-100'">
                  {{ day.key.substring(0, 1) }}
                </button>
              </div>

            </div>
          </div>
        </div>
      </div>
      <div class="flex backup flex-col !w-full mt-2">
        <span class="text-sm !pl-2">Storage & Backup</span>
        <div class="flex card flex-col !w-full justify-between p-2">
          <div class="flex flex-row !w-full justify-between items-center">
            <div class="flex flex-col">
              <span>Google Drive</span>
              <span class="text-xs text-gray-500" v-if="userStore.user?.isGoogleDriveLinked">Connected</span>
              <span class="text-xs text-gray-500" v-else>Not connected</span>
            </div>
            <Button
                :label="userStore.user?.isGoogleDriveLinked ? 'Reconnect' : 'Connect'"
                :icon="userStore.user?.isGoogleDriveLinked ? 'pi pi-refresh' : 'pi pi-google'"
                :severity="userStore.user?.isGoogleDriveLinked ? 'secondary' : 'primary'"
                size="small"
                @click="linkGoogleDrive"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>