<template>
  <div class="pt-3 container">
    <h3 class="text-lg font-medium mb-3 text-black">Employment History</h3>
  </div>
  
  <div class="space-y-2">
    <!-- Iterate Over Employment History -->
    <FieldsToggleContainer
      v-for="(employment, index) in request.doc.employment_history"
      :key="employment.id"
      :title="employment.company || `Employment ${index + 1}`"
    >
      <div class="lg:grid grid-cols-2 lg:gap-2">
          <!-- Company Field -->
          <FieldContainer>
            <StyledInput
              labelText="Company"
              :isMandatory="true"
              infoText="Company"
              inputType="text"
              name="company"
              :id="`company-${employment.id}`"
              v-model="employment.company"
              :isValid="false"
              validationMessage="You can edit the message."
            />
          </FieldContainer>  

          <!-- Country Autocomplete -->
          <FieldContainer>
            <Autocomp
              labelText="Country"
              :isMandatory="true"
              infoText="Country"
              inputType="text"
              name="country"
              :id="`country-${employment.id}`"
              :options="optionCountry"
              v-model="employment.country"
              @input-change="handleCountryChange(index)"
              :isValid="false"
              validationMessage="You can edit the message."
            />
          </FieldContainer>  

          <!-- City Autocomplete -->
          <FieldContainer>
            <Autocomp
              labelText="City"
              :isMandatory="true"
              infoText="City"
              inputType="text"
              name="city"
              :id="`city-${employment.id}`"
              :options="optionCity"
              @update:modelValue="handleCountryChange"
              v-model="employment.city"
              @input-change="handleCityChange(index)" 
              :isValid="false"
              validationMessage="You can edit the message."
            />
          </FieldContainer>

          <!-- Governorate Autocomplete -->
          <FieldContainer>
            <Autocomp
              labelText="Governorate"
              :isMandatory="true"
              infoText="Governorate"
              inputType="text"
              name="governorate"
              :id="`governorate-${employment.id}`"
              :options="optionGovernorate"
              v-model="employment.governorate"
              :isValid="false"
              validationMessage="You can edit the message."
            />
          </FieldContainer>
      </div>
   
      <!-- Add Employment Button From Doctype-->
      <div class="flex justify-end py-2">
        <Button level="danger" @clicked="saveRequest">Add</Button>
      </div>
    </FieldsToggleContainer>

    <!-- Add Employment Button -->
    <div class="flex justify-center py-3">
      <Button level="secondary" @clicked="addEmployment">+ Add Employment History</Button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, reactive, nextTick } from 'vue'
import { createDocumentResource } from 'frappe-ui'
import { useToast } from 'vue-toastification'
import { v4 as uuidv4 } from 'uuid'

// مكونات
import Button from '../../components/button.vue'
import FieldContainer from '../../components/fieldContainer.vue'
import FieldsToggleContainer from '../../components/fieldsToggleContainer.vue'
import StyledInput from '../../components/styledInput.vue'
import Autocomp from '../../components/autocomp.vue'
import { location } from '../../data/useAddressLogic'

// تهيئة Toast
const toast = useToast()

// مورد المستند
const request = createDocumentResource({
  doctype: 'Verification Instructions Request',
  name: 'VIR-2024-26-09-000007',
})

// خيارات الدول
const valueCountry = ref('')
    const valueCity = ref('')
    const valueGovernorate = ref('')

    const selectedCountry = ref('')
    const selectedCity= ref('')

    const optionCountry = computed(() => {
        return location.data.filter(loc => loc.location_type === 'Country').map(loc => ({
            label: loc.location_name,
            value: loc.location_name
        }))
    })

    const optionCity = computed(() => {
        return location.data.filter(loc => loc.location_type === 'City' && loc.parent_location == selectedCountry.value).map(loc => ({
            label: loc.location_name,
            value: loc.location_name
        }))
    })

    const optionGovernorate= computed(() => {
        return location.data.filter(loc => loc.location_type === 'Governorate' && loc.parent_location == selectedCity.value).map(loc => ({
            label: loc.location_name,
            value: loc.location_name
        }))
    })

    const handleCountryChange = (value) => {
        selectedCountry.value = value.value
    }
    const handleCityChange = (value) => {
        selectedCity.value = value.value
    }
// تهيئة employment_history
watch(() => request.doc, (newDoc) => {
  if (newDoc) {
    if (!newDoc.employment_history) {
      // تهيئة employment_history كمصفوفة فارغة إذا لم تكن موجودة
      newDoc.employment_history = []
    }
  }
}, { immediate: true })

// بديل للتهيئة أثناء إعداد الكمبوننت
if (!request.doc || !request.doc.employment_history) {
  if (request.doc) {
    request.doc.employment_history = []
  } else {
    // التعامل مع حالة أن request.doc في البداية null
    // قد تحتاج إلى تعديل بناءً على كيفية عمل createDocumentResource
    request.doc = {
      employment_history: []
    }
  }
}

// إدارة الأقسام المفتوحة
const openSections = reactive({})

// إضافة إدخال توظيف جديد
const addEmployment = () => {
  const newEmployment = {
    id: uuidv4(), // معرف فريد
    company: '',
    name_of_your_employer: '',
    country: '',
    city: '',
    governorate: '',
  }
  request.doc.employment_history.push(newEmployment)
  nextTick(() => {
    openSections[newEmployment.id] = true
  })
}

// حفظ الطلب
const saveRequest = async () => {
  try {
    await request.setValue.submit(request.doc)
    toast.success('Request has been successfully saved!')
  } catch (error) {
    console.error('Failed to save the request:', error)
    toast.error('Failed to save the request.')
  }
}
</script>