<script setup>
import { ref, defineProps } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { parseError, getError, clearErrors} from "@/components/request/HandleGlobalError.vue";
import ShowErrorField from "@/components/global/ShowErrorField.vue";
import { selected_date, onChangeCall, selected_department_id} from "@/views/dashboards/departmentDashboard/modules/daily-report/DepartmentDailyReportObject.vue";
import Swal from "sweetalert2";

const props = defineProps({
    department_id: Number,
    date: String,
});

// Define the random unique id
const uniqueId = Math.random().toString(36).substr(2, 9);

// Define the form fields
const water_usage = ref(0);
const water_usage_morning = ref(0);
const notes = ref(null);
const filled_by = ref(null);
const created_at = ref(null);
const id = ref(null);
const message = ref('');
const yesterday = ref({
    date: new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0],
    water_usage: 0,
    water_usage_morning: 0,
    notes: null,
    filled_by: null,
    created_at: null,
    id: null
});

const onFormSubmit = async (event) => {
    event.preventDefault();
    console.log('Form submitted with values:', water_usage.value, water_usage_morning.value, notes.value, filled_by.value, created_at.value, id.value);
    SessionUser.objects.department_daily_reports.set.water_usage_morning(id.value, parseInt(water_usage_morning.value))
        .then(() => {
            SessionUser.objects.department_daily_reports.set.water_usage(id.value, parseInt(water_usage.value))
                .then((response) => {
                  if (response.data.data.id === id.value) {
                    message.value = 'Rapporten er gemt ' + new Date().toLocaleTimeString();
                    Swal.fire(
                        'Rapporten er gemt',
                        'Rapporten er gemt i systemet',
                        'success'
                    )
                    clearErrors();
                  } else {
                    catchError('Der skete en fejl', uniqueId);
                  }
                })
                .catch(error => {
                    catchError(error, uniqueId);
                });
        }).catch(error => {
        catchError(error, uniqueId);
    })
};


const catchError = (error, uniqueId) => {
    message.value = null;
    parseError(error, uniqueId);
};

const createDailyReport = async () => {
    try {
        await SessionUser.objects.department_daily_reports.add(props.department_id, 0, 0, null, selected_date.value)
            .then(response => {
                console.log(response.data.data);
            });
    } catch (error) {
        parseError(error, 'department_daily_reports');
    }
};

const getYesterdaysReport = async () => {
    try {
        await SessionUser.objects.department_daily_reports.functions.getDepartmentDailyReport(
            selected_department_id.value,
            yesterday.value.date
        )
            .then(response => {
                yesterday.value.water_usage = parseInt(response.data.data.water_usage);
                yesterday.value.notes = response.data.data.notes ? response.data.data.notes : '';
                yesterday.value.filled_by = response.data.data.filled_by ? response.data.data.filled_by : null;
                yesterday.value.created_at = response.data.data.created_at;
                yesterday.value.id = response.data.data.id;
            });
    } catch (error) {
        parseError(error, uniqueId + '_yesterday');
    }
};

const getDailyReport = async () => {
  try {
    await SessionUser.objects.department_daily_reports.functions.getDepartmentDailyReport(
        selected_department_id.value,
        selected_date.value
    )
      .then(response => {
        // Check if the date is today
        const created_at_val = new Date(response.data.data.created_at);
        const today = new Date();
        if (created_at_val.toDateString() === (selected_date.value ? new Date(selected_date.value) : today).toDateString()) {
          // The daily report is today
          // So we can set the values
          water_usage.value = parseInt(response.data.data.water_usage);
          notes.value = response.data.data.notes ? response.data.data.notes : '';
          filled_by.value = response.data.data.filled_by ? response.data.data.filled_by : null;
          created_at.value = response.data.data.created_at;
          id.value = response.data.data.id;
        } else {
          // If the selected date is today, then we need to create a new daily report
          if (SessionUser.functions.date.isToday(selected_date.value)) {
            createDailyReport();
            getDailyReport();
          }
        }
      });
  } catch (error) {
    // Check if the error is a 404 (Then we need to create a new daily report)
    if (error.response.status === 404 && SessionUser.functions.date.isToday(selected_date)) {
      // Create a new daily report, and then rerun the getDailyReport function
      // This is done to prevent an infinite loop of creating daily reports
      await createDailyReport().then(() => {
        // Rerun the getDailyReport function, if the day today is selected
        getDailyReport()
      });
    } else {
      parseError(error, uniqueId);
    }
  }
};



const resetData = () => {
  water_usage.value = 0;
  notes.value = null;
  filled_by.value = null;
  created_at.value = null;
  id.value = null;
  message.value = null;
  // Yesterday
  yesterday.value.water_usage = 0;
  yesterday.value.notes = null;
  yesterday.value.filled_by = null;
  yesterday.value.created_at = null;
  yesterday.value.id = null;
  clearErrors();
};

// Get the daily report
getDailyReport();
getYesterdaysReport();

onChangeCall(() => {
  resetData();
  getDailyReport();
  getYesterdaysReport();
});

</script>

<template>
  <form @submit="onFormSubmit">
    <div class="columns is-multiline">
      <div class="column is-12">
        <div class="is-pulled-right">
          <!-- Warnings -->
        </div>
        <h1 class="title">{{ SessionUser.functions.date.isToday(selected_date) ? 'Dagens rapport' : 'Tidligere rapport' }}</h1>
        <h4 class="subtitle is-5">{{ SessionUser.functions.date.toWords(selected_date) }}</h4>
        <ShowErrorField :error="uniqueId" />
      </div>
      <div class="column">
        <div class="field">
          <label class="label">{{SessionUser.objects.department_daily_reports.columns.water_usage.label}}</label>
          <div class="control">
            <input
                class="input"
                type="number"
                v-model="water_usage"
                v-bind:placeholder="yesterday.water_usage ? yesterday.water_usage + ' ( I går )' : '0'"
                required
            >
          </div>
        </div>
      </div>
    </div>
    <div class="field">
      <div class="control">
        <button class="button is-dark is-fullwidth" type="submit" v-if="id !== null" @click="onFormSubmit">
          <!-- A daily report already exists, so we update it -->
          Opdater {{ SessionUser.functions.date.isToday(selected_date) ? 'dagens' : '' }} rapport {{ SessionUser.functions.date.isToday(selected_date) ? '' :  'for ' + SessionUser.functions.date.toWords(selected_date) }}
        </button>
      </div>
      <!-- Show the success message -->
      <div class="control mt-2">
        <div class="message is-success" v-if="message">
          <div class="message-body">
            {{ message }}
          </div>
        </div>
      </div>
    </div>
  </form>
</template>

<style scoped>

</style>