<script setup lang="ts">
import {onMounted, ref, useTemplateRef} from "vue";
import {useAuditLog} from "ucsd-its-frontend";
import {useAppStore} from "../../stores/app";
import {Audit} from "ucsd-its-frontend";
import {useToast} from 'vue-toast-notification';
import {useTheme} from "vuetify";
import {useUcsdAppUtils} from "ucsd-its-frontend";
import 'vue-toast-notification/dist/theme-bootstrap.css';
import {ChangeHistory} from "ucsd-its-frontend";
import {useItsAppStore} from "ucsd-its-frontend";
import {AuditTimeLine} from "ucsd-its-frontend";
import {useItsAuthStore} from "ucsd-its-frontend";

const auditLog = useAuditLog()
const appStore = useAppStore()
const $toast = useToast()
const theme = useTheme()
const appUtils = useUcsdAppUtils()
const itsAppStore = useItsAppStore()
const itsAuthStore = useItsAuthStore()

interface SimpleFormData {
  id: number,
  name: string,
  item: string | null,
  paid: boolean,
}

let auditTimeLine = [] as AuditTimeLine[]
const loadingTimeLine = ref(true)
const formDataList = ref([] as SimpleFormData[]);
const formData = ref({} as SimpleFormData)
const items = ref(['Item 1', 'Item 2', 'Item 3', 'Item 4'])
const loading = ref(false)
const formRef = useTemplateRef('form')
const nameRules = [
  (v: any) => !!v || 'Name is required',
  (v: any) => (v && v.length <= 10) || 'Name must be 10 characters or less',
]

const showAuditTimeline = () => {
  loadingTimeLine.value = true;
  let detailKey = 'simple-form-' + formData.value.id;
  const audits = itsAppStore.getAuditQueue(detailKey);
  auditTimeLine = auditLog.mapAuditToTimeLine(audits);
  loadingTimeLine.value = false;
}

const userAudit = () => {
  loadingTimeLine.value = true;
  const audits = itsAppStore.getAuditQueue(undefined, itsAuthStore.getUserEmail());
  auditTimeLine = auditLog.mapAuditToTimeLine(audits);
  loadingTimeLine.value = false;
}

onMounted(() => {
  //You can await here if data is loaded via API
  itsAppStore.resetAuditQueue()
  auditLog.trackChanges(formData.value, false)
})

const updateExample = () => {
  const auditRecord: Audit = appStore.getAuditRecord(); //Audit application source identifier
  auditRecord.event = 'Existing Record Updated';
  auditRecord.eventIcon = 'mdi-account-edit-outline'; //Change the icon based on description
  auditLog.commitChanges(formData.value, auditRecord, 'simple-form-' + formData.value.id, 'update', []);
}

const newExample = () => {
  const auditRecord: Audit = appStore.getAuditRecord(); //Audit application source identifier
  auditRecord.event = 'New Record created';
  auditRecord.eventIcon = 'mdi-account-plus-outline'; //Change the icon based on description
  auditRecord.eventColor = 'success'
  auditLog.commitChanges(formData.value, auditRecord, 'simple-form-' + formData.value.id, 'new', ['id', 'name']);
}

const deleteExample = () => {
  const auditRecord: Audit = appStore.getAuditRecord(); //Audit application source identifier
  auditRecord.event = 'Record deleted';
  auditRecord.eventIcon = 'mdi-account-minus-outline'; //Change the icon based on description
  auditRecord.eventColor = 'error'
  auditLog.commitChanges(formData.value, auditRecord, 'simple-form-' + formData.value.id, 'delete', []);
}

const addRecord = () => {
  const data = appUtils.deepClone(formData.value) as SimpleFormData;
  data.id = formDataList.value.length + 1;
  data.paid = !(data.paid === null || !data.paid);
  formData.value.id = data.id;
  formDataList.value.push(data)
  newExample();
}

const updateRecord = () => {
  const data = appUtils.deepClone(formData.value) as SimpleFormData;
  formDataList.value.forEach((item, index) => {
    if (item.id === data.id) {
      formDataList.value[index] = data;
    }
  })
  updateExample();
}

const deleteRecord = () => {
  formDataList.value = formDataList.value.filter(item => item.id !== formData.value.id)
  deleteExample();
  formData.value = {
    id: 0,
    name: '',
    item: null,
    paid: false,
  }
  resetValidation();
  $toast.success('Record deleted successfully')
}


const validate = async () => {
  // @ts-ignore
  const {valid} = await formRef.value?.validate()
  if (valid) {
    loading.value = true;
    await appStore.simulateAxiosCall({message: 'Success'}, 1000, false).then(response => {
      if (formData.value.id > 0) {
        updateRecord()
      } else {
        addRecord()
      }
      $toast.success('Data saved successfully', {position: 'top-right'})
    }).catch(error => {
      $toast.error('Failed to save data ' + error.message, {position: 'top-right'})
    })
    loading.value = false;
  }
}

const reset = () => {
  // @ts-ignore
  formRef.value?.reset()
  formData.value = {
    id: 0,
    name: '',
    item: null,
    paid: false,
  }
}


const resetValidation = () => {
  // @ts-ignore
  formRef.value?.resetValidation()
}


</script>

<template>
  <v-container>
    <v-row justify="center" class="ma-2">
      <v-col cols="auto">
        <v-card class="rounded-xl pa-4"
                :class="`bg-grey-${theme.current.value.dark ? 'darken' : 'lighten'}-4`">
          <v-card-title>
            <v-row>
              <v-col cols="2">
                <v-btn class="text-none" variant="plain" size="large" prepend-icon="mdi-history"
                       @click.stop="showAuditTimeline">
                  <change-history :loading-history="loadingTimeLine" :audit-time-line="auditTimeLine"/>
                </v-btn>
              </v-col>
              <v-col cols="8"><h3 class="text-center">Simple Form</h3></v-col>
              <v-col cols="2" class="text-right text-body-1">
                ID: {{ formData.id }}
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-item>
            <v-form ref="form">
              <v-text-field
                  v-model="formData.name"
                  :counter="10"
                  label="Name"
                  required
                  :rules="nameRules"
              />

              <v-select
                  v-model="formData.item"
                  :items="items"
                  label="Item"
                  required
                  :rules="[v => !!v || 'Item is required']"
              />

              <v-checkbox
                  hide-details
                  v-model="formData.paid"
                  label="Paid?"
              />

              <v-progress-linear
                  v-if="loading"
                  class="mb-4"
                  color="light-green-darken-4"
                  height="10"
                  indeterminate
                  striped
              ></v-progress-linear>

              <div class="d-flex flex-column mx-auto" style="width: 70%">
                <v-btn
                    block
                    class="mt-4"
                    color="success"
                    @click="validate"
                >
                  Validate and Save
                </v-btn>

                <v-btn
                    block
                    class="mt-4"
                    color="error"
                    @click="reset"
                >
                  Reset Form
                </v-btn>

                <v-btn
                    block
                    class="mt-4"
                    color="success"
                    @click="reset"
                >
                  New Record
                </v-btn>

                <v-btn v-if="formData.id > 0"
                       block
                       class="mt-4"
                       color="secondary"
                       @click="deleteRecord"
                >
                  Delete
                </v-btn>
                <v-btn class="mt-4" color="secondary" prepend-icon="mdi-history" @click.stop="userAudit" block> User
                  Audit
                  <change-history :loading-history="loadingTimeLine" :audit-time-line="auditTimeLine"/>
                </v-btn>
              </div>

            </v-form>
          </v-card-item>
        </v-card>
      </v-col>
      <v-col cols="auto">
        <v-table
            class="mt-10"
            height="300px"
            fixed-header
        >
          <thead>
          <tr>
            <th class="text-left">
              ID
            </th>
            <th class="text-left">
              Name
            </th>
            <th class="text-left">
              Item
            </th>
            <th class="text-left">
              Paid
            </th>
          </tr>
          </thead>
          <tbody>
          <tr
              v-for="item in formDataList"
              :key="item.id"
              class="cursor-pointer"
              @click="formData = item"
          >
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.item }}</td>
            <td>{{ item.paid }}</td>
          </tr>
          </tbody>
        </v-table>
      </v-col>
    </v-row>
  </v-container>
</template>
<style scoped>

</style>
