<template>
  <section-wrapper class="bg-background-3 pb-12">
    <section-container mobile-padding class="max-w-container">
      <div class="rounded-xl bg-white px-12 py-8">
        <h2 class="text-primary mb-10 text-[1.563rem] font-bold">
          Mes chauffeurs
        </h2>
        <ProgressBar
          v-if="loading"
          mode="indeterminate"
          class="mb-10"
          style="height: 6px"
        ></ProgressBar>
        <Message severity="error" v-if="error">{{ error }}</Message>

        <Message :sticky="false" life="3000" severity="success" v-if="success"
          >{{ success }}
        </Message>
        <OperatorForm @updated="fetchOperators" class="mb-10"></OperatorForm>

        <div v-if="operators" class="grid-cols-2 gap-10 md:grid">
          <OperatorForm
            :operator="operator"
            :key="operator.id"
            @updated="fetchOperators"
            v-for="operator in operators"
          >
          </OperatorForm>
        </div>
      </div>
    </section-container>
  </section-wrapper>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useAuthStore } from "../store/auth";
import _ from "lodash";

const { $api, $toast, $listen, $unListen } = useNuxtApp();
const authStore = useAuthStore();
const operators = ref([]);
const loading = ref(false);
const success = ref(null);
const error = ref(null);

import CitySelectField from "./form/CitySelectField.vue";
import OperatorForm from "./OperatorForm.vue";

const update = async () => {
  loading.value = true;
  error.value = null;
  success.value = null;
};

async function fetchOperators() {
  loading.value = true;
  try {
    operators.value = await $api.call("get", $api.route("me.operators.index"));
  } catch (e) {
    error.value = e;
    $toast.error(
      "Une erreur est survenue lors de la récupération des chauffeurs."
    );
  } finally {
    loading.value = false;
  }
}

onMounted(async () => {
  await fetchOperators();

  $listen("refresh-all", fetchOperators);
});

onBeforeUnmount(() => {
  $unListen("refresh-all", fetchOperators);
});
</script>
