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

    <!-- Header -->
    <div class="areas-header">
      <div class="header-title">
        <h2>Usuarios del sistema</h2>
        <p class="subtitle">Administra las cuentas de acceso al panel</p>
      </div>
      <a-button type="primary" @click="abrirModalCrear">
        <template #icon><PlusOutlined /></template>
        Nuevo usuario
      </a-button>
    </div>

    <!-- Filtros -->
    <div class="filtros-bar">
      <a-input-search
        v-model:value="filtros.buscar"
        placeholder="Buscar por nombre o email..."
        style="width: 280px"
        allow-clear
        @search="buscar"
        @change="onBuscarChange"
      />
      <a-select
        v-model:value="filtros.rol"
        placeholder="Filtrar por rol"
        style="width: 180px"
        allow-clear
        @change="buscar"
      >
        <a-select-option v-for="rol in store.roles" :key="rol.name" :value="rol.name">
          {{ rol.name }}
        </a-select-option>
      </a-select>
    </div>

    <!-- Tabla -->
    <div class="areas-table-container">
      <a-table
        :columns="columnas"
        :data-source="store.usuarios"
        :loading="store.loading"
        :pagination="{
          current: store.pagination.current,
          pageSize: store.pagination.pageSize,
          total: store.pagination.total,
          showTotal: (t) => `${t} usuarios`,
        }"
        row-key="id"
        class="areas-table"
        @change="onTableChange"
      >
        <template #bodyCell="{ column, record }">

          <!-- Nombre + avatar inicial -->
          <template v-if="column.key === 'name'">
            <div style="display: flex; align-items: center; gap: 10px;">
              <a-avatar :style="{ background: avatarColor(record.name), fontSize: '13px' }" :size="32">
                {{ iniciales(record.name) }}
              </a-avatar>
              <span>{{ record.name }}</span>
            </div>
          </template>

          <!-- Rol -->
          <template v-else-if="column.key === 'roles'">
            <a-tag
              v-for="rol in record.roles"
              :key="rol"
              :color="rolColor(rol)"
            >
              {{ rol }}
            </a-tag>
            <a-tag v-if="!record.roles?.length" color="default">Sin rol</a-tag>
          </template>

          <!-- Fecha -->
          <template v-else-if="column.key === 'created_at'">
            <span style="font-size: 12px; color: #666;">{{ formatDate(record.created_at) }}</span>
          </template>

          <!-- Acciones -->
          <template v-else-if="column.key === 'acciones'">
            <div style="display: flex; gap: 6px; flex-wrap: wrap;">
              <a-button size="small" @click="abrirModalEditar(record)">
                <template #icon><EditOutlined /></template>
                Editar
              </a-button>
              <a-button size="small" @click="abrirModalPassword(record)">
                <template #icon><LockOutlined /></template>
                Contraseña
              </a-button>
              <a-popconfirm
                title="¿Eliminar este usuario?"
                ok-text="Sí, eliminar"
                cancel-text="Cancelar"
                ok-type="danger"
                :disabled="record.id === userStore.user?.id"
                @confirm="eliminarUsuario(record.id)"
              >
                <a-button
                  size="small"
                  danger
                  :disabled="record.id === userStore.user?.id"
                >
                  <template #icon><DeleteOutlined /></template>
                  Eliminar
                </a-button>
              </a-popconfirm>
            </div>
          </template>

        </template>
      </a-table>
    </div>

    <!-- ===== MODAL CREAR ===== -->
    <a-modal
      v-model:open="modalCrear.visible"
      title="Nuevo usuario"
      :confirm-loading="modalCrear.loading"
      ok-text="Crear usuario"
      cancel-text="Cancelar"
      @ok="submitCrear"
      @cancel="resetModalCrear"
    >
      <a-form
        ref="formCrearRef"
        :model="modalCrear.form"
        :rules="reglasCrear"
        layout="vertical"
        style="margin-top: 12px;"
      >
        <a-form-item label="Nombre completo" name="name">
          <a-input v-model:value="modalCrear.form.name" placeholder="Ej: Juan Pérez" />
        </a-form-item>
        <a-form-item label="Correo electrónico" name="email">
          <a-input v-model:value="modalCrear.form.email" placeholder="correo@ejemplo.com" />
        </a-form-item>
        <a-form-item label="Rol" name="rol">
          <a-select v-model:value="modalCrear.form.rol" placeholder="Selecciona un rol">
            <a-select-option v-for="rol in store.roles" :key="rol.name" :value="rol.name">
              {{ rol.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="Contraseña" name="password">
          <a-input-password v-model:value="modalCrear.form.password" placeholder="Mínimo 8 caracteres" />
        </a-form-item>
        <a-form-item label="Confirmar contraseña" name="password_confirmation">
          <a-input-password v-model:value="modalCrear.form.password_confirmation" placeholder="Repite la contraseña" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- ===== MODAL EDITAR ===== -->
    <a-modal
      v-model:open="modalEditar.visible"
      title="Editar usuario"
      :confirm-loading="modalEditar.loading"
      ok-text="Guardar cambios"
      cancel-text="Cancelar"
      @ok="submitEditar"
      @cancel="resetModalEditar"
    >
      <a-form
        ref="formEditarRef"
        :model="modalEditar.form"
        :rules="reglasEditar"
        layout="vertical"
        style="margin-top: 12px;"
      >
        <a-form-item label="Nombre completo" name="name">
          <a-input v-model:value="modalEditar.form.name" />
        </a-form-item>
        <a-form-item label="Correo electrónico" name="email">
          <a-input v-model:value="modalEditar.form.email" />
        </a-form-item>
        <a-form-item label="Rol" name="rol">
          <a-select v-model:value="modalEditar.form.rol" placeholder="Selecciona un rol">
            <a-select-option v-for="rol in store.roles" :key="rol.name" :value="rol.name">
              {{ rol.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- ===== MODAL CAMBIAR CONTRASEÑA ===== -->
    <a-modal
      v-model:open="modalPassword.visible"
      title="Cambiar contraseña"
      :confirm-loading="modalPassword.loading"
      ok-text="Actualizar contraseña"
      cancel-text="Cancelar"
      @ok="submitPassword"
      @cancel="resetModalPassword"
    >
      <a-alert
        v-if="modalPassword.esPropia"
        message="Estás cambiando tu propia contraseña. Se te pedirá la contraseña actual."
        type="info"
        show-icon
        style="margin-bottom: 16px;"
      />
      <a-alert
        v-else
        :message="`Cambiando contraseña de ${modalPassword.usuario?.name}. La sesión activa de este usuario será cerrada.`"
        type="warning"
        show-icon
        style="margin-bottom: 16px;"
      />
      <a-form
        ref="formPasswordRef"
        :model="modalPassword.form"
        :rules="reglasPassword"
        layout="vertical"
      >
        <a-form-item
          v-if="modalPassword.esPropia"
          label="Contraseña actual"
          name="current_password"
        >
          <a-input-password v-model:value="modalPassword.form.current_password" placeholder="Tu contraseña actual" />
        </a-form-item>
        <a-form-item label="Nueva contraseña" name="password">
          <a-input-password v-model:value="modalPassword.form.password" placeholder="Mínimo 8 caracteres" />
        </a-form-item>
        <a-form-item label="Confirmar nueva contraseña" name="password_confirmation">
          <a-input-password v-model:value="modalPassword.form.password_confirmation" placeholder="Repite la nueva contraseña" />
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LockOutlined,
} from '@ant-design/icons-vue'
import { useUsuariosStore } from '../../../store/usuariosStore'
import { useUserStore } from '../../../store/user'

const store     = useUsuariosStore()
const userStore = useUserStore()

// ─── Tabla ────────────────────────────────────────────────────────────────────

const columnas = [
  { title: 'Nombre',   key: 'name',       dataIndex: 'name' },
  { title: 'Email',    key: 'email',      dataIndex: 'email' },
  { title: 'Rol',      key: 'roles' },
  { title: 'Creado',   key: 'created_at' },
  { title: 'Acciones', key: 'acciones',   width: 240 },
]

const filtros = reactive({ buscar: '', rol: undefined })

const onTableChange = ({ current }) => {
  store.fetchUsuarios({ page: current, buscar: filtros.buscar, rol: filtros.rol })
}

let buscarTimer = null
const onBuscarChange = () => {
  clearTimeout(buscarTimer)
  buscarTimer = setTimeout(() => buscar(), 400)
}

const buscar = () => {
  store.fetchUsuarios({ page: 1, buscar: filtros.buscar, rol: filtros.rol })
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const iniciales = (name) => {
  if (!name) return 'U'
  const parts = name.split(' ')
  return parts.length === 1
    ? parts[0][0].toUpperCase()
    : (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
}

const COLORS = ['#1890ff','#52c41a','#fa8c16','#f5222d','#722ed1','#13c2c2','#eb2f96','#faad14']
const avatarColor = (name) => {
  if (!name) return COLORS[0]
  const idx = name.split('').reduce((a, c) => a + c.charCodeAt(0), 0)
  return COLORS[idx % COLORS.length]
}

const rolColor = (rol) => {
  const map = { administrador: 'blue', superadmin: 'purple', editor: 'green', viewer: 'default' }
  return map[rol?.toLowerCase()] || 'geekblue'
}

const formatDate = (val) => {
  if (!val) return '—'
  return new Date(val).toLocaleDateString('es-PE', { day: '2-digit', month: 'short', year: 'numeric' })
}

// ─── Modal Crear ──────────────────────────────────────────────────────────────

const formCrearRef = ref(null)

const modalCrear = reactive({
  visible: false,
  loading: false,
  form: { name: '', email: '', rol: undefined, password: '', password_confirmation: '' },
})

const reglasCrear = {
  name:                  [{ required: true, message: 'Ingresa el nombre' }],
  email:                 [{ required: true, type: 'email', message: 'Ingresa un email válido' }],
  rol:                   [{ required: true, message: 'Selecciona un rol' }],
  password:              [{ required: true, min: 8, message: 'Mínimo 8 caracteres' }],
  password_confirmation: [{ required: true, message: 'Confirma la contraseña' }],
}

const abrirModalCrear = () => { modalCrear.visible = true }

const resetModalCrear = () => {
  formCrearRef.value?.resetFields()
  Object.assign(modalCrear.form, { name: '', email: '', rol: undefined, password: '', password_confirmation: '' })
}

const submitCrear = async () => {
  try {
    await formCrearRef.value.validate()
  } catch {
    return
  }
  modalCrear.loading = true
  try {
    await store.createUsuario({ ...modalCrear.form })
    message.success('Usuario creado correctamente')
    modalCrear.visible = false
    resetModalCrear()
    store.fetchUsuarios({ page: 1 })
  } catch (error) {
    mostrarErrores(error)
  } finally {
    modalCrear.loading = false
  }
}

// ─── Modal Editar ─────────────────────────────────────────────────────────────

const formEditarRef = ref(null)

const modalEditar = reactive({
  visible: false,
  loading: false,
  id: null,
  form: { name: '', email: '', rol: undefined },
})

const reglasEditar = {
  name:  [{ required: true, message: 'Ingresa el nombre' }],
  email: [{ required: true, type: 'email', message: 'Ingresa un email válido' }],
  rol:   [{ required: true, message: 'Selecciona un rol' }],
}

const abrirModalEditar = (record) => {
  modalEditar.id = record.id
  modalEditar.form.name  = record.name
  modalEditar.form.email = record.email
  modalEditar.form.rol   = record.roles?.[0] ?? undefined
  modalEditar.visible    = true
}

const resetModalEditar = () => {
  formEditarRef.value?.resetFields()
  modalEditar.id = null
  Object.assign(modalEditar.form, { name: '', email: '', rol: undefined })
}

const submitEditar = async () => {
  try {
    await formEditarRef.value.validate()
  } catch {
    return
  }
  modalEditar.loading = true
  try {
    await store.updateUsuario(modalEditar.id, { ...modalEditar.form })
    message.success('Usuario actualizado correctamente')
    modalEditar.visible = false
    resetModalEditar()
    store.fetchUsuarios({ page: store.pagination.current, buscar: filtros.buscar, rol: filtros.rol })
  } catch (error) {
    mostrarErrores(error)
  } finally {
    modalEditar.loading = false
  }
}

// ─── Modal Contraseña ─────────────────────────────────────────────────────────

const formPasswordRef = ref(null)

const modalPassword = reactive({
  visible: false,
  loading: false,
  usuario: null,
  esPropia: false,
  form: { current_password: '', password: '', password_confirmation: '' },
})

const reglasPassword = computed(() => ({
  ...(modalPassword.esPropia
    ? { current_password: [{ required: true, message: 'Ingresa tu contraseña actual' }] }
    : {}),
  password:              [{ required: true, min: 8, message: 'Mínimo 8 caracteres' }],
  password_confirmation: [{ required: true, message: 'Confirma la nueva contraseña' }],
}))

const abrirModalPassword = (record) => {
  modalPassword.usuario  = record
  modalPassword.esPropia = record.id === userStore.user?.id
  modalPassword.visible  = true
}

const resetModalPassword = () => {
  formPasswordRef.value?.resetFields()
  Object.assign(modalPassword.form, { current_password: '', password: '', password_confirmation: '' })
  modalPassword.usuario = null
}

const submitPassword = async () => {
  try {
    await formPasswordRef.value.validate()
  } catch {
    return
  }

  if (modalPassword.form.password !== modalPassword.form.password_confirmation) {
    message.error('Las contraseñas no coinciden')
    return
  }

  modalPassword.loading = true
  try {
    await store.changePassword(modalPassword.usuario.id, { ...modalPassword.form })
    message.success('Contraseña actualizada correctamente')
    modalPassword.visible = false
    resetModalPassword()
  } catch (error) {
    mostrarErrores(error)
  } finally {
    modalPassword.loading = false
  }
}

// ─── Eliminar ─────────────────────────────────────────────────────────────────

const eliminarUsuario = async (id) => {
  try {
    await store.deleteUsuario(id)
    message.success('Usuario eliminado')
    store.fetchUsuarios({ page: store.pagination.current, buscar: filtros.buscar, rol: filtros.rol })
  } catch (error) {
    mostrarErrores(error)
  }
}

// ─── Errores del backend ──────────────────────────────────────────────────────

const mostrarErrores = (error) => {
  const errors = error?.response?.data?.errors
  if (errors) {
    Object.values(errors).flat().forEach((msg) => message.error(msg))
  } else {
    const msg = error?.response?.data?.message || 'Ocurrió un error inesperado'
    message.error(msg)
  }
}

// ─── Init ─────────────────────────────────────────────────────────────────────

onMounted(async () => {
  await Promise.all([
    store.fetchUsuarios({ page: 1 }),
    store.fetchRoles(),
  ])
})
</script>

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

.areas-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.header-title h2 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1a2e;
}

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

.filtros-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.areas-table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.areas-table :deep(.ant-table-thead th) {
  background: #fafafa;
  font-weight: 600;
  font-size: 13px;
}
</style>
