<!-- src/pages/employee/edit.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs & Title -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Employees</li>
          <li>Edit Employee</li>
        </ul>
      </div>

      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mt-4">
        <h1 class="text-3xl font-bold">
          Edit Employee
        </h1>
        <router-link v-if="employeeId" :to="{ name: 'employeeProfile', params: { id: employeeId } }"
          class="btn btn-secondary btn-sm mt-2 sm:mt-0">
          Back to Profile
        </router-link>
      </div>

      <!-- Main Form Card -->
      <div class="bg-neutral rounded-lg p-6 mt-6">
        <form @submit.prevent="onSubmit" class="space-y-6">

          <!-- SECTION 1: General Info -->
          <div>
            <h2 class="text-lg font-bold">General Info</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <!-- First Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">First Name</span></label>
                <input v-model="form.employee_first_name" type="text" placeholder="First Name"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_first_name.$error }" />
                <span v-if="v$.form.employee_first_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_first_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Last Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">Last Name</span></label>
                <input v-model="form.employee_last_name" type="text" placeholder="Last Name"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_last_name.$error }" />
                <span v-if="v$.form.employee_last_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_last_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Phone Number -->
              <div class="form-control">
                <label class="label"><span class="label-text">Phone Number</span></label>
                <input v-model="form.employee_phone_number" @input="acceptNumber" type="text" placeholder="Phone Number"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_phone_number.$error }" />
                <span v-if="v$.form.employee_phone_number.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_phone_number.$errors[0].$message }}
                </span>
              </div>
              <!-- Employee Type -->
              <div class="form-control">
                <label class="label"><span class="label-text">Employee Role</span></label>
                <select v-model="form.employee_type" class="select select-bordered select-sm w-full"
                  :class="{ 'select-error': v$.form.employee_type.$error }">
                  <option disabled :value="0">Select a role</option>
                  <option v-for="employee in employList" :key="employee.value" :value="employee.value">
                    {{ employee.text }}
                  </option>
                </select>
                <span v-if="v$.form.employee_type.$error" class="text-red-500 text-xs mt-1">
                  Role is required.
                </span>
              </div>
            </div>
          </div>

          <!-- SECTION 2: Address -->
          <div>
            <h2 class="text-lg font-bold">Address</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- Street Address -->
              <div class="form-control">
                <label class="label"><span class="label-text">Street Address</span></label>
                <input v-model="form.employee_address" type="text" placeholder="Street Address"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_address.$error }" />
                <span v-if="v$.form.employee_address.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_address.$errors[0].$message }}
                </span>
              </div>
              <!-- Apt, Suite, etc. -->
              <div class="form-control">
                <label class="label"><span class="label-text">Apt, Suite, etc. (Optional)</span></label>
                <input v-model="form.employee_apt" type="text" placeholder="Apt, suite, unit..."
                  class="input input-bordered input-sm w-full" />
              </div>
              <!-- Town -->
              <div class="form-control">
                <label class="label"><span class="label-text">Town</span></label>
                <input v-model="form.employee_town" type="text" placeholder="Town"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_town.$error }" />
                <span v-if="v$.form.employee_town.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_town.$errors[0].$message }}
                </span>
              </div>
              <!-- State -->
              <div class="form-control">
                <label class="label"><span class="label-text">State</span></label>
                <select v-model="form.employee_state" class="select select-bordered select-sm w-full"
                  :class="{ 'select-error': v$.form.employee_state.$error }">
                  <option disabled :value="0">Select a state</option>
                  <option v-for="state in stateList" :key="state.value" :value="state.value">
                    {{ state.text }}
                  </option>
                </select>
                <span v-if="v$.form.employee_state.$error" class="text-red-500 text-xs mt-1">
                  State is required.
                </span>
              </div>
              <!-- Zip Code -->
              <div class="form-control">
                <label class="label"><span class="label-text">Zip Code</span></label>
                <input v-model="form.employee_zip" type="text" placeholder="Zip Code"
                  class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_zip.$error }" />
                <span v-if="v$.form.employee_zip.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.form.employee_zip.$errors[0].$message }}
                </span>
              </div>
            </div>
          </div>

          <!-- SECTION 3: Employment Dates -->
          <div>
            <h2 class="text-lg font-bold">Employment Dates & Details</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div class="form-control">
                <label class="label"><span class="label-text">Birthday</span></label>
                <input v-model="form.employee_birthday" type="date" class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_birthday.$error }" />
                <span v-if="v$.form.employee_birthday.$error" class="text-red-500 text-xs mt-1">Required.</span>
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">Start Date</span></label>
                <input v-model="form.employee_start_date" type="date" class="input input-bordered input-sm w-full"
                  :class="{ 'input-error': v$.form.employee_start_date.$error }" />
                <span v-if="v$.form.employee_start_date.$error" class="text-red-500 text-xs mt-1">Required.</span>
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">End Date (Optional)</span></label>
                <input v-model="form.employee_end_date" type="date" class="input input-bordered input-sm w-full" />
              </div>
            </div>
          </div>

          <!-- SECTION 4: Active Status -->
          <div>
            <h2 class="text-lg font-bold">Employment Status</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="form-control">
              <label class="label cursor-pointer">
                <span class="label-text">Active Employee</span>
                <input v-model="form.active" type="checkbox" class="checkbox checkbox-primary" />
              </label>
            </div>
          </div>

          <!-- SUBMIT BUTTON -->
          <div class="pt-4">
            <button type="submit" class="btn btn-primary btn-sm" :disabled="isSubmitting">
              {{ isSubmitting ? 'Saving...' : 'Save Changes' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { notify } from "@kyvg/vue3-notification"
import { useVuelidate } from '@vuelidate/core'
import { required, minLength } from "@vuelidate/validators"
import { adminService } from '../../services/adminService'
import { queryService } from '../../services/queryService'

interface SelectOption {
  text: string
  value: number
}

const route = useRoute()
const router = useRouter()

// State
const employeeId = ref<string>(route.params.id as string)
const isSubmitting = ref(false)
const stateList = ref<SelectOption[]>([])
const employList = ref<SelectOption[]>([])
const form = reactive({
  employee_first_name: '',
  employee_last_name: '',
  employee_town: '',
  employee_address: '',
  employee_apt: '',
  employee_zip: '',
  employee_birthday: '',
  employee_phone_number: '',
  employee_start_date: '',
  employee_end_date: '',
  employee_type: 0,
  employee_state: 0,
  active: true,
})

// Validation rules
const rules = computed(() => ({
  form: {
    employee_last_name: { required, minLength: minLength(1) },
    employee_first_name: { required, minLength: minLength(1) },
    employee_town: { required, minLength: minLength(1) },
    employee_type: { required },
    employee_zip: { required, minLength: minLength(5) },
    employee_state: { required },
    employee_address: { required },
    employee_birthday: { required },
    employee_phone_number: { required },
    employee_start_date: { required },
  },
}))

const v$ = useVuelidate(rules, { form })

// Methods
function acceptNumber() {
  const x = form.employee_phone_number.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/)
  if (x) {
    form.employee_phone_number = !x[2] ? x[1] : `(${x[1]}) ${x[2]}${x[3] ? `-${x[3]}` : ''}`
  }
}

async function getEmployee(userId: string) {
  try {
    const response = await adminService.employees.getById(Number(userId))
    const data = response.data as any
    // Populate form with data
    form.employee_first_name = data.employee_first_name || ''
    form.employee_last_name = data.employee_last_name || ''
    form.employee_town = data.employee_town || ''
    form.employee_address = data.employee_address || ''
    form.employee_apt = data.employee_apt || ''
    form.employee_zip = data.employee_zip || ''
    form.employee_birthday = data.employee_birthday || ''
    form.employee_phone_number = data.employee_phone_number || ''
    form.employee_start_date = data.employee_start_date || ''
    form.employee_end_date = data.employee_end_date || ''
    form.employee_type = data.employee_type || 0
    form.employee_state = data.employee_state || 0
    form.active = data.active === 1
  } catch (error) {
    console.error('Failed to fetch employee:', error)
  }
}

async function getEmployeeTypeList() {
  try {
    const response = await queryService.getEmployeeTypes()
    const data = response.data as any
    if (data && data.employee_types) {
      employList.value = data.employee_types
    } else if (Array.isArray(data)) {
      employList.value = data
    }
  } catch (error) {
    console.error('Failed to fetch employee types:', error)
  }
}

async function getStatesList() {
  try {
    const response = await queryService.getStates()
    const data = response.data as any
    if (data && data.states) {
      stateList.value = data.states
    } else if (Array.isArray(data)) {
      stateList.value = data
    }
  } catch (error) {
    console.error('Failed to fetch states:', error)
  }
}

async function onSubmit() {
  const isValid = await v$.value.$validate()
  if (!isValid) {
    notify({ title: "Validation Error", text: "Please fill out all required fields correctly.", type: "error" })
    return
  }

  if (isSubmitting.value) return
  isSubmitting.value = true

  try {
    const apiPayload = { ...form, active: form.active ? 1 : 0 }
    const response = await adminService.employees.update(Number(employeeId.value), apiPayload)
    if ((response.data as any).ok) {
      router.push({ name: "employeeProfile", params: { id: employeeId.value } })
    } else {
      notify({ title: "Error", text: (response.data as any).error || "Failed to update employee", type: "error" })
    }
  } catch (error) {
    notify({ title: "Error", text: "Failed to update employee", type: "error" })
  } finally {
    isSubmitting.value = false
  }
}

// Lifecycle
onMounted(() => {
  getEmployeeTypeList()
  getStatesList()
  getEmployee(employeeId.value)
})
</script>
