<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">
    <FieldsToggleContainer
      v-for="(employment, index) in request.doc.employment_history"
      :key="employment.id"
      :title="'Company ' + (index + 1)"
    >
      <div class="lg:grid grid-cols-2 lg:gap-2">
        <FieldContainer>
          <StyledInput
            labelText="Company"
            isMandatory="true"
            infoText="Company"
            inputType="text"
            :name="`company-${employment.id}`"
            :id="`company-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.company"
          />
        </FieldContainer>
        <FieldContainer>
          <StyledInput
            labelText="Name of Your Employer"
            isMandatory="true"
            infoText="Name of Your Employer"
            inputType="text"
            :name="`name_of_your_employer-${employment.id}`"
            :id="`name_of_your_employer-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.name_of_your_employer"
          />
        </FieldContainer>
        <!-- Repeat similar structure for other fields -->

        <FieldContainer>
          <CheckBox 
            :name="`continuous-${employment.id}`" 
            :id="`continuous-${employment.id}`" 
            @input-change="value => handleInput(employment.id, 'continuous', value)"
            v-model="employment.continuous"
          >
            Continuous
          </CheckBox>
        </FieldContainer>

        <FieldContainer>
          <Autocomp
            labelText="Country"
            isMandatory="true"
            infoText="Country"
            inputType="text"
            :name="`country-${employment.id}`"
            :id="`country-${employment.id}`"
            :options="optionCountry"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.country"
          />
        </FieldContainer>
        <!-- Continue updating all other fields similarly -->

        <FieldContainer>
          <StyledInput 
            id="from_date" 
            :name="`from_date-${employment.id}`" 
            labelText="From" 
            isMandatory="true" 
            infoText="From Date" 
            inputType="date" 
            @input-change="value => handleInput(employment.id, 'from_date', value)" 
            v-model="employment.from_date"
          />
        </FieldContainer>
        <FieldContainer>
          <StyledInput 
            id="to_date" 
            :name="`to_date-${employment.id}`" 
            labelText="To" 
            isMandatory="true" 
            infoText="To Date" 
            inputType="date" 
            @input-change="value => handleInput(employment.id, 'to_date', value)" 
            v-model="employment.to_date"
          />
        </FieldContainer>

        <!-- Phone Field -->
        <FieldContainer>
          <StyledInput
            labelText="Phone"
            isMandatory="true"
            infoText="+999-77885951"
            inputType="text"
            :name="`phone-${employment.id}`"
            :id="`phone-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.phone"
          />
        </FieldContainer>

        <!-- Type of Employment -->
        <FieldContainer>
          <Select 
            :id="`type_of_employment-${employment.id}`" 
            :name="`type_of_employment-${employment.id}`"  
            labelText="Type of Employment" 
            isMandatory="true" 
            infoText="Type of Employment"   
            :options="optionsTypeEmployment"
            @input-change="value => handleInput(employment.id, 'type_of_employment', value)" 
            v-model="employment.type_of_employment"
          />
        </FieldContainer>

        <!-- Extension -->
        <FieldContainer>
          <StyledInput
            labelText="Extension"
            isMandatory="true"
            infoText="Extension"
            inputType="text"
            :name="`ext-${employment.id}`"
            :id="`ext-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.ext"
          />
        </FieldContainer>      

        <!-- Permissions and Flags -->
        <FieldContainer>
          <CheckBox 
            :name="`do_we_have_permission_to_contact_this_current_employer-${employment.id}`" 
            :id="`do_we_have_permission_to_contact_this_current_employer-${employment.id}`" 
            @input-change="value => handleInput(employment.id, 'do_we_have_permission_to_contact_this_current_employer', value)"
            v-model="employment.do_we_have_permission_to_contact_this_current_employer"
          >
            Do we have permission to contact this current employer?
          </CheckBox>
        </FieldContainer>
        <!-- Repeat for other CheckBoxes -->

        <!-- Different Company Names -->
        <FieldContainer>
          <StyledInput
            labelText="Different Company Names"
            isMandatory="false"
            infoText="Different Company Names"
            inputType="text"
            :name="`different_company_names-${employment.id}`"
            :id="`different_company_names-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.different_company_names"
          />
        </FieldContainer>  

        <!-- Last Position -->
        <FieldContainer>
          <StyledInput
            labelText="Name of the Last Position You Held"
            isMandatory="true"
            infoText="Name of the Last Position You Held"
            inputType="text"
            :name="`name_of_the_last_position_you_held-${employment.id}`"
            :id="`name_of_the_last_position_you_held-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.name_of_the_last_position_you_held"
          />
        </FieldContainer> 

        <!-- Nickname -->
        <FieldContainer>
          <CheckBox 
            :name="`you_have_a_nickname-${employment.id}`" 
            :id="`you_have_a_nickname-${employment.id}`" 
            @input-change="value => handleInput(employment.id, 'you_have_a_nicknamecx', value)"
            v-model="employment.you_have_a_nicknamecx"
          >
            You have a nickname?
          </CheckBox>
        </FieldContainer> 

        <FieldContainer v-if="employment.you_have_a_nicknamecx">
          <StyledInput
            labelText="Nickname"
            isMandatory="false"
            infoText="Nickname"
            inputType="text"
            :name="`nickname-${employment.id}`"
            :id="`nickname-${employment.id}`"
            :isValid="employment.isValid"
            :validationMessage="employment.validationMessage"
            v-model="employment.nickname"
          />
        </FieldContainer>         
      </div>  
      <FileUpload  
        :name="`file-${employment.id}`"
        :id="`file-${employment.id}`"
      />
      <Button level="danger" @clicked="() => confirmRemove(employment.id)">
        Remove
      </Button>
      <!-- <Button level="danger" @clicked="() => saveRequest(employment.id)">
        Add 
      </Button>  -->
    </FieldsToggleContainer>
    <div class="flex justify-center py-3">
      <Button level="secondary" @clicked="addEmployment">+ Add Employment History</Button>
    </div>
  </div>
</template>

<script setup>
import Button from '../../components/button.vue';
import CheckBox from '../../components/checkBox.vue';
import FieldContainer from '../../components/fieldContainer.vue';
import FieldsToggleContainer from '../../components/fieldsToggleContainer.vue';
import FileUpload from '../../components/fileUpload.vue';
import Select from '../../components/select.vue';
import StyledInput from '../../components/styledInput.vue';
import Autocomp from '../../components/autocomp.vue';
import { ref, computed, watch, reactive, nextTick } from 'vue';
import { createDocumentResource } from 'frappe-ui';
import { location } from '../../data/useAddressLogic';
// import { v4 as uuidv4 } from 'uuid'; // Ensure you have installed uuid: npm install uuid

const optionsTypeEmployment = [
  { value: "Full-Time", label: "Full-Time" },
  { value: "Part-Time", label: "Part-Time" },
  { value: "Contract", label: "Contract" },
  { value: "Internship", label: "Internship" },
];

const request = createDocumentResource({
  doctype: 'Verification Instructions Request',
  name: 'VIR-2024-26-09-000007',
});

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

const getOptionCity = (country) => {
  if (!country) return [];
  return location.data
    .filter(loc => loc.location_type === 'City' && loc.parent_location === country)
    .map(loc => ({
      label: loc.location_name,
      value: loc.location_name
    }));
};

const getOptionGovernorate = (city) => {
  if (!city) return [];
  return location.data
    .filter(loc => loc.location_type === 'Governorate' && loc.parent_location === city)
    .map(loc => ({
      label: loc.location_name,
      value: loc.location_name
    }));
};

watch(() => request.doc, (newDoc) => {
  if (newDoc && !newDoc.employment_history) {
    newDoc.employment_history = [];
  }
}, { immediate: true });

const openSections = reactive({});

const toggleSection = (id) => {
  openSections[id] = !openSections[id];
};

const isOpen = (id) => {
  return openSections[id];
};

const addEmployment = () => {
  const newEmployment = {
    // id: uuidv4(),
    company: '',
    name_of_your_employer: '',
    type_of_employment: '',
    continuous: false,
    country: '',
    city: '',
    governorate: '',
    from_date: '',
    to_date: '',
    phone: '',
    ext: '',
    do_we_have_permission_to_contact_this_current_employer: false,
    issuing_salary: false,
    activity_has_stopped: false,
    the_company_has_different_names: false, 
    different_company_names: '',
    name_of_the_last_position_you_held: '',
    you_have_a_nicknamecx: false,
    nickname: '',
    isValid: true,
    validationMessage: ''
  };
  request.doc.employment_history.push(newEmployment);
  nextTick(() => {
    openSections[newEmployment.id] = true;
  });
};

const confirmRemove = (id) => {
  if (confirm('Are you sure you want to delete this employment record?')) {
    removeEmployment(id);
  }
};

const removeEmployment = (id) => {
  const index = request.doc.employment_history.findIndex(emp => emp.id === id);
  if (index !== -1) {
    request.doc.employment_history.splice(index, 1);
    delete openSections[id];
  }
};

const handleInput = (id, field, value) => {
  const employment = request.doc.employment_history.find(emp => emp.id === id);
  if (employment) {
    employment[field] = value;
    validateField(employment, field);
  }
};

const validateField = (employment, field) => {
  switch(field) {
    case 'company':
    case 'name_of_your_employer':
    case 'type_of_employment':
    case 'country':
    case 'city':
    case 'governorate':
    case 'from_date':
    case 'phone':
    case 'ext':
    case 'name_of_the_last_position_you_held':
      if (!employment[field] || (typeof employment[field] === 'string' && !employment[field].trim())) {
        employment.isValid = false;
        employment.validationMessage = `${field.replace(/_/g, ' ')} is required.`;
      } else {
        employment.isValid = true;
        employment.validationMessage = '';
      }
      break;
    // Add more cases as needed for other fields
    default:
      break;
  }
};

const saveRequest = async () => {
  try {
    await request.setValue.submit({
      employment_history: request.doc.employment_history,
    });
    toast.success('Request has been successfully saved!');
  } catch (error) {
    if (!errors.global) {
      errors.global = [];
    }
    errors.global.push(`An error occurred while saving the request: ${error.message}`);
  }
};

// Props
const props = defineProps({
  stepData: {
    type: Object,
    required: true,
  },
});
</script>