<template>
  <ReusableDialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    :title="`Review Pages from ${franchisee?.franchisee?.name || franchisee?.name}`"
    :max-width="modalStyles.maxWidth"
    :persistent="true"
    :fullscreen-on-mobile="false"
  >
    <!-- Always render main modal content -->
    <div class="modal-content" style="position: relative">
      <!-- Overlay loader: appears above main page area, not header -->
      <div v-if="loadingPages" class="modal-loading-overlay">
        <img src="/images/loader.gif" alt="Loading..." />
      </div>
      <!-- Actual modal body (blurred if loading) -->
      <div :class="{ blurred: loadingPages }">
        <div class="modal-subtitle">
          <p>{{ pendingPagesForFranchisee.length }} page(s) pending review</p>
        </div>
        <div v-if="pendingPagesForFranchisee.length > 0" class="pages-list">
          <div
            v-for="page in pendingPagesForFranchisee"
            :key="page.submission_id"
            class="page-card"
          >
            <div class="page-info">
              <h4 class="page-title">
                {{ page.title }} ({{ page.language_code }})
              </h4>
              <div class="page-details">
                <div class="page-url">
                  <strong>Preview URL:</strong>
                  <a
                    :href="getPreviewUrl(page)"
                    target="_blank"
                    class="preview-link"
                    rel="noopener"
                  >
                    <span class="preview-text">{{ getPreviewUrl(page) }}</span>
                    <i class="pi pi-external-link"></i>
                  </a>
                </div>
                <div class="page-meta">
                  <small>Page ID: {{ page.page_id }}</small
                  ><br />
                  <small>Language: {{ page.language_code }}</small
                  ><br />
                  <small>Slug: {{ page.slug }}</small>
                </div>
              </div>
            </div>
            <div class="page-actions">
              <Button
                label="Approve"
                icon="pi pi-check"
                severity="success"
                size="small"
                :loading="processingSubmissionId === page.submission_id"
                :disabled="isProcessing"
                @click="handleApprovePage(page.submission_id, page.title)"
              />
              <Button
                label="Reject"
                icon="pi pi-times"
                class="reject-button"
                outlined
                size="small"
                :loading="processingSubmissionId === page.submission_id"
                :disabled="isProcessing"
                @click="handleRejectPage(page.submission_id, page.title)"
              />
            </div>
          </div>
        </div>
        <div v-else class="no-pages">
          <div class="no-pages-content">
            <i
              class="pi pi-check-circle"
              style="font-size: 3rem; color: #10b981; margin-bottom: 1rem"
            ></i>
            <p>No pending pages to review.</p>
            <small class="text-muted"
              >All pages have been processed successfully.</small
            >
          </div>
        </div>
      </div>
    </div>
    <!-- Actions slot remains outside loader/content -->
    <template #actions>
      <div class="flex align-items-center justify-content-end gap-3">
        <Button
          label="Close"
          icon="pi pi-times"
          class="theme-button-outline"
          :disabled="isProcessing"
          @click="handleClose"
        />
        <Button
          v-if="pendingPagesForFranchisee.length > 0"
          label="Approve All"
          icon="pi pi-check-circle"
          class="btn-approve-all"
          size="small"
          :loading="processingAll"
          :disabled="isProcessing"
          @click="handleApproveAll"
        />
      </div>
    </template>
  </ReusableDialog>
</template>

<script setup>
import { computed, watch } from "vue";
import { useApprovalStore } from "@/stores/approvalStore";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  franchisee: {
    type: Object,
    default: null,
  },
});
const emit = defineEmits([
  "update:visible",
  "page-approved",
  "page-rejected",
  "all-approved",
]);
const approvalStore = useApprovalStore();
const pendingPagesForFranchisee = computed(() => {
  if (!props.franchisee) return [];
  const franchiseeId = props.franchisee.franchisee_id || props.franchisee.id;
  return approvalStore.franchiseePages.filter(
    (page) => page.franchisee_id === franchiseeId,
  );
});
const processingSubmissionId = computed(
  () => approvalStore.processingSubmissionId,
);
const processingAll = computed(() => approvalStore.processingAll);
const isProcessing = computed(() => approvalStore.isProcessing);
const basePreviewUrl = import.meta.env.VITE_PREVIEW_URL || "";
const getPreviewUrl = (page) => {
  const parts = [
    page.franchisee_id ? `franchiseeId=${page.franchisee_id}` : "",
    page.slug ? `slug=${page.slug}` : "",
    page.page_id ? `pageId=${page.page_id}` : "",
  ]
    .filter(Boolean)
    .join("&");
  return parts ? `${basePreviewUrl}?${parts}` : basePreviewUrl;
};
const loadingPages = computed(() => approvalStore.loading);
const modalStyles = computed(() => {
  const baseStyles = {
    maxWidth: "900px",
    borderRadius: "12px",
  };
  if (loadingPages.value) {
    return {
      ...baseStyles,
      width: "80vw",
      height: "70vh",
    };
  }
  if (pendingPagesForFranchisee.value.length === 0) {
    return {
      ...baseStyles,
      width: "450px",
      height: "auto",
      minHeight: "300px",
    };
  } else {
    return {
      ...baseStyles,
      width: "80vw",
      height: "70vh",
    };
  }
});
const handleClose = () => {
  emit("update:visible", false);
};
const handleApprovePage = async (submissionId, title) => {
  try {
    await approvalStore.approvePage(submissionId);
    emit("page-approved", submissionId);
  } catch (error) {
    // Error handled in store
  }
};
const handleRejectPage = async (submissionId, title) => {
  try {
    await approvalStore.rejectPage(submissionId);
    emit("page-rejected", submissionId);
  } catch (error) {
    // Error handled in store
  }
};
const handleApproveAll = async () => {
  if (!props.franchisee) return;
  try {
    const franchiseeId = props.franchisee.franchisee_id || props.franchisee.id;
    const pagesCount = pendingPagesForFranchisee.value.length;
    await approvalStore.approveAllPages(franchiseeId);
    emit("all-approved", franchiseeId, pagesCount);
  } catch (error) {
    // Error handled in store
  }
};
watch(
  () => props.franchisee,
  async (newFranchisee) => {
    if (newFranchisee && props.visible) {
      try {
        const franchiseeId = newFranchisee.franchisee_id || newFranchisee.id;
        await approvalStore.fetchPendingPages(franchiseeId);
      } catch (error) {}
    }
  },
  { immediate: true },
);
watch(
  () => props.visible,
  async (isVisible) => {
    if (isVisible && props.franchisee) {
      try {
        const franchiseeId =
          props.franchisee.franchisee_id || props.franchisee.id;
        await approvalStore.fetchPendingPages(franchiseeId);
      } catch (error) {}
    }
  },
);
</script>

<style scoped>
.modal-content {
  padding: 24px 28px 20px 28px;
  background: #fff;
  border-radius: 12px;
  box-sizing: border-box;
  position: relative; /* For loader overlay */
}
.modal-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.6);
  z-index: 2;
}
.modal-loading-overlay img {
  width: 60px;
  height: 60px;
}
.blurred {
  filter: blur(2px);
  pointer-events: none;
  user-select: none;
}
.modal-subtitle {
  margin-bottom: 1.25rem;
}
.modal-subtitle p {
  color: #64748b;
  margin: 0;
  font-size: 1rem;
}
.pages-list {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
  min-height: 100px;
  margin: 0;
}
.page-card {
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 59, 111, 0.05);
  background: #fff;
  padding: 1.25rem 1.5rem;
  margin: 0;
  transition:
    box-shadow 0.15s,
    border-color 0.15s;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.page-card:hover {
  border-color: #004d8f;
  box-shadow: 0 4px 16px rgba(0, 59, 111, 0.1);
}
.no-pages {
  text-align: center;
  padding: 2.5rem 1.75rem;
  color: #64748b;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 180px;
}
.no-pages-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
}
.no-pages-content p {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: #475569;
}
.no-pages-content small {
  color: #94a3b8;
  font-size: 0.95rem;
}
.page-info {
  flex: 1;
}
.page-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #003b6f;
  margin: 0 0 0.75rem 0;
}
.page-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.page-url {
  margin-bottom: 0.5rem;
}
.preview-link {
  color: #003b6f;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  font-family: monospace;
  background: #f1f5f9;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
  margin-left: 0.5rem;
}
.preview-link:hover {
  background: #e2e8f0;
  color: #002749;
}
.preview-text {
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.page-meta {
  color: #64748b;
  font-size: 0.875rem;
}
.page-actions {
  display: flex;
  flex-direction: column;
  gap: 0.7rem;
  margin-left: 1.2rem;
}
.btn-approve-all {
  background-color: #003b6f;
  color: white;
  border: none;
  transition: background-color 0.18s;
}
.btn-approve-all:hover {
  background-color: #002749;
}
:deep(.p-button-success) {
  background-color: #003b6f !important;
  border-color: #003b6f !important;
}
:deep(.p-button) {
  background-color: #003b6f !important;
  border-color: #003b6f !important;
  color: #fff !important;
}
:deep(.p-button.p-button-outlined),
:deep(.reject-button),
:deep(.theme-button-outline) {
  background-color: transparent !important;
  color: #003b6f !important;
  border-color: #003b6f !important;
}
.pages-list::-webkit-scrollbar {
  width: 6px;
}
.pages-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}
.pages-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}
.pages-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
@media (max-width: 768px) {
  .modal-content {
    padding: 12px 6px;
    border-radius: 8px;
  }
  .page-card {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
    border-radius: 7px;
  }
  .page-actions {
    flex-direction: row;
    margin-left: 0;
  }
  .no-pages {
    padding: 1.25rem 0.5rem;
    min-height: 130px;
  }
}
</style>
