<script setup>
import ReusableDataTable from "@/components/ReusableDataTable.vue";
import SearchBox from "@/components/SearchBox.vue";
import HeroSection from "@/components/HeroSection.vue";
import { useAuthStore } from "@/stores/authStore";
import { useUserStore } from "@/stores/userStore";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
import UserForm from "./UserForm.vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import ActionButton from "@/components/ActionButton.vue";

const userStore = useUserStore();
const authStore = useAuthStore();
const { users, total, loading, saving, deleting } = storeToRefs(userStore);
const { user: authUser } = storeToRefs(authStore);

// Ensure array
const usersData = computed(() =>
  Array.isArray(users.value) ? users.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 selectedUser = ref(null);
const formErrors = ref({});

// ========== COLUMNS CONFIG ==========
const columns = [
  {
    field: "name",
    header: "User Details",
    sortable: true,
    template: "user",
    subField: "email",
    style: { minWidth: "280px" },
  },
  {
    field: "role",
    header: "Role",
    sortable: true,
    template: "badge",
    style: { minWidth: "150px" },
  },
  {
    field: "franchisee",
    header: "Franchise",
    sortable: false,
    style: { minWidth: "200px" },
    template: "custom",
    customHTML: (rowData) =>
      rowData.franchisee?.name || '<span class="text-gray-400">-</span>',
  },
  {
    field: "updated_at",
    header: "Last Active",
    sortable: true,
    style: { minWidth: "180px" },
    type: "datetime",
  },
];

// ========== UPDATED ACTIONS (NEW ICONS) ==========
const actions = [
  {
    icon: "pi pi-user-edit", // Changed from pi-pencil to user-edit
    tooltip: "Edit Details",
    severity: "info",
    action: "edit",
  },
  {
    icon: "pi pi-trash", // Kept trash, but you can use 'pi pi-ban' for "Deactivate" look
    tooltip: "Remove User",
    severity: "danger",
    action: "delete",
    condition: (rowData) => rowData.id !== authUser.value?.data?.id,
  },
];

// Load users
const loadUsersLazy = async () => {
  try {
    await userStore.fetchUsersLazy({
      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 users error:", err);
  }
};

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

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

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

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

const createUser = () => {
  formMode.value = "create";
  selectedUser.value = null;
  formErrors.value = {};
  userStore.clearError();
  userStore.clearSelectedUser();
  showForm.value = true;
};

const editUser = (user) => {
  formMode.value = "edit";
  selectedUser.value = user;
  formErrors.value = {};
  userStore.setSelectedUser(user);
  showForm.value = true;
};

const confirmDelete = (user) => {
  selectedUser.value = user;
  showDelete.value = true;
};

const handleSave = async (data) => {
  formErrors.value = {};
  try {
    let payload = { ...data };
    if (data.role === "super_admin") delete payload.franchisee_id;
    else if (
      data.role === "franchise_admin" ||
      data.role === "franchise_editor"
    ) {
      if (authUser.value?.data?.role === "super_admin")
        payload.franchisee_id = data.franchisee_id;
      else
        payload.franchisee_id =
          data.franchisee_id || authUser.value?.data?.franchisee_id;
    }
    payload.created_by = authUser.value?.data?.id;

    let result;
    if (formMode.value === "create")
      result = await userStore.createUser(payload);
    else result = await userStore.updateUser(selectedUser.value.id, payload);

    if (result && result.success !== false) {
      showForm.value = false;
      selectedUser.value = null;
      userStore.clearSelectedUser();
      await loadUsersLazy();
    }
  } catch (err) {
    // 422 from the API — show each message on its own field, not just the toast.
    formErrors.value = err?.response?.data?.errors ?? {};
    console.error("Save error:", err);
  }
};

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

onMounted(() => {
  loadUsersLazy();
});
</script>

<template>
  <div class="users-page-container">
    <HeroSection
      title="User Management"
      subtitle="Control access and manage team members across franchises"
      icon="pi pi-users"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="search-section">
            <SearchBox
              v-model="lazyParams.search"
              placeholder="Search by name, email or role..."
              :loading="loading"
              @search="handleSearch"
              @clear="handleClearSearch"
              class="w-full"
            />
          </div>
          <div class="action-buttons">
            <ActionButton
              v-if="authUser?.data?.role !== 'franchise_editor'"
              label="Add New User"
              icon="pi pi-plus"
              class="create-button"
              @click="createUser"
            />
          </div>
        </div>

        <div class="table-container">
          <ReusableDataTable
            :data="usersData"
            :columns="columns"
            :actions="actions"
            :loading="loading"
            :total-records="total"
            :rows="lazyParams.rows"
            :sort-field="lazyParams.sortField"
            :sort-order="lazyParams.sortOrder"
            :lazy="true"
            :paginator="true"
            data-key="id"
            @page="onPage"
            @sort="onSort"
            @action-click="
              ({ action, rowData }) =>
                action.action === 'edit'
                  ? editUser(rowData)
                  : confirmDelete(rowData)
            "
          />
        </div>
      </div>
    </div>

    <UserForm
      :visible="showForm"
      :user="selectedUser"
      :mode="formMode"
      :loading="saving"
      :auth-user="authUser"
      :server-errors="formErrors"
      @update:visible="(v) => (showForm = v)"
      @save="handleSave"
      @cancel="() => (showForm = false)"
    />

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

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

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

.page-content {
  background: transparent;
}

/* ========== TOOLBAR ========== */
.toolbar {
  background: white;
  padding: 1.25rem 1.5rem;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1.5rem;
  border: 1px solid #e2e8f0; /* Crisp border */
  border-bottom: none;
  margin-bottom: 0;
}

.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;
}

.create-button:active {
  transform: translateY(0);
}

/* ========== 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;
}

/* ========== 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%;
  }
  .create-button {
    width: 100%;
    justify-content: center;
  }
}

/* ========== GLOBAL PAGINATION OVERRIDE ========== */
/* This ensures the blue color wins, even if ReusableDataTable isn't perfect */
:deep(.p-paginator .p-paginator-pages .p-paginator-page.p-highlight) {
  background: #003b6f !important;
  border-color: #003b6f !important;
  color: #ffffff !important;
}

:deep(.p-dropdown-panel .p-dropdown-items .p-dropdown-item.p-highlight) {
  color: #003b6f !important;
  background: #eff6ff !important;
}
</style>
