<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 1100px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader
          :title="ticket ? 'Editar Ticket' : 'Novo Ticket'"
          @close="onDialogCancel"
        />

        <q-form ref="formRef" @submit="onOKClick">
          <q-card-section class="q-pt-sm">
            <CustomTabComponent
              v-if="ticket?.id"
              v-model:active-tab="currentTab"
              :tabs="tabs"
              class="q-mb-md"
            />

            <!-- Tab: Ticket -->
            <div v-show="currentTab === 'ticket'">
              <div class="row q-col-gutter-sm">
                <DefaultInput
                  v-model="form.title"
                  label="Título da Tarefa"
                  class="col-12"
                />

                <DefaultSelect
                  v-model="form.severity"
                  label="Prioridade"
                  :options="priorityOptions"
                  emit-value
                  map-options
                  class="col-6"
                />

                <DefaultInput
                  :model-value="user?.name"
                  label="Responsável"
                  disable
                  class="col-6"
                />

                <DefaultSelect
                  v-model="form.scope"
                  label="Destino"
                  :options="unitTargetOptions"
                  emit-value
                  map-options
                  class="col-6"
                />

                <DefaultInput
                  v-model="form.sector"
                  label="Setor"
                  class="col-6"
                />

                <UnitSelect
                  v-if="form.scope === 'specific'"
                  v-model="selectedUnit"
                  class="col-6"
                />

                <DefaultInput
                  v-model="form.description"
                  label="Descrição"
                  type="textarea"
                  class="col-12"
                />
              </div>
            </div>

            <!-- Tab: Comentários -->
            <div v-show="currentTab === 'comentarios'">
              <div class="flex justify-end q-mb-sm">
                <q-btn
                  color="primary"
                  icon="mdi-plus"
                  unelevated
                  style="width: 40px; height: 40px"
                  @click="onAddComment"
                />
              </div>
              <div style="max-height: 340px; overflow-y: auto; display: flex; flex-direction: column; gap: 8px;">
                <TicketCommentCard
                  v-for="comment in mockComments"
                  :key="comment.id"
                  :reply="comment.reply"
                  :created-at="comment.created_at"
                  :user-name="comment.user_name"
                />
              </div>
            </div>
          </q-card-section>

          <q-card-actions align="right" class="q-px-md q-pb-md">
            <q-btn
              outline
              color="primary"
              label="Cancelar"
              @click="onDialogCancel"
            />
            <q-btn
              v-if="ticket?.id && ticket?.status === 'in_progress'"
              outline
              color="negative"
              label="Encerrar"
              @click="onCloseTicket"
            />
            <q-btn
              v-if="!ticket?.id || ticket?.status === 'in_progress'"
              color="primary"
              label="Salvar"
              type="submit"
              :loading="loading"
            />
          </q-card-actions>
        </q-form>
      </q-card>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { useDialogPluginComponent } from "quasar";

import CustomTabComponent from "src/components/shared/CustomTabComponent.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import UnitSelect from "src/components/selects/UnitSelect.vue";
import TicketCommentCard from "./TicketCommentCard.vue";
import { userStore } from "src/stores/user";
import { useQuasar } from "quasar";
import { createSupportTicket, updateSupportTicket } from "src/api/support_ticket";
import CloseTicketDialog from "./CloseTicketDialog.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { ticket } = defineProps({
  ticket: {
    type: Object,
    default: null,
  },
});

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const $q = useQuasar();
const { user } = userStore();

const formRef = ref(null);
const loading = ref(false);
const currentTab = ref("ticket");
const selectedUnit = ref(ticket?.unit_id ? { value: ticket.unit_id } : null);

const tabs = computed(() => {
  const base = [{ name: "ticket", label: "Ticket" }];
  if (ticket?.id) base.push({ name: "comentarios", label: "Comentários" });
  return base;
});

const mockComments = [
  {
    id: 1,
    reply: "Já identifiquei o problema, estou trabalhando na correção.",
    created_at: "18/05/2026 09:14",
    user_name: "Ana Souza",
  },
  {
    id: 2,
    reply: "Correção aplicada em ambiente de homologação, aguardando validação.",
    created_at: "18/05/2026 11:30",
    user_name: "Carlos Mendes",
  },
  {
    id: 3,
    reply: "Validado com sucesso em homologação, subindo para produção.",
    created_at: "18/05/2026 14:05",
    user_name: "Ana Souza",
  },
  {
    id: 4,
    reply: "Deploy concluído. Por favor confirme se o problema foi resolvido.",
    created_at: "18/05/2026 15:48",
    user_name: "Carlos Mendes",
  },
];

const priorityOptions = [
  { label: "Alta", value: "alta" },
  { label: "Normal", value: "normal" },
  { label: "Baixa", value: "baixa" },
];

const unitTargetOptions = [
  { label: "Todas as Unidades", value: "all" },
  { label: "Suporte Interno", value: "internal" },
  { label: "Unidade Específica", value: "specific" },
];

const form = ref({
  title:       ticket?.title ?? null,
  severity:    ticket?.severity ?? null,
  scope:       ticket?.scope ?? null,
  sector:      ticket?.sector ?? null,
  description: ticket?.description ?? null,
});

const buildPayload = () => ({
  title:       form.value.title,
  severity:    form.value.severity,
  scope:       form.value.scope,
  sector:      form.value.sector || null,
  description: form.value.description || null,
  unit_id:     form.value.scope === "specific" ? (selectedUnit.value?.value ?? null) : null,
});

const onAddComment = () => {
  // TODO: implement add comment
};

const onCloseTicket = () => {
  $q.dialog({
    component: CloseTicketDialog,
    componentProps: { ticket },
  }).onOk(() => {
    onDialogOK(true);
  });
};

const onOKClick = async () => {
  loading.value = true;
  try {
    const payload = buildPayload();
    if (ticket?.id) {
      await updateSupportTicket(ticket.id, payload);
    } else {
      await createSupportTicket(payload);
    }
    onDialogOK(true);
  } finally {
    loading.value = false;
  }
};
</script>
