<script setup>
import { goTo, transl } from "./Component";
import { Link, useForm } from "@inertiajs/vue3";
import { ref, computed, onMounted } from "vue";

import PageHeader from "@/Components/Dashboard/PageHeader.vue";
import GoogleIcon from "@/Components/Shared/GoogleIcon.vue";
import DashboardLayout from "@/Layouts/DashboardLayout.vue";
import DepartmentSelector from "@/Components/App/DepartmentSelector.vue";
import MainRoleSelector from "@/Components/App/MainRoleSelector.vue";
import SkillAssignment from "@/Components/App/SkillAssignment.vue";

const props = defineProps({
  mainRoles: {
    type: Array,
    default: () => []
  },
  skills: {
    type: Array,
    default: () => []
  },
  scores: {
    type: Array,
    default: () => []
  },
  selectedRole: {
    type: Object,
    default: null
  },
  selectedDepartment: {
    type: Object,
    default: null
  }
});

const selectedDepartment = ref(props.selectedDepartment);
const selectedMainRole = ref(props.selectedRole);

const form = useForm({
  main_role_id: props.selectedRole?.id || '',
  skills: []
});

// Obtener departamentos únicos
const departments = computed(() => {
  const uniqueDepartments = [];
  const seenIds = new Set();

  props.mainRoles.forEach(role => {
    if (role.department && !seenIds.has(role.department.id)) {
      seenIds.add(role.department.id);
      uniqueDepartments.push(role.department);
    }
  });

  return uniqueDepartments;
});

// Filtrar habilidades por departamento seleccionado
const departmentSkills = computed(() => {
  if (!selectedDepartment.value) return [];
  return props.skills.filter(skill =>
    skill.department_id === selectedDepartment.value.id
  );
});

const handleDepartmentSelect = (department) => {
  selectedDepartment.value = department;
  selectedMainRole.value = null;
  form.main_role_id = '';
};

const handleRoleSelect = (role) => {
  selectedMainRole.value = role;
  form.main_role_id = role.id;
};

const submit = (skillsData) => {
  form.skills = skillsData;

  form.post(route(goTo("store")), {
    onSuccess: () => {
      // Redireccionar al index
    },
    onError: () => {
      // Mostrar mensaje de error
    },
  });
};

const goBack = () => {
  if (selectedMainRole.value) {
    selectedMainRole.value = null;
    form.main_role_id = '';
  } else if (selectedDepartment.value) {
    selectedDepartment.value = null;
  }
};

onMounted(() => {
  // Si tenemos rol seleccionado, asegurar que el departamento también esté seleccionado
  if (props.selectedRole && props.selectedRole.department) {
    selectedDepartment.value = props.selectedRole.department;
    selectedMainRole.value = props.selectedRole;
    form.main_role_id = props.selectedRole.id;
  }
});
</script>

<template>
  <DashboardLayout :title="transl('create.title')">
    <PageHeader>
      <Link :href="route(goTo('index'))">
        <GoogleIcon
          :title="$t('return')"
          class="btn-icon-primary"
          name="arrow_back"
          outline
        />
      </Link>
    </PageHeader>

    <div class="w-full pb-8">
      <div class="mt-8">
        <p v-text="transl('create.description')" />
      </div>
    </div>

    <div class="w-full">
      <!-- Navegación hacia atrás -->
      <div v-if="selectedDepartment || selectedMainRole" class="mb-6">
        <button
          @click="goBack"
          class="text-primary hover:underline flex items-center gap-2"
        >
          <GoogleIcon name="arrow_back" class="w-4 h-4" />
          <span v-if="selectedMainRole">Cambiar rol principal</span>
          <span v-else-if="selectedDepartment">Cambiar departamento</span>
        </button>
      </div>

      <!-- Paso 1: Selector de Departamento -->
      <DepartmentSelector
        v-if="!selectedDepartment"
        :departments="departments"
        @select="handleDepartmentSelect"
      />

      <!-- Paso 2: Selector de Rol Principal -->
      <MainRoleSelector
        v-else-if="selectedDepartment && !selectedMainRole"
        :selectedDepartment="selectedDepartment"
        :mainRoles="mainRoles"
        @select="handleRoleSelect"
      />

      <!-- Paso 3: Asignación de Habilidades -->
      <SkillAssignment
        v-else-if="selectedDepartment && selectedMainRole"
        :form="form"
        :skills="departmentSkills"
        :scores="scores"
        :selectedDepartment="selectedDepartment"
        :selectedMainRole="selectedMainRole"
        @submit="submit"
      />
    </div>
  </DashboardLayout>
</template>
