<script setup>
import ReusableDataTable from "@/components/ReusableDataTable.vue"; // ✅ Using Main Table
import SearchBox from "@/components/SearchBox.vue";
import { useTeacherStore } from "@/stores/teacherStore";
import { useAuthStore } from "@/stores/authStore";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
import ActionButton from "@/components/ActionButton.vue";
import HeroSection from "@/components/HeroSection.vue";
import TeacherForm from "./TeacherForm.vue";
import TranslationModal from "@/components/TranslationModal.vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import { showToast } from "@/composables/useStoreHelpers";

const teacherStore = useTeacherStore();
const { teachers, total, loading, saving, deleting } =
  storeToRefs(teacherStore);

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

// Ensure array
const teachersData = computed(() =>
  Array.isArray(teachers.value) ? teachers.value : [],
);

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

// Dialog state
const showForm = ref(false);
const showDelete = ref(false);
const formMode = ref("create");
const selectedTeacher = ref(null);
const selectedTeachers = ref([]);
const showTranslationModal = ref(false);

const isSuperAdmin = computed(
  () => authUser.value?.data?.role === "super_admin",
);
const selectedTeacherIds = computed(() =>
  selectedTeachers.value.map((t) => t.id),
);
const hasSelectedTeachers = computed(() => selectedTeachers.value.length > 0);

// ========== COLUMNS CONFIG (Premium Design) ==========
const columns = [
  {
    field: "name",
    header: "Teacher", // ✅ Combined Photo + Name
    sortable: true,
    style: { minWidth: "250px" },
    template: "custom",
    customHTML: (row) => {
      const name = row.name || "Teacher";
      const initial = name.charAt(0).toUpperCase();
      // Render Image or Initials Fallback
      const avatar = row.profile_image
        ? `<img src="${row.profile_image}" alt="${name}" class="w-8 h-8 rounded-full object-cover border border-slate-200 shadow-sm shrink-0" />`
        : `<div class="w-8 h-8 rounded-full bg-blue-50 flex items-center justify-center text-blue-600 font-bold text-xs border border-blue-100 shadow-sm shrink-0">${initial}</div>`;

      return `
        <div class="flex items-center gap-3">
          ${avatar}
          <span class="font-semibold text-slate-700 text-sm">${name}</span>
        </div>
      `;
    },
  },
  {
    field: "qualification",
    header: "Qualification",
    sortable: true,
    style: { minWidth: "200px" },
    template: "custom",
    // ✅ Icon Design
    customHTML: (row) => `
      <div class="flex items-center gap-2 text-slate-600">
        <i class="pi pi-book text-blue-600 text-xs"></i>
        <span class="text-sm font-medium">${row.qualification || "-"}</span>
      </div>`,
  },
  {
    field: "experience",
    header: "Experience",
    sortable: true,
    style: { minWidth: "150px" },
    template: "custom",
    // ✅ Icon Design
    customHTML: (row) => `
      <div class="flex items-center gap-2 text-slate-600">
        <i class="pi pi-briefcase text-blue-600 text-xs"></i>
        <span class="text-sm font-medium">${row.experience ? row.experience + " years" : "-"}</span>
      </div>`,
  },
  {
    field: "created_at",
    header: "Joined Date",
    sortable: true,
    style: { minWidth: "180px" },
    type: "datetime",
  },
  {
    field: "status",
    header: "Status",
    sortable: true,
    style: { minWidth: "100px" },
    template: "toggle",
    trueValue: "Active",
    falseValue: "Inactive",
  },
];

const togglingTeachers = ref(new Set());

// Actions definition
const actions = [
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Teacher",
    severity: "info",
    action: "edit",
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Teacher",
    severity: "danger",
    action: "delete",
    condition: (row) => isSuperAdmin.value || !row.is_global, // Protect global
  },
];

// Handlers
const loadTeachersLazy = async () => {
  try {
    await teacherStore.fetchTeachersLazy({
      page: lazyParams.value.page,
      rows: lazyParams.value.rows,
      sortField: lazyParams.value.sortField,
      sortOrder: lazyParams.value.sortOrder,
      search: lazyParams.value.search,
    });
  } catch (err) {
    console.error("Load teachers error:", err);
  }
};

const handleReorder = async ({ data }) => {
  try {
    // Optimistic update logic if store supports it immediately
    await teacherStore.reorderTeachers(data);
    showToast("success", "", "Order updated successfully");
  } catch (error) {
    loadTeachersLazy(); // Revert
  }
};

const handleToggleEnabled = async (teacher) => {
  if (togglingTeachers.value.has(teacher.id)) return;
  const original = teacher.status;
  // Compute previous value since ToggleSwitch v-model updates teacher.status immediately under the hood
  // before @change emits when clicking (it binds down to the rowData value).
  // So the UI toggled it to the 'new' value already in the UI element.
  const newStatus = teacher.status; // Get what it changed to
  try {
    togglingTeachers.value.add(teacher.id);
    await teacherStore.updateTeacher(teacher.id, {
      status: newStatus,
    });
    // Opt-in UI update or reload
    await loadTeachersLazy();
  } catch {
    // Revert if failed
    teacher.status = original === "Active" ? "Inactive" : "Active";
    showToast("error", "", "Failed to update status");
  } finally {
    togglingTeachers.value.delete(teacher.id);
  }
};

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

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

const handleSearch = (term) => {
  lazyParams.value.search = term;
  loadTeachersLazy();
};
const handleClearSearch = () => {
  lazyParams.value.search = "";
  loadTeachersLazy();
};

const handleRowClick = (teacher) => {
  if (isSuperAdmin.value) return;
  const index = selectedTeachers.value.findIndex((t) => t.id === teacher.id);
  index > -1
    ? selectedTeachers.value.splice(index, 1)
    : selectedTeachers.value.push(teacher);
};

const openTranslationModal = () => {
  if (!hasSelectedTeachers.value) {
    showToast("error", "", "Please select at least one teacher");
    return;
  }
  showTranslationModal.value = true;
};

const handleTranslation = async (payload) => {
  try {
    const result = await teacherStore.translateTeachers({
      ...payload,
      teacher_ids: selectedTeacherIds.value,
    });
    if (result?.success) {
      showTranslationModal.value = false;
      selectedTeachers.value = [];
      await loadTeachersLazy();
      showToast("success", "", "Teachers translated successfully");
    } else {
      showToast("error", "", result?.error || "Failed to translate");
    }
  } catch (error) {
    showToast("error", "", "Translation failed");
  }
};

const createTeacher = () => {
  formMode.value = "create";
  selectedTeacher.value = null;
  teacherStore.clearError();
  teacherStore.clearSelectedTeacher();
  showForm.value = true;
};

const handleAction = ({ action, rowData }) => {
  if (action.action === "edit") {
    formMode.value = "edit";
    selectedTeacher.value = rowData;
    teacherStore.setSelectedTeacher(rowData);
    showForm.value = true;
  } else if (action.action === "delete") {
    if (!isSuperAdmin.value && rowData.is_global) {
      showToast("error", "", "You cannot delete global teachers");
      return;
    }
    selectedTeacher.value = rowData;
    showDelete.value = true;
  }
};

const handleSave = async (data) => {
  try {
    let result =
      formMode.value === "create"
        ? await teacherStore.createTeacher(data)
        : await teacherStore.updateTeacher(selectedTeacher.value.id, data);

    if (result && result.success !== false) {
      showForm.value = false;
      selectedTeacher.value = null;
      teacherStore.clearSelectedTeacher();
    }
  } catch (err) {
    console.error("Save error:", err);
  }
};

const handleDelete = async () => {
  if (!selectedTeacher.value) return;
  try {
    const result = await teacherStore.deleteTeacher(selectedTeacher.value.id);
    if (result && result.success !== false) {
      showDelete.value = false;
      selectedTeacher.value = null;
    }
  } catch (err) {
    console.error("Delete error:", err);
  }
};

onMounted(loadTeachersLazy);
</script>

<template>
  <div class="teachers-page-container">
    <HeroSection
      title="Teachers"
      subtitle="Manage and organize your teacher profiles"
      icon="pi pi-user-edit"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="search-section">
            <SearchBox
              v-model="lazyParams.search"
              placeholder="Search teachers..."
              :loading="loading"
              size="medium"
              @search="handleSearch"
              @clear="handleClearSearch"
            />
          </div>
          <div class="action-buttons">
            <ActionButton
              v-if="hasSelectedTeachers && !isSuperAdmin"
              label="Translate Selected"
              icon="pi pi-language"
              severity="info"
              size="medium"
              @click="openTranslationModal"
              class="translate-button"
              :loading="saving"
            />
            <ActionButton
              label="New Teacher"
              icon="pi pi-plus"
              class="create-button"
              size="medium"
              @click="createTeacher"
            />
          </div>
        </div>

        <ReusableDataTable
          :data="teachersData"
          :columns="columns"
          :actions="actions"
          :loading="loading"
          :total-records="total"
          :rows="lazyParams.rows"
          :reorderable="true"
          @reorder="handleReorder"
          @toggle-enabled="handleToggleEnabled"
          @action-click="handleAction"
          @page="onPage"
          @sort="onSort"
          @row-click="handleRowClick"
          :row-selected="(t) => selectedTeachers.some((st) => st.id === t.id)"
        />
      </div>
    </div>

    <TeacherForm
      :visible="showForm"
      :teacher="selectedTeacher"
      :mode="formMode"
      :loading="saving"
      @update:visible="(v) => (showForm = v)"
      @save="handleSave"
      @cancel="() => (showForm = false)"
    />
    <TranslationModal
      :visible="showTranslationModal"
      :selected-count="selectedTeachers.length"
      :loading="saving"
      entity-type="teachers"
      @update:visible="(v) => (showTranslationModal = v)"
      @translate="handleTranslation"
      @cancel="() => (showTranslationModal = false)"
    />
    <ConfirmationDialog
      v-model:visible="showDelete"
      title="Delete Teacher"
      :message="`Delete '${selectedTeacher?.name}'?`"
      :item="selectedTeacher"
      :loading="deleting"
      @confirm="handleDelete"
      @cancel="() => (showDelete = false)"
    />
  </div>
</template>

<style scoped>
/* ========== CONTENT WRAPPER ========== */
.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 ========== */
.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;
}
.action-buttons {
  display: flex;
  gap: 0.75rem;
  flex-shrink: 0;
}

/* ========== BUTTONS ========== */
.create-button {
  background: #003b6f !important;
  border: 1px solid #003b6f !important;
  color: white !important;
}
.create-button:hover {
  background: #002a50 !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(.gap-2) {
  gap: 0.5rem;
}
:deep(.gap-3) {
  gap: 0.75rem;
}
:deep(.text-blue-600) {
  color: #2563eb;
}
:deep(.text-slate-600) {
  color: #475569;
}
:deep(.text-slate-700) {
  color: #334155;
}
:deep(.font-medium) {
  font-weight: 500;
}
:deep(.font-semibold) {
  font-weight: 600;
}
:deep(.text-sm) {
  font-size: 0.875rem;
}
:deep(.text-xs) {
  font-size: 0.75rem;
}
:deep(.w-8) {
  width: 2rem;
}
:deep(.h-8) {
  height: 2rem;
}
:deep(.rounded-full) {
  border-radius: 9999px;
}
:deep(.object-cover) {
  object-fit: cover;
}
:deep(.border) {
  border-width: 1px;
}
:deep(.border-slate-200) {
  border-color: #e2e8f0;
}
:deep(.shadow-sm) {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
:deep(.bg-blue-50) {
  background-color: #eff6ff;
}
:deep(.border-blue-100) {
  border-color: #dbeafe;
}

/* ========== RESPONSIVE ========== */
@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>
