<template>
  <div class="p-6 min-h-screen">
    <h1 class="text-3xl font-bold mb-8 text-center text-gray-700">
      {{ isEditMode ? 'Editar Empleado' : 'Crear Empleado' }}
    </h1>

    <form
      @submit.prevent="handleSubmit"
      class="max-w-lg mx-auto p-8 rounded-lg shadow-lg empleado-actual-form"

    >
      <!-- ───────── Nombre ───────── -->
      <div class="mb-6">
        <label
          for="name"
          class="block text-gray-700 font-semibold mb-2"
        >Nombre Completo</label>
        <input
          id="name"
          v-model="form.name"
          type="text"
          required
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: Juan Pérez"
        />
      </div>

      <!-- ───────── Cédula ───────── -->
      <div class="mb-6">
        <label
          for="cedula"
          class="block text-gray-700 font-semibold mb-2"
        >Cédula</label>
        <input
          id="cedula"
          v-model="form.cedula"
          type="number"
          required
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: 123456789"
        />
      </div>

      <!-- ───────── Ubicación ───────── -->
      <div class="mb-6">
        <label
          for="ubicacion"
          class="block text-gray-700 font-semibold mb-2"
        >Ubicación</label>
        <input
          id="ubicacion"
          v-model="form.ubicacion"
          type="text"
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: Oficina Principal"
        />
      </div>

      <!-- ───────── Grupo de estudio ───────── -->
      <div class="mb-6">
        <label
          for="grupo_estudio"
          class="block text-gray-700 font-semibold mb-2"
        >Grupo de Estudio</label>
        <input
          id="grupo_estudio"
          v-model="form.grupo_estudio"
          type="text"
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: Grupo A"
        />
      </div>

      <!-- ───────── Avatar ───────── -->
      <div class="mb-6">
        <label
          for="avatar_url"
          class="block text-gray-700 font-semibold mb-2"
        >URL del Avatar</label>
        <input
          id="avatar_url"
          v-model="form.avatar_url"
          type="url"
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: https://example.com/avatar.png"
        />
      </div>

      <!-- ───────── Teléfono ───────── -->
      <div class="mb-6">
        <label
          for="telefono"
          class="block text-gray-700 font-semibold mb-2"
        >Teléfono</label>
        <input
          id="telefono"
          v-model="form.telefono"
          type="tel"
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: 0991234567"
        />
      </div>

      <!-- ───────── ID CIAT ───────── -->
      <div class="mb-6">
        <label
          for="idciat"
          class="block text-gray-700 font-semibold mb-2"
        >ID CIAT</label>
        <input
          id="idciat"
          v-model="form.idciat"
          type="text"
          class="form-input w-full px-4 py-2 border border-gray-300 rounded-md
                 focus:outline-none"
          placeholder="Ej: CIAT123"
        />
      </div>

      <!-- ───────── Botones ───────── -->
      <div class="flex justify-end">
        <button
          type="button"
          @click="handleCancel"
          class="btn-secondary mr-4 px-6 py-2 text-gray-700 border border-gray-300 rounded-md
                 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400"
        >
          Cancelar
        </button>
        <button
          type="submit"
          class="btn-submit px-6 py-2 text-white font-semibold rounded-md
                 focus:outline-none focus:ring-2 focus:ring-offset-2"
        >
          {{ isEditMode ? 'Actualizar' : 'Crear' }}
        </button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useEmpleadosStore } from '@/stores/useEmpleados.js'
import { useUi } from '@/stores/useUi'; // Corrected UI store import

/* ───── Tipos ───── */
interface EmpleadoForm {
  name: string
  cedula: number | null
  ubicacion: string
  grupo_estudio?: string
  avatar_url?: string
  telefono?: string
  idciat?: string
}

/* ───── helpers ───── */
const defaultForm = (): EmpleadoForm => ({
  name: '',
  cedula: null,
  ubicacion: '.',   // default del schema
  grupo_estudio: '',
  avatar_url: '',
  telefono: '',
  idciat: '',
})

/* ───── Router ───── */
const route  = useRoute()
const router = useRouter()

/* ───── Store ───── */
const empleadosStore         = useEmpleadosStore()
const { currentEmpleado }    = storeToRefs(empleadosStore)
const uiStore = useUi(); // Corrected UI store instantiation

/* ───── State ───── */
const form         = ref<EmpleadoForm>(defaultForm())
const employeeId   = computed(() => route.params.id as string | undefined)
const isEditMode   = computed(() => !!employeeId.value)

/* ───── Lifecycle ───── */
onMounted(async () => {
  if (isEditMode.value && employeeId.value) {
    try {
      await empleadosStore.fetchEmpleadoById(employeeId.value)
      // copiamos solo campos que el form necesita
      form.value = {
        name          : currentEmpleado.value.name       ?? '',
        cedula        : currentEmpleado.value.cedula     ?? null,
        ubicacion     : currentEmpleado.value.ubicacion  ?? '.',
        grupo_estudio : currentEmpleado.value.grupo_estudio ?? '',
        avatar_url    : currentEmpleado.value.avatar_url ?? '',
        telefono      : currentEmpleado.value.telefono   ?? '',
        idciat        : currentEmpleado.value.idciat     ?? '',
      }
    } catch (err) {
      console.error('Error cargando empleado:', err)
    }
  }
})

/* ───── Submit ───── */
const handleSubmit = async () => {
  const payload = { ...form.value, empleado: true }

  try {
    if (isEditMode.value && employeeId.value) {
      await empleadosStore.updateEmpleado(employeeId.value, payload)
    } else {
      await empleadosStore.createEmpleado(payload)
    }
    router.push({ name: 'empleados-index' })
  } catch (error) {
    console.error('Error al guardar empleado:', error)
    // aquí podrías disparar una notificación
  }
}

/* ───── Cancel ───── */
const handleCancel = () => {
  empleadosStore.clearCurrentEmpleado()
  router.go(-1)
}
</script>

<style scoped>
/* --- Validación rápida de inputs requeridos --- */
input:required:invalid {
  border-color: var(--warning-color); /* Using warning color for invalid fields */
}

/* Removing generic input:focus, button:focus as they are too broad */
.empleado-actual-form {
  background-color: var(--table-bg-color-empleados);
}

.form-container { background-color: var(--background-color); } /* Use theme background */
.form-card      { box-shadow: 0 10px 15px -3px rgba(0,0,0,.1),
                            0 4px 6px -2px rgba(0,0,0,.05); }

.form-title   { color: var(--text-color); } /* Use theme text color */
.form-label   { color: var(--text-color); font-weight: 600; } /* Use theme text color */

.form-input   {
  border-color: var(--accent-color-empleados);
  background-color: var(--input-field-bg-color);
  color: var(--text-color);
  transition: border-color .2s, box-shadow .2s;
}
.form-input:focus {
  outline: none;
  border-color: var(--accent-color-empleados); /* Accent color for focus border */
  box-shadow: 0 0 0 2px var(--accent-color-empleados); /* Accent color for focus ring */
}

.btn-submit {
  background-color: var(--accent-color-empleados);
  transition: background-color .2s, filter .2s;
}
.btn-submit:hover {
  filter: brightness(1.1);
}
.btn-submit:focus {
  box-shadow: 0 0 0 2px var(--background-color), 0 0 0 4px var(--accent-color-empleados);
}

.btn-secondary {
  /* Keeping secondary button less prominent, using general theme colors */
  background-color: var(--secondary-color);
  color: var(--text-color); /* Adjust if secondary-color is too dark for default text */
  border: 1px solid var(--secondary-color);
  transition: background-color .2s, filter .2s;
}
.btn-secondary:hover {
  filter: brightness(0.9);
}
.btn-secondary:focus {
  box-shadow: 0 0 0 2px var(--background-color), 0 0 0 4px var(--secondary-color);
}
</style>
