<script setup>
import { useProgramStore } from "@/stores/programStore";
import { storeToRefs } from "pinia";
import { onActivated, onMounted, ref, computed } from "vue";
import { useAppToast } from "@/composables/useAppToast";
import SearchBox from "@/components/SearchBox.vue";
import { useAuthStore } from "@/stores/authStore";
import { useSettingStore } from "@/stores/settingStore";
import { useRouter } from "vue-router";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import HeroSection from "@/components/HeroSection.vue";
import ReusableDataTable from "@/components/ReusableDataTable.vue";
import ActionButton from "@/components/ActionButton.vue";
import { languages } from "@/utils/languageCode";

const { success } = useAppToast();
const programStore = useProgramStore();
const { programs, total, loading, reordering } = storeToRefs(programStore);
const authStore = useAuthStore();
const { user: authUser } = storeToRefs(authStore);
const settingStore = useSettingStore();
const { setting } = storeToRefs(settingStore);
const router = useRouter();

// Table state
const lazyParams = ref({
  page: 1,
  rows: 50,
  sortField: "order_no",
  sortOrder: 1,
  search: "",
});
const selectedPrograms = ref([]);
const showConfirmDialog = ref(false);
const confirmAction = ref("");
const selectedProgram = ref(null);
const togglingPrograms = ref(new Set());

const selectedProgramIds = computed(() => selectedPrograms.value.map((p) => p.id));
const hasSelectedPrograms = computed(() => selectedPrograms.value.length > 0);
const franchisePreferredLanguageCode = computed(() => {
  const raw =
    setting.value?.general_settings?.language_code ||
    setting.value?.general_settings?.language ||
    authUser.value?.data?.franchisee?.language_code ||
    authUser.value?.data?.franchisee?.language ||
    "en";
  const normalized = String(raw || "en").toLowerCase();

  if (normalized === "en" || normalized === "english") {
    return "en";
  }

  const byCode = languages.find((lang) => lang.code.toLowerCase() === normalized);
  if (byCode) {
    return byCode.code.toLowerCase();
  }

  const byName = languages.find((lang) => lang.name.toLowerCase() === normalized);
  return byName?.code?.toLowerCase() || "en";
});

const listingPrograms = computed(() => {
  const rows = Array.isArray(programs.value) ? programs.value : [];
  return rows;
});
const isSuperAdmin = computed(
  () => authUser.value?.data?.role === "super_admin",
);
const isFranchiseAdmin = computed(() =>
  ["franchise_admin", "franchise_editor"].includes(authUser.value?.data?.role),
);

const formatDuration = (duration) => {
  if (!duration) return "-";
  return duration.replace(/minutes?/gi, "min");
};

// ========== COLUMNS CONFIG ==========
const columns = [
  {
    field: "title",
    header: "Title",
    sortable: true,
    style: { minWidth: "220px" },
    template: "user",
  },
  {
    field: "age_range",
    header: "Age",
    style: { minWidth: "120px" },
    template: "custom",
    customHTML: (row) => `
      <div class="dt-table-cell">
        <i class="pi pi-users dt-table-cell__icon"></i>
        <span>${row.age_range}</span>
      </div>`,
  },
  {
    field: "duration",
    header: "Duration",
    style: { minWidth: "120px" },
    template: "custom",
    customHTML: (row) => `
      <div class="dt-table-cell">
        <i class="pi pi-clock dt-table-cell__icon"></i>
        <span>${formatDuration(row.duration)}</span>
      </div>`,
  },
  {
    field: "status",
    header: "Status",
    sortable: true,
    style: { minWidth: "120px" },
    template: "badge",
  },
  {
    field: "is_enabled",
    header: "Enabled",
    sortable: true,
    style: { minWidth: "100px" },
    template: "toggle",
  },
];

const actions = [
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Program",
    action: "edit",
    severity: "info",
    to: (r) => `/programs/${r.id}/edit`,
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Program",
    action: "delete",
    severity: "danger",
    condition: (r) => isSuperAdmin.value || !r.is_global,
  },
];

const handleAction = ({ action, rowData }) => {
  switch (action.action) {
    case "edit":
      handleEdit(rowData);
      break;
    case "delete":
      handleDelete(rowData);
      break;
  }
};

const loadProgramsLazy = async () => {
  if (!isSuperAdmin.value && !setting.value) {
    await settingStore.getSetting();
  }

  const language = isSuperAdmin.value ? "en" : franchisePreferredLanguageCode.value;
  await programStore.fetchProgramsLazy({
    page: lazyParams.value.page,
    rows: lazyParams.value.rows,
    sortField: lazyParams.value.sortField,
    sortOrder: lazyParams.value.sortOrder,
    search: lazyParams.value.search,
    language,
  });
};

const handleSearch = (term) => {
  lazyParams.value.search = term;
  loadProgramsLazy();
};
const handleClearSearch = () => {
  lazyParams.value.search = "";
  loadProgramsLazy();
};
const createProgram = () => router.push("/programs/add");

// ✅ Only used for manual selection if needed, but DataTable handles checkbox click
const handleRowClick = (program) => {
  if (isSuperAdmin.value || program.language !== "en") return;
  // Logic handled by v-model:selection, but we can keep this if clicking row also selects
};


const handleReorder = async ({ data }) => {
  try {
    // reorderPrograms posts the new order_no list and updates store state on success.
    await programStore.reorderPrograms(data);
  } catch (error) {
    loadProgramsLazy();
  }
};

const handleToggleEnabled = async (program) => {
  if (togglingPrograms.value.has(program.id)) return;
  const original = program.is_enabled;
  try {
    togglingPrograms.value.add(program.id);
    await programStore.updateProgram(program.id, {
      is_enabled: program.is_enabled,
    });
    await loadProgramsLazy();
  } catch {
    program.is_enabled = original;
  } finally {
    togglingPrograms.value.delete(program.id);
  }
};

const handleEdit = (p) => router.push(`/programs/${p.id}/edit`);
const handleDelete = (p) => {
  selectedProgram.value = p;
  confirmAction.value = "delete";
  showConfirmDialog.value = true;
};
const handleConfirm = async () => {
  await programStore.deleteProgram(selectedProgram.value.id);
  showConfirmDialog.value = false;
  loadProgramsLazy();
};

onMounted(loadProgramsLazy);
onActivated(loadProgramsLazy);
</script>

<template>
  <div class="programs-page-container">
    <HeroSection
      title="Programs"
      subtitle="Manage your programs and educational offerings"
      icon="pi pi-graduation-cap"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="search-section">
            <SearchBox
              v-model="lazyParams.search"
              placeholder="Search programs..."
              :loading="loading"
              size="medium"
              @search="handleSearch"
              @clear="handleClearSearch"
            />
          </div>
          <div class="action-buttons">
            <ActionButton
              v-if="isSuperAdmin"
              label="New Program"
              icon="pi pi-plus"
              severity="primary"
              @click="createProgram"
            />
          </div>
        </div>

        <div class="table-container">
          <ReusableDataTable
            :data="listingPrograms"
            :columns="columns"
            :actions="actions"
            :loading="loading"
            :total-records="total"
            :rows="lazyParams.rows"
            :rows-per-page-options="[10, 25, 50]"
            :lazy="false"
            :reorderable="true"
            data-key="id"
            @reorder="handleReorder"
            @toggle-enabled="handleToggleEnabled"
            @action-click="handleAction"
            @page="
              (e) => {
                lazyParams.page = e.page + 1;
                loadProgramsLazy();
              }
            "
          />
        </div>
      </div>
    </div>

    <ConfirmationDialog
      v-model:visible="showConfirmDialog"
      :title="confirmAction === 'delete' ? 'Confirm Delete' : 'Confirm Action'"
      :message="`Delete '${selectedProgram?.title}'?`"
      :item="selectedProgram"
      @confirm="handleConfirm"
      @cancel="showConfirmDialog = false"
    />
  </div>
</template>

<style scoped>
.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 1.5rem;
  position: relative;
  z-index: 10;
}

.page-content {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.toolbar {
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1.5rem;
}

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

/* ✅ Added Gap Style for buttons */
.action-buttons {
  display: flex;
  align-items: center;
  gap: 1rem;
}

: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 */
:deep(.flex) {
  display: flex;
}
:deep(.items-center) {
  align-items: center;
}
:deep(.gap-2) {
  gap: 0.5rem;
}
:deep(.text-slate-400) {
  color: #94a3b8;
}
:deep(.text-blue-600) {
  color: #2563eb;
}
: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(.text-slate-700) {
  color: #334155;
}
:deep(.opacity-70) {
  opacity: 0.7;
}
:deep(.truncate) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
:deep(.shrink-0) {
  flex-shrink: 0;
}
:deep(.w-full) {
  width: 100%;
}
:deep(.text-black) {
  color: #000000;
}

/* Animation */
.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.3s ease,
    transform 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(10px);
}

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