<template>
  <q-card flat bordered class="new-notification-panel">
    <q-card-section>
      <div class="flex items-center gap-sm q-mb-md">
        <q-icon name="mdi-send-outline" size="20px" color="violet-normal" />
        <span class="text-body1 text-violet-normal text-weight-medium q-pl-sm">
          {{ $t('notification.new') }}
        </span>
      </div>

      <q-form ref="formRef" greedy>
        <DefaultInput
          v-model="form.title"
          :label="$t('notification.title_label')"
          :placeholder="$t('notification.title_placeholder')"
          :rules="[inputRules.required]"
          bg-color="violet-light"
          outlined
        />


        <DefaultInput
          v-model="form.message"
          :label="$t('notification.message_label')"
          :placeholder="$t('notification.message_placeholder')"
          :rules="[inputRules.required]"
          bg-color="violet-light"
          outlined
          class="q-pt-md"
        />

        <div class="row q-col-gutter-md q-mt-md">
          <div class="col-7">
            <div class="q-mb-md">
              <div class="text-caption text-grey-7 q-mb-sm">
                {{ $t('notification.recipients') }}
              </div>
              <div class="row q-gutter-sm">
                <q-chip
                  v-for="opt in recipientOptions"
                  :key="opt.value"
                  clickable
                  :color="form.recipient === opt.value ? 'violet-normal' : 'violet-light'"
                  :text-color="form.recipient === opt.value ? 'white' : 'violet-normal'"
                  :icon="opt.icon"
                  class="notification-chip"
                  @click="form.recipient = opt.value"
                >
                  {{ opt.label }}
                </q-chip>
              </div>
            </div>

            <div class="q-mb-md">
              <div class="text-caption text-grey-7 q-mb-sm">
                {{ $t('notification.by_position') }}
              </div>
              <div v-if="loadingPositions" class="flex items-center">
                <q-spinner color="violet-normal" size="18px" />
              </div>
              <div v-else class="row q-gutter-sm">
                <q-chip
                  v-for="pos in positions"
                  :key="pos.id"
                  clickable
                  :color="form.recipient_position_id === pos.id ? 'violet-normal' : 'violet-light'"
                  :text-color="form.recipient_position_id === pos.id ? 'white' : 'violet-normal'"
                  class="notification-chip"
                  @click="togglePosition(pos.id)"
                >
                  {{ pos.name }}
                </q-chip>
                <q-chip
                  clickable
                  color="negative"
                  text-color="white"
                  icon="mdi-close"
                  class="notification-chip"
                  @click="form.recipient_position_id = null"
                />
              </div>
            </div>

            <div>
              <div class="text-caption text-grey-7 q-mb-sm">
                {{ $t('notification.by_sector') }}
              </div>
              <div v-if="loadingSectors" class="flex items-center">
                <q-spinner color="violet-normal" size="18px" />
              </div>
              <div v-else class="row q-gutter-sm">
                <q-chip
                  v-for="sec in sectors"
                  :key="sec.id"
                  clickable
                  :color="form.recipient_sector_id === sec.id ? 'violet-normal' : 'violet-light'"
                  :text-color="form.recipient_sector_id === sec.id ? 'white' : 'violet-normal'"
                  class="notification-chip"
                  @click="toggleSector(sec.id)"
                >
                  {{ sec.name }}
                </q-chip>
                <q-chip
                  clickable
                  color="negative"
                  text-color="white"
                  icon="mdi-close"
                  class="notification-chip"
                  @click="form.recipient_sector_id = null"
                />
              </div>
            </div>
          </div>

          <div class="col-5 flex column items-end">
            <div class="text-caption text-grey-7 q-mb-sm">
              {{ $t('notification.media') }}
            </div>
            <DefaultFilePicker
              v-model="form.image"
              type="image"
              class="new-notification-panel__file-picker"
            />
          </div>
        </div>

        <q-btn
          unelevated
          class="btn-gradient full-width q-mt-md"
          :label="$t('notification.send').toUpperCase()"
          icon="mdi-send-outline"
          padding="12px"
          :loading="submitting"
          @click="onSubmit"
        />
      </q-form>
    </q-card-section>
  </q-card>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { permissionStore } from "src/stores/permission";
import { sendNotification } from "src/api/notification";
import { getPositions } from "src/api/position";
import { getSectors } from "src/api/sector";
import { useInputRules } from "src/composables/useInputRules";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultFilePicker from "src/components/defaults/DefaultFilePicker.vue";

const emit = defineEmits(["sent"]);

const $q = useQuasar();
const { t } = useI18n();
const permission_store = permissionStore();
const inputRules = useInputRules();

const formRef = ref(null);
const submitting = ref(false);

const form = ref({
  title: "",
  message: "",
  recipient: "todos",
  recipient_position_id: null,
  recipient_sector_id: null,
  image: null,
});

const recipientOptions = computed(() => [
  { value: "todos", label: t("notification.all"), icon: "mdi-earth" },
  { value: "associado", label: t("notification.recipient_associado"), icon: "mdi-account-group-outline" },
  { value: "parceiro", label: t("notification.recipient_parceiro"), icon: "mdi-handshake-outline" },
]);

const togglePosition = (id) => {
  form.value.recipient_position_id = form.value.recipient_position_id === id ? null : id;
};

const toggleSector = (id) => {
  form.value.recipient_sector_id = form.value.recipient_sector_id === id ? null : id;
};

const resetForm = () => {
  form.value = {
    title: "",
    message: "",
    recipient: "todos",
    recipient_position_id: null,
    recipient_sector_id: null,
    image: null,
  };
  formRef.value?.resetValidation();
};

const onSubmit = async () => {
  if (!permission_store.getAccess("notificacao", "add")) {
    $q.notify({ type: "negative", message: t("validation.permissions.add") });
    return;
  }

  const valid = await formRef.value?.validate();
  if (!valid) return;

  submitting.value = true;
  try {
    await sendNotification(form.value);
    $q.notify({ type: "positive", message: t("common.actions.save") + "!" });
    resetForm();
    emit("sent");
  } finally {
    submitting.value = false;
  }
};

const positions = ref([]);
const sectors = ref([]);
const loadingPositions = ref(true);
const loadingSectors = ref(true);

onMounted(async () => {
  await Promise.all([
    getPositions()
      .then((r) => { positions.value = r; })
      .finally(() => { loadingPositions.value = false; }),
    getSectors()
      .then((r) => { sectors.value = r; })
      .finally(() => { loadingSectors.value = false; }),
  ]);
});
</script>

<style scoped lang="scss">
.new-notification-panel {
  border-radius: 8px;

  &__file-picker {
    width: 100%;
    height: 180px;
  }
}

.notification-chip {
  border-radius: 20px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 8px !important;
}

.btn-gradient :deep(.q-icon) { color: white !important; }
</style>
