<script setup>
import { date } from 'alga-js'
import { DateTimePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { toast } from 'bulma-toast'

const route = useRoute()
const organizationId = useCookie('logship_organization_id')

const props = defineProps({
  action: String,
  info: Object
})

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  user: props.info?.name || '',
  userId: props.info?.id || '',
  salesRep: '',
  salesRepId: '',
  salesOpportunity: '',
  salesOpportunityId: '',
  activityType: '',
  activityTypeId: '',
  description: '',
  help: '',
  startDate: date.now(''),
  endDate: date.now(''),
  isComplete: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.user = props.info?.name || ''
  form.value.userId = props.info?.id || ''
})

const resetHandler = () => {
  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    user: props.info?.name || '',
    userId: props.info?.id || '',
    salesRep: '',
    salesRepId: '',
    salesOpportunity: '',
    salesOpportunityId: '',
    activityType: '',
    activityTypeId: '',
    description: '',
    help: '',
    startDate: date.now(''),
    endDate: date.now(''),
    isComplete: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}

const showDetailRecordModal = ref(false)
const showAddressModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  resetHandler()
}

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/admin/users/'+route.params.id+'/activity', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          user: item?.AD_User_ID?.identifier || '',
          userId: item?.AD_User_ID?.id || '',
          salesRep: item?.SalesRep_ID?.identifier || '',
          salesRepId: item?.SalesRep_ID?.id || '',
          salesOpportunity: item?.SalesOpportunity?.identifier || '',
          salesOpportunityId: item?.SalesOpportunity?.id || '',
          activityType: item?.ContactActivityType?.identifier || '',
          activityTypeId: item?.ContactActivityType?.id || '',
          description: item?.Description || '',
          help: item?.Comments || '',
          startDate: date.format(item?.StartDate || date.now('')),
          endDate: date.format(item?.EndDate || date.now('')),
          isComplete: item?.IsComplete ?? false,
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  entries.value.splice(index, 1)

  if(entry.id) {
    await $fetch('/api/admin/users/'+entry.id+'/activity', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/admin/users/'+route.params.id+'/activity', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        salesRepId: form.value.salesRepId,
        salesOpportunityId: form.value.salesOpportunityId,
        activityTypeId: form.value.activityTypeId,
        description: form.value.description,
        help: form.value.help,
        startDate: form.value.startDate,
        endDate: form.value.endDate,
        isComplete: form.value.isComplete,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/admin/users/'+route.params.id+'/activity', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        userId: route.params.id,
        salesRepId: form.value.salesRepId,
        salesOpportunityId: form.value.salesOpportunityId,
        activityTypeId: form.value.activityTypeId,
        description: form.value.description,
        help: form.value.help,
        startDate: form.value.startDate,
        endDate: form.value.endDate,
        isComplete: form.value.isComplete,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th class="w-200px">Activity Type</th>
            <th>Description</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th class="w-100px">Active</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 6 : 5" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.activityType }}</td>
            <td>{{ entry.description }}</td>
            <td>{{ entry.startDate }}</td>
            <td>{{ entry.endDate }}</td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.isComplete" class="checkInput" :id="'isComplete_'+index" :checked="entry.isComplete" disabled>
                <label class="checkLabel" :for="'isComplete_'+index">Complete</label>
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                <span @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                  <i class="menu-icon tf-icons ti ti-pencil"></i>
                </span>
                <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                  <i class="menu-icon tf-icons ti ti-trash"></i>
                </span>
              </div>
            </td>
          </tr>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="showDetailRecordModal = true; resetHandler();" class="button">Add Record</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Activity</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody mnh-450px">
            <div class="mb-3 mt-0 px-0.75rem">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns is-desktop">
                <div class="column is-two-thirds">
                  <div class="columns is-desktop">
                    <div class="column is-half">
                      <label class="label d-block">Start Date *</label>
                      <DateTimePicker v-model="form.startDate" :max="form.endDate" />

                      <label class="label d-block mt-2">Activity Type *</label>
                      <select v-model="form.activityTypeId" class="select" :disabled="form.id !== ''">
                        <option value=""></option>
                        <option value="EM">Email</option>
                        <option value="ME">Meeting</option>
                        <option value="PC">Phone call</option>
                        <option value="TA">Task</option>
                      </select>

                      <label class="label d-block mt-2">Sales Opportunity</label>
                      <select v-model="form.salesOpportunityId" class="select">
                        <option value=""></option>
                      </select>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">End Date *</label>
                      <DateTimePicker v-model="form.endDate" :min="form.startDate" :add="14" />

                      <label class="label d-block mt-2">Sales Representative</label>
                      <ClientOnly>
                        <SelectBox v-model="form.salesRepId" :options="getOptions?.['sales_reps']?.records || [{id: form.salesRepId, Name: form.salesRep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'sales_reps')" :loading="loading?.['sales_reps'] ?? true" />
                      </ClientOnly>
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description *</label>
                  <textarea v-model="form.description" class="input"></textarea>

                  <label class="label d-block mt-2">Comments</label>
                  <textarea v-model="form.help" class="input"></textarea>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Tenant/Client</label>
                  <input type="text" v-model="form.client" class="input" readonly />

                  <label class="label d-block mt-2">Organization</label>
                  <input type="text" v-model="form.organization" class="input" readonly />

                  <label class="label d-block mt-2">User</label>
                  <input type="text" v-model="form.user" class="input" readonly />

                  <label class="label d-block mt-2">Status</label>
                  <div class="d-flex flexDirection-column px-0.75rem">
                    <div class="check">
                      <input type="checkbox" v-model="form.isComplete" class="checkInput" id="isComplete" :checked="form.isComplete">
                      <label class="checkLabel" for="isComplete">Complete</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button type="button" class="button" @click="save" :class="(form.description === '' || form.activityTypeId === '' || form.startDate === '' || form.endDate === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>