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

import PrimaryButton from "@/Components/Dashboard/Button/Primary.vue";
import SecondaryButton from "@/Components/Dashboard/Button/Secondary.vue";
import PageHeader from "@/Components/Dashboard/PageHeader.vue";
import GoogleIcon from "@/Components/Shared/GoogleIcon.vue";
import DashboardLayout from "@/Layouts/DashboardLayout.vue";

// Componentes específicos para el flujo
import StepIndicator from "@/Components/App/StepIndicator.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: Object,
  skills: Object,
  scores: Object,
});

// Estado del flujo
const currentStep = ref(1);
const selectedDepartment = ref(null);
const selectedMainRole = ref(null);

const form = useForm({
  main_role_id: "",
  skill_id: "",
  scored_id: "",
});

// Datos computados
const uniqueDepartments = computed(() => {
  const deps = [];
  const seen = new Set();

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

  return deps;
});

// Métodos de navegación
const handleDepartmentSelect = (department) => {
  selectedDepartment.value = department;
  currentStep.value = 2;
};

const handleMainRoleSelect = (mainRole) => {
  selectedMainRole.value = mainRole;
  form.main_role_id = mainRole.id;
  currentStep.value = 3;
};

const goBack = () => {
  if (currentStep.value === 3) {
    selectedMainRole.value = null;
    form.main_role_id = "";
    form.skill_id = "";
    form.scored_id = "";
    currentStep.value = 2;
  } else if (currentStep.value === 2) {
    selectedDepartment.value = null;
    selectedMainRole.value = null;
    form.reset();
    currentStep.value = 1;
  }
};

const resetFlow = () => {
  selectedDepartment.value = null;
  selectedMainRole.value = null;
  form.reset();
  currentStep.value = 1;
};

const submit = (skillArray) => {
  const skillsData = skillArray.map(skill => ({
      skill_id: skill.skill_id,
      scored_id: skill.scored_id,
  }));
  form
    .transform((data) => ({
      main_role_id: data.main_role_id,
      skills: skillsData
    }))
    .post(route(goTo("store")), {
      onSuccess: () => {
        Notify.success(transl("create.onSuccess"));
        resetFlow();
      },
      onError: () => Notify.error(transl("create.onError")),
    });
};
</script>

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

    <!-- Indicador de progreso componentizado -->
    <div class="mt-6">
      <StepIndicator :current-step="currentStep" />
      <div class="flex justify-center gap-2">
        <SecondaryButton v-if="currentStep > 1" @click="goBack" type="button">
          <GoogleIcon name="keyboard_backspace" class="mr-2" />
          {{ $t("Regresar") }}
        </SecondaryButton>

        <SecondaryButton
          v-if="currentStep > 1"
          @click="resetFlow"
          type="button"
        >
          <GoogleIcon name="refresh" class="mr-2" />
          {{ $t("Inicio") }}
        </SecondaryButton>
      </div>
    </div>

    <!-- Componentes de pasos -->
    <DepartmentSelector
      v-if="currentStep === 1"
      :departments="uniqueDepartments"
      @select="handleDepartmentSelect"
    />

    <MainRoleSelector
      v-if="currentStep === 2"
      :main-roles="mainRoles"
      :selected-department="selectedDepartment"
      @select="handleMainRoleSelect"
    />

    <SkillAssignment
      v-if="currentStep === 3"
      :form="form"
      :skills="skills"
      :scores="scores"
      :selected-department="selectedDepartment"
      :selected-main-role="selectedMainRole"
      @submit="submit"
    />
  </DashboardLayout>
</template>
