<template>
  <div class="container-fluid py-4">
    <div class="row">
      <div class="col-lg-8 mx-auto">
        <client-group-form
          :initial-data="formData"
          :is-edit="isEdit"
          :loading="loading"
          @submit="handleSubmit"
          @cancel="handleCancel"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from "vue";
import { useRouter } from "vue-router";
import { useClientGroupStore } from "@/stores/clientGroupStore";
import { useNotificationStore } from "@/stores/notification";
import ClientGroupForm from "@/components/molecules/ClientGroup/ClientGroupForm.vue";

const props = defineProps({
  groupId: {
    type: [String, Number],
    default: null,
  },
});

const router = useRouter();
const clientGroupStore = useClientGroupStore();
const notificationStore = useNotificationStore();

const formData = ref({
  name: "",
  description: "",
  clients: [],
});
const loading = ref(false);
const isEdit = ref(!!props.groupId);

onMounted(async () => {
  try {
    const group = props.groupId
      ? await clientGroupStore.fetchClientGroup(props.groupId)
      : null;

    if (group) {
      formData.value = {
        name: group.name,
        description: group.description || "",
        clients: group.clients || [],
      };
    }
  } catch (error) {
    notificationStore.error(
      "Erreur",
      "Impossible de charger le groupe",
      3000
    );

    try {
      router.push("/clients/groups");
    } catch (navigationError) {
      console.error(navigationError);
    }
  }
});

const handleSubmit = async (data) => {
  loading.value = true;
  try {
    if (isEdit.value) {
      await clientGroupStore.updateClientGroup({
        id: props.groupId,
        ...data,
      });
      notificationStore.success(
        "Groupe mis à jour",
        "Le groupe a été mis à jour avec succès",
        3000
      );
    } else {
      await clientGroupStore.createClientGroup(data);
      notificationStore.success(
        "Groupe créé",
        "Le groupe a été créé avec succès",
        3000
      );
    }
    router.push("/clients/groups");
  } catch (error) {
    notificationStore.error(
      "Erreur",
      isEdit.value
        ? "Impossible de mettre à jour le groupe"
        : "Impossible de créer le groupe",
      3000
    );
  } finally {
    loading.value = false;
  }
};

const handleCancel = () => {
  router.push("/clients/groups");
};
</script>
