<script setup>
import ActionButton from "@/components/ActionButton.vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import HeroSection from "@/components/HeroSection.vue";
import ReusableDataTable from "@/components/ReusableDataTable.vue";
import SearchBox from "@/components/SearchBox.vue";
import { useAuthStore } from "@/stores/authStore";
import { usePagesStore } from "@/stores/pagesStore";
import { storeToRefs } from "pinia";
import { computed, onActivated, onMounted, ref } from "vue";
import { useRouter } from "vue-router";

const authStore = useAuthStore();
const { user: authUser } = storeToRefs(authStore);

// ─────────────────────────────
// Constants
// ─────────────────────────────
const DEFAULT_ROWS = 10;
const SEARCH_DEBOUNCE = 500;

// ========== COLUMNS CONFIG (Avatar Title + Separate Slug) ==========
const columns = [
  {
    field: "title",
    header: "Title",
    sortable: true,
    style: { width: "220px" },
    // ✅ KEEP AVATAR LOOK (First Letter)
    template: "user",
    // Removed subField: "slug" so it doesn't show double
  },
  {
    field: "slug",
    header: "Slug",
    sortable: true,
    style: { width: "200px" },
    template: "custom",
    // ✅ RESTORED SLUG COLUMN
    customHTML: (rowData) =>
      `<div class="dt-table-slug">
         <i class="pi pi-link dt-table-slug__icon"></i>
         <span>/${rowData.slug}</span>
       </div>`,
  },
  {
    field: "franchise_name",
    header: "Author",
    sortable: true,
    style: { width: "180px" },
    template: "custom",
    customHTML: (rowData) =>
      `<div class="flex items-center gap-2">
         <i class="pi pi-user text-slate-400"></i>
         <span>${rowData.franchise_name || "System"}</span>
       </div>`,
  },
  {
    field: "created_at",
    header: "Date Created",
    sortable: true,
    type: "datetime",
    style: { width: "180px" },
  },
  {
    field: "status",
    header: "Status",
    sortable: true,
    template: "badge", // Automatically Blue/White
    style: { width: "120px" },
  },
];

const actions = [
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Page",
    severity: "info",
    action: "edit",
    to: (row) => `/pages/edit/${row.id}`,
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Page",
    severity: "danger",
    action: "delete",
    condition: (rowData) => {
      if (authUser.value?.data?.role === "super_admin") {
        return true;
      }
      if (typeof rowData.can_delete === "boolean") {
        return rowData.can_delete;
      }
      return false;
    },
  },
];

// ─────────────────────────────
// Store & Router
// ─────────────────────────────
const router = useRouter();
const pagesStore = usePagesStore();
const { pages, total, loading, error } = storeToRefs(pagesStore);
const { fetchPages, deletePageById } = pagesStore;

// ─────────────────────────────
// Table State
// ─────────────────────────────
const lazyParams = ref({
  page: 1,
  rows: DEFAULT_ROWS,
  sortField: "",
  sortOrder: 0,
  search: "",
});

const pagesData = computed(() =>
  Array.isArray(pages.value) ? pages.value : [],
);

// ─────────────────────────────
// Handlers
// ─────────────────────────────
async function loadPages() {
  try {
    await fetchPages({ ...lazyParams.value });
  } catch {
    console.error("Failed to load pages");
  }
}

function onPage(event) {
  lazyParams.value.page = event.page + 1;
  lazyParams.value.rows = event.rows;
  loadPages();
}

function onSort(event) {
  lazyParams.value.sortField = event.sortField;
  lazyParams.value.sortOrder = Number(event.sortOrder || 0);
  loadPages();
}

let searchTimeout = null;
function onSearch() {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    lazyParams.value.page = 1;
    loadPages();
  }, SEARCH_DEBOUNCE);
}

// ─────────────────────────────
// Navigation
// ─────────────────────────────
function addPage() {
  router.push("/pages/add");
}

function onActionClick({ action, rowData }) {
  if (action.action === "edit") {
    router.push(`/pages/edit/${rowData.id}`);
  } else if (action.action === "delete") {
    openDeleteDialog(rowData);
  }
}

// ─────────────────────────────
// Delete Flow
// ─────────────────────────────
const deleteDialog = ref(false);
const selectedId = ref(null);
const selectedDeleteRow = ref(null);

const deleteConfirmMessage = computed(() => {
  const row = selectedDeleteRow.value;
  const role = authUser.value?.data?.role;
  if (
    role !== "super_admin" &&
    row?.is_global &&
    row?.can_delete === true
  ) {
    return "Remove your franchise override for this global page? Your site will use the super-admin page content again. This does not delete the global page.";
  }
  return "Are you sure you want to delete this page? This action cannot be undone.";
});

function openDeleteDialog(rowData) {
  selectedDeleteRow.value = rowData;
  selectedId.value = rowData?.id ?? null;
  deleteDialog.value = true;
}

async function confirmDelete() {
  const response = await deletePageById(selectedId.value);
  if (response.status) {
    deleteDialog.value = false;
    selectedDeleteRow.value = null;
    loadPages();
  }
}

function cancelDeleteDialog() {
  deleteDialog.value = false;
  selectedDeleteRow.value = null;
}

// ─────────────────────────────
// Lifecycle
// ─────────────────────────────
onMounted(loadPages);
onActivated(loadPages);
</script>

<template>
  <div class="pages-page-container">
    <HeroSection
      title="All Pages"
      subtitle="Manage and organize your site pages"
      icon="pi pi-file"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="search-section">
            <SearchBox
              v-model="lazyParams.search"
              placeholder="Search pages..."
              :loading="loading"
              size="medium"
              @search="onSearch"
              @clear="
                () => {
                  lazyParams.search = '';
                  onSearch();
                }
              "
              class="w-full"
            />
          </div>

          <div class="action-buttons">
            <ActionButton
              label="Add Page"
              icon="pi pi-plus"
              class="create-button"
              @click="addPage"
            />
          </div>
        </div>

        <div class="table-container">
          <ReusableDataTable
            :data="pagesData"
            :columns="columns"
            :actions="actions"
            :loading="loading"
            :total-records="total"
            :rows="lazyParams.rows"
            :sort-field="lazyParams.sortField"
            :sort-order="lazyParams.sortOrder"
            :lazy="true"
            :paginator="true"
            :rows-per-page-options="[10, 25, 50, 100]"
            data-key="id"
            @page="onPage"
            @sort="onSort"
            @action-click="onActionClick"
          />
        </div>
      </div>
    </div>
  </div>

  <ConfirmationDialog
    v-model:visible="deleteDialog"
    :title="
      authUser?.data?.role !== 'super_admin' &&
      selectedDeleteRow?.is_global &&
      selectedDeleteRow?.can_delete
        ? 'Remove franchise override'
        : 'Delete Page'
    "
    :message="deleteConfirmMessage"
    :item="null"
    :loading="false"
    @confirm="confirmDelete"
    @cancel="cancelDeleteDialog"
  />
</template>

<style scoped>
/* ========== MAIN PAGE BACKGROUND ========== */

/* ========== CONTENT WRAPPER ========== */
.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0;
  position: relative;
}

/* page-content + toolbar: styled globally in _listing-layout.scss */

/* ========== TOOLBAR ========== */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.search-section {
  flex: 1;
  max-width: 400px;
}

/* ========== BUTTONS ========== */
.create-button {
  background-color: #003b6f !important;
  border: 1px solid #003b6f !important;
  color: white !important;
  padding: 0.6rem 1.25rem !important;
  font-weight: 500 !important;
  font-size: 0.9rem !important;
  border-radius: 8px !important;
  box-shadow: 0 2px 4px rgba(0, 59, 111, 0.1) !important;
  transition: all 0.2s ease !important;
}

.create-button:hover {
  background-color: #002a50 !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0, 59, 111, 0.2) !important;
}

/* Table merge: _listing-layout.scss */

/* ========== UTILITIES FOR CUSTOM HTML ========== */
:deep(.flex) {
  display: flex;
}
:deep(.items-center) {
  align-items: center;
}
:deep(.gap-2) {
  gap: 0.5rem;
}
:deep(.text-slate-400) {
  color: #94a3b8;
}
:deep(.font-mono) {
  font-family: monospace;
}
:deep(.text-xs) {
  font-size: 0.75rem;
}
:deep(.text-sm) {
  font-size: 0.875rem;
}
:deep(.text-slate-500) {
  color: #64748b;
}
:deep(.opacity-70) {
  opacity: 0.7;
}

/* ========== RESPONSIVE ========== */
@media (max-width: 768px) {
  .content-wrapper {
    margin-top: 0;
    padding: 0;
  }
  .toolbar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  .search-section {
    max-width: 100%;
  }
  .create-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
