<template>
  <div class="cursos-container">
    <div class="cursos-header">
      <div class="header-title">
        <h2>Detalles del Proceso</h2>
        <p class="subtitle">Proceso: {{ store.procesoActual?.titulo || '-' }}</p>
      </div>

      <a-space>
        <a-button @click="goBack"><ArrowLeftOutlined /> Volver</a-button>
        <a-button type="primary" @click="openCreateModal"><PlusOutlined /> Nuevo Detalle</a-button>
      </a-space>
    </div>

    <div class="filters-section">
      <a-select v-model:value="tipoFilter" placeholder="Tipo" style="width: 240px" size="large" @change="fetchDetalles">
        <a-select-option :value="null">Todos</a-select-option>
        <a-select-option value="requisitos">requisitos</a-select-option>
        <a-select-option value="pagos">pagos</a-select-option>
        <a-select-option value="vacantes">vacantes</a-select-option>
        <a-select-option value="cronograma">cronograma</a-select-option>
      </a-select>

      <a-button @click="clearFilters" size="large">
        <ReloadOutlined /> Limpiar
      </a-button>
    </div>

    <div v-if="store.loading && store.detalles.length === 0" class="loading-state">
      <a-spin size="large" />
      <p>Cargando detalles...</p>
    </div>

    <div v-else-if="store.detalles.length === 0" class="empty-state">
      <a-empty description="No hay detalles" />
    </div>

    <div v-else class="cursos-table-container">
      <a-table :data-source="store.detalles" :columns="columns" :loading="store.loading" row-key="id" class="cursos-table">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'imagenes'">
            <a-space>
              <a v-if="record.imagen_url" :href="record.imagen_url" target="_blank">Imagen 1</a>
              <a v-if="record.imagen_url_2" :href="record.imagen_url_2" target="_blank">Imagen 2</a>
              <span v-if="!record.imagen_url && !record.imagen_url_2">-</span>
            </a-space>
          </template>

          <template v-else-if="column.key === 'acciones'">
            <a-space>
              <a-button type="link" size="small" @click="editDetalle(record)"><EditOutlined /> Editar</a-button>
              <a-button type="link" size="small" danger @click="confirmDelete(record)"><DeleteOutlined /> Eliminar</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- Modal Crear/Editar -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEditing ? 'Editar Detalle' : 'Nuevo Detalle'"
      :confirm-loading="store.loading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="920px"
      class="curso-modal"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules" layout="vertical" @finish="onFormSubmit">
        <div class="grid2">
          <a-form-item label="Tipo" name="tipo">
            <a-select v-model:value="formState.tipo" size="large" :disabled="isEditing">
              <a-select-option value="requisitos">requisitos</a-select-option>
              <a-select-option value="pagos">pagos</a-select-option>
              <a-select-option value="vacantes">vacantes</a-select-option>
              <a-select-option value="cronograma">cronograma</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="Título" name="titulo_detalle">
            <a-input v-model:value="formState.titulo_detalle" size="large" />
          </a-form-item>
        </div>

        <a-form-item label="Descripción" name="descripcion">
          <a-textarea v-model:value="formState.descripcion" :rows="3" />
        </a-form-item>

        <div class="grid2">
          <a-form-item label="URL (opcional)" name="url">
            <a-input v-model:value="formState.url" placeholder="https://..." size="large" />
          </a-form-item>

          <a-form-item label="Listas (JSON)" name="listas_json">
            <a-textarea v-model:value="formState.listas_json" :rows="8" placeholder='Ej: [{"titulo":"DNI","descripcion":"..."}]' />
          </a-form-item>
        </div>

        <a-form-item label="Meta (JSON)" name="meta_json">
          <a-textarea v-model:value="formState.meta_json" :rows="6" placeholder='Ej: {"moneda":"PEN"}' />
        </a-form-item>

        <a-divider>Imágenes (SUBIR)</a-divider>

        <div class="grid2">
          <a-form-item label="Imagen 1">
            <a-upload v-model:file-list="fileImg1" :before-upload="() => false" :max-count="1" accept="image/*">
              <a-button>Seleccionar</a-button>
            </a-upload>
            <small class="hint" v-if="isEditing && formState.imagen_url">
              Actual: <a :href="formState.imagen_url" target="_blank">ver</a>
            </small>
          </a-form-item>

          <a-form-item label="Imagen 2">
            <a-upload v-model:file-list="fileImg2" :before-upload="() => false" :max-count="1" accept="image/*">
              <a-button>Seleccionar</a-button>
            </a-upload>
            <small class="hint" v-if="isEditing && formState.imagen_url_2">
              Actual: <a :href="formState.imagen_url_2" target="_blank">ver</a>
            </small>
          </a-form-item>
        </div>

        <div class="form-footer" v-if="store.error">
          <a-alert type="error" :message="store.error" show-icon class="error-alert" />
        </div>
      </a-form>
    </a-modal>

    <!-- Delete modal -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="Confirmar Eliminación"
      @ok="handleDelete"
      @cancel="deleteModalVisible = false"
      ok-text="Eliminar"
      cancel-text="Cancelar"
      ok-type="danger"
      width="420px"
    >
      <a-alert message="¿Eliminar este detalle?" type="warning" show-icon />
      <div class="curso-info" v-if="toDelete" style="margin-top:12px;">
        <p><strong>Tipo:</strong> {{ toDelete.tipo }}</p>
        <p><strong>Título:</strong> {{ toDelete.titulo_detalle }}</p>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, ArrowLeftOutlined } from '@ant-design/icons-vue'
import { useProcesoAdmisionStore } from '../../../store/procesosAdmisionStore'

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

const procesoId = computed(() => Number(route.params.id))
const tipoFilter = ref(null)

const modalVisible = ref(false)
const deleteModalVisible = ref(false)
const isEditing = ref(false)
const toDelete = ref(null)
const formRef = ref()

const fileImg1 = ref([])
const fileImg2 = ref([])

const formState = reactive({
  id: null,
  tipo: 'requisitos',
  titulo_detalle: '',
  descripcion: '',
  url: '',
  listas_json: '',
  meta_json: '',
  imagen_url: null,
  imagen_url_2: null
})

const formRules = {
  tipo: [{ required: true, message: 'Selecciona tipo', trigger: 'change' }],
  titulo_detalle: [{ required: true, message: 'Ingresa título', trigger: 'blur' }]
}

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: 'Tipo', dataIndex: 'tipo', key: 'tipo', width: 130 },
  { title: 'Título', dataIndex: 'titulo_detalle', key: 'titulo_detalle' },
  { title: 'Imágenes', key: 'imagenes', width: 180 },
  { title: 'Acciones', key: 'acciones', width: 160, align: 'center' }
]

function goBack() {
  router.push({ name: 'ProcesosAdmisionList' })
}

function clearFilters() {
  tipoFilter.value = null
  fetchDetalles()
}

async function fetchDetalles() {
  await store.fetchDetalles(procesoId.value, {
    tipo: tipoFilter.value || undefined
  })
}

function resetUploads() {
  fileImg1.value = []
  fileImg2.value = []
}

function resetForm() {
  formState.id = null
  formState.tipo = 'requisitos'
  formState.titulo_detalle = ''
  formState.descripcion = ''
  formState.url = ''
  formState.listas_json = ''
  formState.meta_json = ''
  formState.imagen_url = null
  formState.imagen_url_2 = null
  resetUploads()
  formRef.value?.resetFields?.()
}

function openCreateModal() {
  isEditing.value = false
  resetForm()
  modalVisible.value = true
}

function editDetalle(row) {
  isEditing.value = true
  resetForm()

  formState.id = row.id
  formState.tipo = row.tipo
  formState.titulo_detalle = row.titulo_detalle
  formState.descripcion = row.descripcion || ''
  formState.url = row.url || ''
  formState.listas_json = row.listas ? JSON.stringify(row.listas, null, 2) : ''
  formState.meta_json = row.meta ? JSON.stringify(row.meta, null, 2) : ''
  formState.imagen_url = row.imagen_url || null
  formState.imagen_url_2 = row.imagen_url_2 || null

  modalVisible.value = true
}

async function handleModalOk() {
  try {
    await formRef.value.validateFields()
    await onFormSubmit()
  } catch (_) {}
}

function handleModalCancel() {
  modalVisible.value = false
  resetForm()
}

function safeJson(text, label) {
  if (!text || !text.trim()) return null
  try {
    return JSON.parse(text)
  } catch {
    message.error(`JSON inválido en ${label}`)
    throw new Error('json_invalid')
  }
}

function buildDetalleFormData() {
  const fd = new FormData()

  fd.append('tipo', formState.tipo)
  fd.append('titulo_detalle', formState.titulo_detalle)
  if (formState.descripcion) fd.append('descripcion', formState.descripcion)
  if (formState.url) fd.append('url', formState.url)

  const listas = safeJson(formState.listas_json, 'listas')
  const meta = safeJson(formState.meta_json, 'meta')

  // 👇 OJO: backend valida 'array' para listas/meta (Laravel)
  // Para FormData, lo más compatible es enviarlo como JSON string y en backend hacer json_decode.
  // Si tu backend ya espera array directo, entonces NO uses FormData para listas/meta.
  // Solución simple: envía como string y decodifica en controller.
  if (listas !== null) fd.append('listas', JSON.stringify(listas))
  if (meta !== null) fd.append('meta', JSON.stringify(meta))

  const img1 = fileImg1.value?.[0]?.originFileObj
  const img2 = fileImg2.value?.[0]?.originFileObj
  if (img1) fd.append('imagen', img1)
  if (img2) fd.append('imagen_2', img2)

  return fd
}

async function onFormSubmit() {
  const fd = buildDetalleFormData()

  // method spoof para update multipart
  if (isEditing.value) {
    fd.append('_method', 'PATCH')
    const ok = await store.updateDetalle(formState.id, fd, { method: 'post' })
    if (ok) message.success('Detalle actualizado')
    else message.error('Error al actualizar')
  } else {
    const ok = await store.createDetalle(procesoId.value, fd)
    if (ok) message.success('Detalle creado')
    else message.error('Error al crear')
  }

  modalVisible.value = false
  resetForm()
  await fetchDetalles()
}

function confirmDelete(row) {
  toDelete.value = row
  deleteModalVisible.value = true
}

async function handleDelete() {
  const ok = await store.deleteDetalle(toDelete.value.id, procesoId.value)
  if (ok) message.success('Detalle eliminado')
  else message.error('Error al eliminar')
  deleteModalVisible.value = false
  toDelete.value = null
}

onMounted(async () => {
  await store.fetchProceso(procesoId.value, { include_detalles: false })
  await fetchDetalles()
})
</script>

<style scoped>
.cursos-container { padding: 0; }
.cursos-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:24px; padding:0 8px; gap: 12px; flex-wrap: wrap; }
.header-title h2 { margin:0; font-size:24px; font-weight:600; color:#1f1f1f; }
.subtitle { margin:4px 0 0; color:#666; font-size:14px; }
.filters-section { display:flex; align-items:center; margin-bottom:18px; padding:0 8px; flex-wrap:wrap; gap:16px; }
.loading-state { display:flex; flex-direction:column; align-items:center; justify-content:center; min-height:220px; gap:16px; }
.empty-state { min-height:220px; display:flex; align-items:center; justify-content:center; }
.cursos-table-container { background:white; border-radius:12px; box-shadow:0 2px 8px rgba(0,0,0,.06); border:1px solid #f0f0f0; overflow:hidden; }
.cursos-table { border-radius:12px; }
.grid2 { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.grid3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
.hint { display:block; margin-top: 6px; color:#666; }
@media (max-width: 768px) { .grid2, .grid3 { grid-template-columns: 1fr; } }
</style>
