<template>
  <div class="postulantes-container">

    <div class="header">
      <div>
        <h2 class="page-title">Gestión de Postulantes</h2>
        <p class="page-subtitle">Administra los usuarios registrados</p>
      </div>

      <a-input-search
        v-model:value="search"
        placeholder="Buscar por nombre, email o DNI"
        style="width: 300px"
        @search="fetchPostulantes"
      />
    </div>

    <a-card>
      <a-table
        :columns="columns"
        :data-source="postulantes"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'name'">
            <strong>{{ record.name }}</strong>
          </template>

          <template v-else-if="column.key === 'email'">
            {{ record.email }}
          </template>

          <template v-else-if="column.key === 'dni'">
            <a-tag color="blue">{{ record.dni }}</a-tag>
          </template>

          <template v-else-if="column.key === 'last_activity'">
            {{ record.last_activity ?? 'Sin actividad' }}
          </template>

          <template v-else-if="column.key === 'acciones'">
            <a-space>
              <a-button type="text" @click="editar(record)">
                Editar
              </a-button>
            </a-space>
          </template>

        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:open="showModal"
      title="Editar Postulante"
      @ok="guardarCambios"
      @cancel="resetForm"
    >
      <a-form layout="vertical">
        <a-form-item label="Nombre">
          <a-input v-model:value="form.name" />
        </a-form-item>

        <a-form-item label="Email">
          <a-input v-model:value="form.email" />
        </a-form-item>

        <a-form-item label="DNI">
          <a-input v-model:value="form.dni" />
        </a-form-item>

        <a-form-item label="Nueva contraseña (opcional)">
          <a-input-password v-model:value="form.password" />
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '../../../axios'

const postulantes = ref([])
const loading = ref(false)
const search = ref('')
const showModal = ref(false)
const editingId = ref(null)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

const form = reactive({
  name: '',
  email: '',
  dni: '',
  password: ''
})

const columns = [
  { title: 'Nombre', dataIndex: 'name', key: 'name' },
  { title: 'Email', dataIndex: 'email', key: 'email' },
  { title: 'DNI', dataIndex: 'dni', key: 'dni' },
  { title: 'Última actividad', dataIndex: 'last_activity', key: 'last_activity' },
  { title: 'Acciones', key: 'acciones', align: 'center' }
]

const fetchPostulantes = async () => {
  loading.value = true
  try {
    const { data } = await api.get('/admin/postulantes', {
      params: {
        page: pagination.current,
        buscar: search.value
      }
    })

    postulantes.value = data.data.data
    pagination.total = data.data.total

  } catch (error) {
    message.error('Error al cargar postulantes')
  } finally {
    loading.value = false
  }
}

const editar = (record) => {
  editingId.value = record.id
  form.name = record.name
  form.email = record.email
  form.dni = record.dni
  form.password = ''
  showModal.value = true
}


const guardarCambios = async () => {
  try {
    await api.put(`/admin/postulantes/${editingId.value}`, form)
    message.success('Postulante actualizado correctamente')
    showModal.value = false
    fetchPostulantes()
  } catch (error) {
    message.error(error.response?.data?.message || 'Error al actualizar')
  }
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  fetchPostulantes()
}

const resetForm = () => {
  showModal.value = false
  editingId.value = null
}

onMounted(fetchPostulantes)
</script>

<style scoped>
.postulantes-container {
  padding: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
}
</style>
