<template>
  <div class="q-pa-md">
    <div class="row q-col-gutter-md">
      <!-- Coluna esquerda: lista -->
      <div class="col-12 col-md-5">
        <div class="row justify-between items-center q-mb-md">
          <span class="text-subtitle1 text-weight-medium">Histórico</span>
          <q-btn
            icon="add"
            color="primary-2"
            style="height: 40px; width: 40px; border-radius: 8px"
            :disable="!unitId"
            @click="openDialog(null)"
          />
        </div>

        <div v-if="loading" class="row justify-center q-pa-xl">
          <q-spinner color="primary" size="40px" />
        </div>

        <template v-else>
          <div v-if="histories.length === 0" class="text-center text-grey-6 q-pa-xl">
            <q-icon name="mdi-history" size="48px" color="grey-4" />
            <div class="q-mt-sm">Nenhum histórico registrado.</div>
          </div>

          <q-list v-else separator>
            <q-item
              v-for="(item, index) in histories"
              :key="item.id"
              clickable
              :active="selectedIndex === index"
              active-class="history-item-active"
              @click="selectedIndex = index"
            >
              <q-item-section avatar>
                <q-icon name="mdi-text-box-outline" color="primary-2" size="md" />
              </q-item-section>

              <q-item-section>
                <q-item-label class="ellipsis" style="max-width: 180px">
                  {{ item.title }}
                </q-item-label>
                <q-item-label caption>
                  {{ formatDate(item.created_at) }}
                </q-item-label>
              </q-item-section>

              <q-item-section side>
                <div class="row q-gutter-xs">
                  <q-btn flat round dense icon="edit" color="grey-7" size="sm" @click.stop="openDialog(item)" />
                  <q-btn flat round dense icon="delete" color="negative" size="sm" @click.stop="onRemove(item, index)" />
                </div>
              </q-item-section>
            </q-item>
          </q-list>
        </template>
      </div>

      <!-- Coluna direita: pré-visualização -->
      <div class="col-12 col-md-7">
        <div class="preview-box q-pa-md">
          <div
            v-if="selectedIndex === null || !histories[selectedIndex]"
            class="flex flex-center full-height text-grey-5"
            style="min-height: 400px"
          >
            <div class="column items-center q-gutter-sm">
              <q-icon name="mdi-history" size="64px" color="grey-3" />
              <span>Selecione um item para visualizar</span>
            </div>
          </div>

          <div v-else>
            <div class="row justify-between items-start q-mb-sm">
              <p class="text-weight-medium text-subtitle1 q-mb-none">
                {{ histories[selectedIndex].title }}
              </p>
              <q-badge
                v-if="histories[selectedIndex].visible_to_franchisee"
                color="positive"
                label="Visível ao franqueado"
              />
            </div>
            <p class="text-caption text-grey-6 q-mb-md">
              {{ formatDate(histories[selectedIndex].created_at) }}
            </p>
            <p class="text-grey-8" style="white-space: pre-wrap">
              {{ histories[selectedIndex].content }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { getHistoriesByUnit, deleteHistory } from "src/api/unit_history";
import AddEditHistoryDialog from "src/pages/unit/components/AddEditHistoryDialog.vue";

const props = defineProps({
  unitId: { type: Number, default: null },
});

const $q = useQuasar();
const histories = ref([]);
const selectedIndex = ref(null);
const loading = ref(false);

async function fetchHistories() {
  if (!props.unitId) return;
  loading.value = true;
  try {
    histories.value = await getHistoriesByUnit(props.unitId);
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
}

function openDialog(item) {
  $q.dialog({
    component: AddEditHistoryDialog,
    componentProps: { history: item, unitId: props.unitId },
  }).onOk((result) => {
    if (item) {
      const idx = histories.value.findIndex((h) => h.id === item.id);
      if (idx !== -1) histories.value.splice(idx, 1, result);
    } else {
      histories.value.unshift(result);
      selectedIndex.value = 0;
    }
  });
}

function onRemove(item, index) {
  $q.dialog({
    title: "Remover histórico",
    message: `Deseja remover o item "${item.title}"?`,
    ok: { color: "negative", label: "Remover" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    try {
      await deleteHistory(item.id);
      histories.value.splice(index, 1);
      if (selectedIndex.value === index) selectedIndex.value = null;
      else if (selectedIndex.value > index) selectedIndex.value--;
    } catch (e) {
      console.error(e);
    }
  });
}

function formatDate(dateStr) {
  if (!dateStr) return "";
  return new Date(dateStr).toLocaleDateString("pt-BR");
}

onMounted(fetchHistories);
</script>

<style scoped>
.preview-box {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  min-height: 400px;
}

.history-item-active {
  background-color: rgba(255, 131, 64, 0.08);
}

.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
