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

const router = useRouter();

// Stores
const formStore = useFormStore();
const { forms, total, loading, deleting } = storeToRefs(formStore);

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

// State
const lazyParams = ref({
  page: 1,
  rows: 10,
  sortField: "",
  sortOrder: 0,
  search: "",
});
const showDelete = ref(false);
const selectedForm = ref(null);

// Computed
const isSuperAdmin = computed(
  () => authUser.value?.data?.role === "super_admin",
);

// ========== COLUMNS CONFIG (Premium Design) ==========
const columns = [
  {
    field: "name",
    header: "Form Name",
    sortable: true,
    style: { minWidth: "250px" },
    // ✅ CHANGED: Uses 'user' template to generate Initials Avatar
    template: "user",
  },
  {
    field: "status",
    header: "Status",
    sortable: true,
    template: "badge", // ✅ Automatically Blue/White
    style: { minWidth: "120px" },
  },
  {
    field: "created_at",
    header: "Created",
    sortable: true,
    style: { minWidth: "150px" },
    type: "datetime",
  },
];

// Actions
const allActions = [
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Form",
    severity: "info",
    action: "edit",
    to: (row) => `/forms/edit/${row.id}`,
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Form",
    severity: "danger",
    action: "delete",
    show: (row) =>
      isSuperAdmin.value ||
      (!row.is_global && !!row.franchisee_id),
  },
];

const actions = computed(() => allActions);

// Methods
const fetchForms = async () => {
  await formStore.fetchFormsLazy(lazyParams.value);
};

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

const onSort = (e) => {
  lazyParams.value.sortField = e.sortField;
  lazyParams.value.sortOrder = e.sortOrder;
  fetchForms();
};

const handleSearch = (searchTerm) => {
  lazyParams.value.search = searchTerm;
  lazyParams.value.page = 1;
  fetchForms();
};

const handleClearSearch = () => {
  lazyParams.value.search = "";
  lazyParams.value.page = 1;
  fetchForms();
};

const createForm = () => {
  if (!isSuperAdmin.value) return;
  router.push("/forms/add");
};

const editForm = (form) => {
  router.push(`/forms/edit/${form.id}`);
};


const confirmDelete = (form) => {
  selectedForm.value = form;
  showDelete.value = true;
};

const handleDelete = async () => {
  if (!selectedForm.value) return;
  try {
    const result = await formStore.deleteForm(selectedForm.value.id);
    if (result && result.success) {
      showDelete.value = false;
      selectedForm.value = null;
    } else {
      showToast("error", "", result?.error || "Failed to delete form");
    }
  } catch (error) {
    console.error("Delete error:", error);
    showToast("error", "", "Failed to delete form");
    if (
      error.message &&
      error.message.includes("Toast service not initialized")
    ) {
      showDelete.value = false;
      selectedForm.value = null;
    }
  }
};

const handleAction = ({ action, rowData }) => {
  if (action.action === "delete") {
    if (!isSuperAdmin.value && rowData.is_global) {
      showToast("error", "", "You cannot delete global forms");
      return;
    }
    confirmDelete(rowData);
    return;
  }
  if (action.action === "edit") {
    editForm(rowData);
  }
};

onMounted(async () => {
  fetchForms();
});
</script>

<template>
  <div class="forms-page-container">
    <HeroSection
      title="Forms"
      subtitle="Create and manage dynamic forms for your applications"
      icon="pi pi-align-justify"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="search-section">            <SearchBox
              v-model="lazyParams.search"
              placeholder="Search forms..."
              :loading="loading"
              size="medium"
              @search="handleSearch"
              @clear="handleClearSearch"
              class="w-full"
            />
          </div>
          <div class="action-buttons">
            <ActionButton
              v-if="isSuperAdmin"
              label="New Form"
              icon="pi pi-plus"
              class="create-button"
              @click="createForm"
            />
          </div>
        </div>

        <div class="table-container">
          <ReusableDataTable
            :data="forms"
            :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]"
            data-key="id"
            @page="onPage"
            @sort="onSort"
            @action-click="handleAction"
          />
        </div>
      </div>
    </div>

    <ConfirmationDialog
      v-model:visible="showDelete"
      title="Delete Form"
      :message="`Are you sure you want to delete '${selectedForm?.name}'? This action cannot be undone.`"
      :item="selectedForm"
      :loading="deleting"
      @confirm="handleDelete"
      @cancel="() => (showDelete = false)"
    />
  </div>
</template>

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

/* ========== CONTENT WRAPPER ========== */
/* layout: _listing-layout.scss */

.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 FIXES ========== */
:deep(.reusable-data-table-container) {
  border-top-left-radius: 0 !important;
  border-top-right-radius: 0 !important;
  border-top: none !important;
  border-color: #e2e8f0 !important;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important;
}

/* ========== UTILITIES FOR CUSTOM HTML ========== */
:deep(.flex) {
  display: flex;
}
:deep(.items-center) {
  align-items: center;
}
:deep(.justify-center) {
  justify-content: center;
}
:deep(.w-8) {
  width: 2rem;
}
:deep(.h-8) {
  height: 2rem;
}
:deep(.rounded-full) {
  border-radius: 9999px;
}
:deep(.rounded-md) {
  border-radius: 0.375rem;
}
:deep(.bg-white) {
  background-color: #ffffff;
}
:deep(.text-slate-700) {
  color: #334155;
}
:deep(.text-slate-500) {
  color: #64748b;
}
:deep(.font-bold) {
  font-weight: 700;
}
:deep(.font-semibold) {
  font-weight: 600;
}
:deep(.border) {
  border-width: 1px;
}
:deep(.border-slate-200) {
  border-color: #e2e8f0;
}
:deep(.uppercase) {
  text-transform: uppercase;
}
:deep(.tracking-wide) {
  letter-spacing: 0.025em;
}
:deep(.shadow-sm) {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

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