<script setup>
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import ReusableDataTable from "@/components/ReusableDataTable.vue";
import HeroSection from "@/components/HeroSection.vue";
import TemplateForm from "@/pages/all-pages/templateForm.vue";
import { usePagesTemplateStore } from "@/stores/pageTemplateStore";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";

const pagesStore = usePagesTemplateStore();
const { templates, total, loading, saving, deleting } = storeToRefs(pagesStore);

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

const lazyParams = ref({
  page: 1,
  rows: 10,
  sortField: "",
  sortOrder: 0,
  search: "",
});

const showTemplateForm = ref(false);
const showDeleteDialog = ref(false);
const formMode = ref("create");
const selectedTemplate = ref(null);

const columns = [
  { field: "name", header: "Template Name", sortable: false },
  { field: "date", header: "Date", sortable: false, type: "datetime" },
];

const actions = [
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Template",
    severity: "info",
    action: "edit",
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Template",
    severity: "danger",
    action: "delete",
  },
];

onMounted(() => {
  loadTemplatesLazy();
});

const loadTemplatesLazy = async () => {
  await pagesStore.fetchTemplates();
};

const onPage = (event) => {
  lazyParams.value.page = event.page + 1;
  lazyParams.value.rows = event.rows;
  loadTemplatesLazy();
};

const onSort = (event) => {
  lazyParams.value.sortField = event.sortField;
  lazyParams.value.sortOrder = event.sortOrder;
  lazyParams.value.page = 1;
  loadTemplatesLazy();
};

const handleSearch = (term) => {
  lazyParams.value.search = term;
  lazyParams.value.page = 1;
  loadTemplatesLazy();
};

const createTemplate = () => {
  formMode.value = "create";
  selectedTemplate.value = null;
  showTemplateForm.value = true;
};

const editTemplate = (template) => {
  formMode.value = "edit";
  selectedTemplate.value = template;
  showTemplateForm.value = true;
};

const confirmDeleteTemplate = (template) => {
  selectedTemplate.value = template;
  showDeleteDialog.value = true;
};

const handleSaveTemplate = async (formData) => {
  try {
    if (formMode.value === "create") {
      await pagesStore.addTemplate(formData);
    } else {
      await pagesStore.updateTemplate(selectedTemplate.value.id, formData);
    }
    showTemplateForm.value = false;
    loadTemplatesLazy();
  } catch (err) {
    // Error toast handled by store
  }
};

const handleDeleteTemplate = async () => {
  try {
    await pagesStore.deleteTemplateById(selectedTemplate.value.id);
    showDeleteDialog.value = false;
    loadTemplatesLazy();
  } catch (err) {
    // Error toast handled by store
  }
};

const onActionClick = ({ action, rowData }) => {
  if (action.action === "edit") {
    editTemplate(rowData);
  } else if (action.action === "delete") {
    confirmDeleteTemplate(rowData);
  }
};
</script>

<template>
  <div class="templates-page-container">
    <!-- Hero Section Component -->
    <HeroSection
      title="All Templates"
      subtitle="Manage your page templates and layouts"
      icon="pi pi-clone"
    />

    <!-- Main Content Card (Overlapping) -->
    <div class="content-wrapper">
      <div class="page-content">
        <!-- Toolbar -->
        <div class="toolbar">
          <!-- Add Button -->
          <div class="action-buttons">
            <Button
              label="Add Template"
              icon="pi pi-plus"
              @click="createTemplate"
              class="create-button"
            />
          </div>
        </div>

        <!-- Data Table -->
        <ReusableDataTable
          :data="templatesData"
          :columns="columns"
          :actions="actions"
          :loading="loading"
          :total-records="total"
          :rows="lazyParams.rows"
          :sort-field="lazyParams.sortField"
          :sort-order="lazyParams.sortOrder"
          :lazy="true"
          :paginator="false"
          table-class="dt-table"
          data-key="id"
          @page="onPage"
          @sort="onSort"
          @action-click="onActionClick"
        />
      </div>
    </div>

    <!-- Template Form -->
    <TemplateForm
      :visible="showTemplateForm"
      @update:visible="(val) => (showTemplateForm = val)"
      :template="selectedTemplate"
      :mode="formMode"
      :loading="saving"
      @save="handleSaveTemplate"
    />

    <!-- Delete Confirmation -->
    <ConfirmationDialog
      v-model:visible="showDeleteDialog"
      title="Delete Template"
      :message="`Are you sure you want to delete '${selectedTemplate?.name}'?`"
      :loading="deleting"
      @confirm="handleDeleteTemplate"
    />
  </div>
</template>

<style scoped>
.templates-page-container {
  background: #f8fafc;
  min-height: 100vh;
  padding-bottom: 3rem;
}

.page-header {
  margin-bottom: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 0.5rem 0;
}

.page-subtitle {
  color: #64748b;
  font-size: 1rem;
  margin: 0;
}

/* ========== CONTENT WRAPPER - Creates Overlap Effect ========== */
.content-wrapper {
  max-width: 1400px;
  margin: -4.5rem auto 0;
  padding: 0 1.5rem;
  position: relative;
  z-index: 10;
}

/* ========== MAIN CONTENT CARD ========== */
.page-content {
  background: #ffffff;
  border-radius: 12px;
  box-shadow:
    0 10px 40px rgba(0, 0, 0, 0.1),
    0 4px 12px rgba(0, 0, 0, 0.05),
    0 0 0 1px rgba(0, 0, 0, 0.02);
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: white;
  padding: 1rem;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* ✅ SIMPLIFIED SEARCH SECTION - SearchBox handles its own styling */
.search-section {
  flex: 1;
  max-width: 400px;
}

/* ❌ REMOVED: Old search input styles - no longer needed */
/* SearchBox component handles all styling internally */

.action-buttons {
  gap: 0.75rem;
}

.create-button {
  background: #003b6f;
  border: none;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.create-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 8px -1px rgba(0, 0, 0, 0.15);
  background: #002147 !important;
}

/* Custom styling for the reusable table */
:deep(.dt-table) {
  font-family:
    "Inter",
    -apple-system,
    BlinkMacSystemFont,
    "Segoe UI",
    sans-serif;
}

:deep(.dt-table .p-datatable-thead > tr > th) {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  font-weight: 600;
  color: #475569;
  border-bottom: 2px solid #e2e8f0;
}

:deep(.dt-table .p-datatable-tbody > tr) {
  transition: all 0.2s ease;
}

:deep(.dt-table .p-datatable-tbody > tr:hover) {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

:deep(.dt-table .p-badge) {
  font-weight: 600;
  text-transform: uppercase;
  font-size: 0.75rem;
  letter-spacing: 0.025em;
}

/* Responsive design */
@media (max-width: 768px) {
  .templates-page-container {
    padding: 1rem;
  }

  .content-wrapper {
    padding: 0 1rem;
    margin: 0 auto;
  }

  .toolbar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  .search-section {
    max-width: none;
  }

  .page-title {
    font-size: 1.5rem;
  }

  .page-header {
    margin-bottom: 1rem;
  }
}

/* Loading states */
:deep(.p-datatable-loading-overlay) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

/* Custom scrollbar for table */
:deep(.p-datatable-scrollable-body)::-webkit-scrollbar {
  height: 8px;
  width: 8px;
}

:deep(.p-datatable-scrollable-body)::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

:deep(.p-datatable-scrollable-body)::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

:deep(.p-datatable-scrollable-body)::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* Enhanced button styles in actions */
:deep(.p-button-sm) {
  border-radius: 6px;
  transition: all 0.2s ease;
}

:deep(.p-button-sm:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
</style>
