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

    <div class="areas-header">
      <div class="header-title">
        <h2>Áreas Académicas</h2>
        <p class="subtitle">Gestiona las áreas académicas del sistema</p>
      </div>
      <a-button 
        type="primary" 
        @click="showCreateModal"
        class="new-area-btn"
      >
        <template #icon>
          <PlusOutlined />
        </template>
        Nueva Área
      </a-button>
    </div>

    <div class="filters-section">
      <a-input-search
        v-model:value="searchText"
        placeholder="Buscar por nombre o código..."
        @search="handleSearch"
        @press-enter="handleSearch"
        style="width: 300px"
        size="large"
      >
        <template #enterButton>
          <SearchOutlined />
        </template>
      </a-input-search>
      
      <a-select
        v-model:value="statusFilter"
        placeholder="Filtrar por estado"
        style="width: 200px; margin-left: 16px"
        size="large"
        @change="handleStatusFilterChange"
      >
        <a-select-option :value="null">Todos los estados</a-select-option>
        <a-select-option :value="true">Activo</a-select-option>
        <a-select-option :value="false">Inactivo</a-select-option>
      </a-select>
      
      <a-button
        @click="handleClearFilters"
        style="margin-left: 16px"
        size="large"
      >
        <template #icon>
          <ReloadOutlined />
        </template>
        Limpiar filtros
      </a-button>
    </div>

    <div v-if="areaStore.loading && areaStore.areas.length === 0" class="loading-state">
      <a-spin size="large" />
      <p>Cargando áreas...</p>
    </div>


    <div v-else-if="areaStore.areas.length === 0" class="empty-state">
      <a-empty description="No hay áreas registradas" />
    </div>

    <div v-else class="areas-table-container">
      <a-table 
        :data-source="areaStore.areas"
        :columns="columns"
        :loading="areaStore.loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="areas-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- Estado -->
          <template v-if="column.key === 'activo'">
            <a-switch
              :checked="record.activo"
              :loading="togglingId === record.id"
              @change="handleToggleStatus(record)"
              checked-children="Activo"
              un-checked-children="Inactivo"
            />
          </template>

          <template v-if="column.key === 'created_at'">
            {{ formatDate(record.created_at) }}
          </template>
          <template v-if="column.key === 'cursos_count'">
            <div class="count-badge" @click="showCourseModal(record)" style="cursor: pointer;">
              <a-tag color="blue">{{ record.cursos_count || 0 }}</a-tag>
              <span v-if="record.cursos_count > 0" class="count-label">curso(s)</span>
            </div>
          </template>

          <template v-if="column.key === 'procesos_count'">
            <div class="count-badge" @click="showProcessModal(record)" style="cursor: pointer;">
              <a-tag color="green">{{ record.procesos_count || 0 }}</a-tag>
              <span v-if="record.procesos_count > 0" class="count-label">proceso(s)</span>
            </div>
          </template>

          <template v-if="column.key === 'acciones'">
            <a-space>
                  <a-button 
                  type="link" 
                  size="small"
                  @click="showProcessModal(record)"
                  class="action-btn"
                >
                  <ApartmentOutlined /> P
                </a-button>


                  <a-button 
                    type="link" 
                    size="small"
                    @click="showCourseModal(record)"
                    class="action-btn"
                  >
                    <BookOutlined /> C
                  </a-button>
              <a-button 
                type="link" 
                size="small"
                @click="showEditModal(record)"
                class="action-btn"
              >
                <EditOutlined /> 
              </a-button>
              <a-button 
                type="link" 
                size="small"
                danger
                @click="confirmDelete(record)"
                class="action-btn"
              >
                <DeleteOutlined /> 
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:open="modalVisible"
      :title="isEditing ? 'Editar Área' : 'Nueva Área'"
      :confirm-loading="areaStore.loading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="500px"
      class="area-modal"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        layout="vertical"
        @finish="onFormSubmit"
      >
        <a-form-item 
          label="Nombre del Área" 
          name="nombre"
          :validate-status="getFieldStatus('nombre')"
          :help="getFieldHelp('nombre')"
        >
          <a-input
            v-model:value="formState.nombre"
            placeholder="Ej: Matemáticas, Ciencias, Lenguaje"
            size="large"
          />
        </a-form-item>

        <a-form-item 
          label="Código" 
          name="codigo"
          :validate-status="getFieldStatus('codigo')"
          :help="getFieldHelp('codigo')"
        >
          <a-input
            v-model:value="formState.codigo"
            placeholder="Código único (ej: MAT, CIE, LEN)"
            size="large"
          />
        </a-form-item>

        <div class="form-footer" v-if="areaStore.errors">
          <a-alert
            v-for="(errorList, field) in areaStore.errors"
            :key="field"
            type="error"
            :message="errorList[0]"
            show-icon
            class="error-alert"
          />
        </div>
      </a-form>
    </a-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="400px"
    >
      <div class="delete-confirm-content">
        <a-alert
          message="¿Estás seguro de eliminar esta área?"
          description="Esta acción no se puede deshacer. Se eliminarán todos los datos asociados al área."
          type="warning"
          show-icon
        />
        <div class="area-info" v-if="areaToDelete">
          <p><strong>Área:</strong> {{ areaToDelete.nombre }}</p>
          <p><strong>Código:</strong> {{ areaToDelete.codigo }}</p>
        </div>
      </div>
    </a-modal>
    <CourseModal
      v-if="selectedAreaForCourses"
      v-model:open="courseModalVisible"
      :area-id="selectedAreaForCourses?.id"
      :area-nombre="selectedAreaForCourses?.nombre"
      @courses-updated="handleCoursesUpdated"
    />

    <ProcesosModal
      v-if="selectedAreaForProcesses"
  v-model:open="processModalVisible"
  :area-id="selectedAreaForProcesses?.id"
  :area-nombre="selectedAreaForProcesses?.nombre"
  @procesos-updated="handleProcessesUpdated"
/>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAreaStore } from '../../../store/area.store'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  BookOutlined,
  ApartmentOutlined,
} from '@ant-design/icons-vue'
import CourseModal from '../areas/CursosModal.vue'
import ProcesosModal from '../areas/ProcesosModal.vue'
const areaStore = useAreaStore()

const modalVisible = ref(false)
const deleteModalVisible = ref(false)
const isEditing = ref(false)
const areaToDelete = ref(null)
const formRef = ref()
const searchText = ref('')
const statusFilter = ref(null)
const togglingId = ref(null)

const formState = reactive({
  id: null,
  nombre: '',
  codigo: ''
})
const courseModalVisible = ref(false) 
const selectedAreaForCourses = ref(null)
const processModalVisible = ref(false)
const selectedAreaForProcesses = ref(null)

const showCourseModal = (area) => {
  selectedAreaForCourses.value = area
  courseModalVisible.value = true
}

const handleCoursesUpdated = () => {
  areaStore.fetchAreas()
  message.success('Cursos actualizados correctamente')
}


const showProcessModal = (area) => {
  selectedAreaForProcesses.value = area
  processModalVisible.value = true
}

const handleProcessesUpdated = () => {
  areaStore.fetchAreas()
  message.success('Procesos actualizados correctamente')
}


const formRules = {
  nombre: [
    { required: true, message: 'Por favor ingresa el nombre del área', trigger: 'blur' },
    { min: 3, max: 100, message: 'El nombre debe tener entre 3 y 100 caracteres', trigger: 'blur' }
  ],
  codigo: [
    { required: true, message: 'Por favor ingresa el código del área', trigger: 'blur' },
    { min: 2, max: 10, message: 'El código debe tener entre 2 y 10 caracteres', trigger: 'blur' }
  ]
}

const pagination = computed(() => ({
  current: areaStore.pagination.current_page,
  pageSize: areaStore.pagination.per_page,
  total: areaStore.pagination.total,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  showTotal: (total, range) => `${range[0]}-${range[1]} de ${total} áreas`
}))

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: 'Nombre',
    dataIndex: 'nombre',
    key: 'nombre',
    sorter: (a, b) => a.nombre.localeCompare(b.nombre)
  },
  {
    title: 'Código',
    dataIndex: 'codigo',
    key: 'codigo',
    width: 120
  },
  {
    title: 'Cursos',
    key: 'cursos_count',
    width: 120,
    align: 'center',

  },
  {
    title: 'Procesos', 
    key: 'procesos_count',
    width: 120,
    align: 'center',

  },
  {
    title: 'Estado',
    dataIndex: 'activo',
    key: 'activo',
    width: 120
  },
  {
    title: 'Creado',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  },
  {
    title: 'Acciones',
    key: 'acciones',
    width: 250, 
    align: 'center'
  }
]
// Métodos
const showCreateModal = () => {
  isEditing.value = false
  resetForm()
  modalVisible.value = true
  areaStore.clearErrors()
}

const showEditModal = (area) => {
  isEditing.value = true
  resetForm()
  
  formState.id = area.id
  formState.nombre = area.nombre
  formState.codigo = area.codigo
  
  modalVisible.value = true
  areaStore.clearErrors()
}

const confirmDelete = (area) => {
  areaToDelete.value = area
  deleteModalVisible.value = true
}

const handleDelete = async () => {
  try {
    await areaStore.deleteArea(areaToDelete.value.id)
    message.success('Área eliminada correctamente')
    deleteModalVisible.value = false
    areaToDelete.value = null
  } catch (error) {
    message.error('Error al eliminar el área')
  }
}

const handleModalOk = async () => {
  try {
    await formRef.value.validateFields()
    await onFormSubmit()
  } catch (error) {
    console.log('Validación fallida:', error)
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
  areaStore.clearErrors()
}

const onFormSubmit = async () => {
  const payload = {
    nombre: formState.nombre,
    codigo: formState.codigo
  }

  let success = false
  
  if (isEditing.value) {
    success = await areaStore.updateArea(formState.id, payload)
  } else {
    success = await areaStore.createArea(payload)
  }

  if (success) {
    message.success(
      isEditing.value 
        ? 'Área actualizada correctamente' 
        : 'Área creada correctamente'
    )
    modalVisible.value = false
    resetForm()
    areaStore.clearErrors()
  } else {
    message.error('Error al guardar el área')
  }
}

const resetForm = () => {
  formState.id = null
  formState.nombre = ''
  formState.codigo = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSearch = () => {
  areaStore.setSearch(searchText.value)
  areaStore.fetchAreas({ page: 1 })
}

const handleStatusFilterChange = (value) => {
  areaStore.setActivo(value)
  areaStore.fetchAreas({ page: 1 })
}

const handleClearFilters = () => {
  searchText.value = ''
  statusFilter.value = null
  areaStore.clearFilters()
  areaStore.fetchAreas({ page: 1 })
}

const handleTableChange = (paginationConfig, filters, sorter) => {
  areaStore.fetchAreas({
    page: paginationConfig.current,
    per_page: paginationConfig.pageSize
  })
}

const handleToggleStatus = async (area) => {
  togglingId.value = area.id
  try {
    await areaStore.toggleArea(area.id)
    message.success(`Área ${area.activo ? 'desactivada' : 'activada'} correctamente`)
  } catch (error) {
    message.error('Error al cambiar el estado del área')
  } finally {
    togglingId.value = null
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('es-ES', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

const getFieldStatus = (fieldName) => {
  if (areaStore.errors && areaStore.errors[fieldName]) {
    return 'error'
  }
  return ''
}

const getFieldHelp = (fieldName) => {
  if (areaStore.errors && areaStore.errors[fieldName]) {
    return areaStore.errors[fieldName][0]
  }
  return ''
}

// Lifecycle
onMounted(() => {
  areaStore.fetchAreas()
})
</script>

<style scoped>
.areas-container {
  padding: 0;
}

.areas-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 8px;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f1f1f;
}

.subtitle {
  margin: 4px 0 0 0;
  color: #666;
  font-size: 14px;
}

.new-area-btn {
  height: 40px;
  font-weight: 500;
}

.filters-section {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 8px;
  flex-wrap: wrap;
  gap: 16px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  gap: 16px;
}

.loading-state p {
  color: #666;
  margin: 0;
}

.empty-state {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.areas-table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

.areas-table {
  border-radius: 12px;
}
  .areas-table {
    min-width: 900px;
  }
.areas-table :deep(.ant-table) {
  border-radius: 12px;
}

.areas-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #1f1f1f;
  border-bottom: 1px solid #f0f0f0;
}

.areas-table :deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid #f0f0f0;
}

.areas-table :deep(.ant-table-tbody > tr:hover > td) {
  background: #fafafa;
}

.action-btn {
  padding: 4px 8px;
  height: auto;
}
  .action-btn:nth-child(1),
  .action-btn:nth-child(2) {
    color: #1890ff;
  }

  .action-btn:nth-child(1):hover,
  .action-btn:nth-child(2):hover {
    color: #40a9ff;
  }
.action-btn :deep(.anticon) {
  font-size: 14px;
}

.area-modal :deep(.ant-modal-header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 20px 24px;
}

.area-modal :deep(.ant-modal-body) {
  padding: 24px;
}

.area-modal :deep(.ant-modal-footer) {
  border-top: 1px solid #f0f0f0;
  padding: 12px 24px;
}

.form-footer {
  margin-top: 16px;
}

.error-alert {
  margin-bottom: 8px;
}

.error-alert:last-child {
  margin-bottom: 0;
}

.delete-confirm-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.area-info {
  background: #fafafa;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.area-info p {
  margin: 4px 0;
  color: #666;
}

.area-info p strong {
  color: #1f1f1f;
}

@media (max-width: 768px) {
  .areas-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .new-area-btn {
    align-self: flex-start;
  }
  
  .filters-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filters-section .ant-input-search,
  .filters-section .ant-select,
  .filters-section .ant-btn {
    width: 100%;
    margin-left: 0;
    margin-bottom: 8px;
  }
  
  .areas-table-container {
    overflow-x: auto;
  }
  


.action-btn {
  padding: 4px 8px;
  height: auto;
  font-size: 12px;
}

.action-btn :deep(.anticon) {
  font-size: 12px;
  margin-right: 4px;
}

.action-btn:first-child {
  color: #1890ff;
}

.action-btn:first-child:hover {
  color: #40a9ff;
}
}
</style>