<template>
  <v-card width="100%">
    <v-toolbar>
      <v-row no-gutters class="fill-height px-6" align="center">
        <span class="font-weight-bold text-h5">
          {{ props.name }}
        </span>
      </v-row>
    </v-toolbar>
    <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0">
      <v-form v-model="validForm" :disabled="disable">
        <v-row no-gutters>
          <v-col cols="12" class="mt-4">
            <InputListGroupSelection
              v-model="definedModel"
              :items="props.permissions"
              variant="outlined"
              border="thin"
              :error-messages="errorMessages"
              :readonly="!edit"
              :hint="
                edit ? 'Select permissions' : 'Permissions are not editable'
              "
              persistent-hint
            />
          </v-col>

          <v-col v-if="edit" cols="12" class="my-2">
            <v-row no-gutters>
              <v-col cols="12" class="text-center">
                <span
                  class="text-none text-subtitle-2 font-weight-medium text-error"
                >
                  {{ message }}
                </span>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12" class="my-2">
            <v-row no-gutters>
              <v-col cols="12" class="text-center">
                <span
                  class="text-none text-subtitle-2 font-weight-medium text-error"
                >
                  {{ message }}
                </span>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-form>
    </v-card-text>

    <v-toolbar>
      <v-row class="px-6">
        <v-col v-if="!edit" cols="6">
          <v-btn
            block
            variant="text"
            class="text-none"
            size="large"
            @click="emit('cancel')"
          >
            Close
          </v-btn>
        </v-col>

        <v-col v-else cols="6">
          <v-btn
            block
            variant="text"
            class="text-none"
            size="large"
            @click="edit = false"
          >
            Cancel
          </v-btn>
        </v-col>

        <v-col v-if="!edit" cols="6">
          <v-btn
            block
            variant="flat"
            color="black"
            class="text-none"
            size="large"
            :disabled="!validForm"
            @click="edit = true"
          >
            Edit
          </v-btn>
        </v-col>

        <v-col v-else cols="6">
          <v-btn
            block
            variant="flat"
            color="black"
            class="text-none"
            size="large"
            :disabled="!validForm"
            @click="submit()"
          >
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>

<script setup lang="ts">
import useRole from '../composables/useRole';
import useUtils from '../composables/useUtils';

const definedModel = defineModel<Array<string>>({
  default: () => [],
});

const props = defineProps({
  name: {
    type: String,
    default: "Role",
  },
  id: {
    type: String,
    default: "",
  },
  permissions: {
    type: Object,
    default: () => ({}),
  },
  originalPermissions: {
    type: Object,
    default: () => ({}),
  },
});

const validForm = ref(false);
const message = ref("");
const disable = ref(false);

const emit = defineEmits(["success", "cancel"]);

const edit = defineModel<boolean>("edit", {
  default: false,
});

function equalListValue() {
  return JSON.stringify(definedModel.value) ===
    JSON.stringify(props.originalPermissions)
    ? "No changes made"
    : "";
}

const { requireListRule } = useUtils();

const errorMessages = computed(() => {
  const equalValue = equalListValue();
  if (edit.value && equalValue) {
    return equalValue;
  }

  const requiredValue = requireListRule(definedModel.value);
  if (requiredValue) {
    return requiredValue;
  }

  return "";
});

const { updatePermissionById } = useRole();

async function submit() {
  disable.value = true;
  try {
    await updatePermissionById(props.id, definedModel.value);
    emit("success");
  } catch (error: any) {
    message.value = error.response._data.message;
  } finally {
    disable.value = false;
  }
}
</script>
