<script setup>
import ActionButton from "@/components/ActionButton.vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import OverlayLoader from "@/components/OverlayLoader.vue";
import ReusableDataTable from "@/components/ReusableDataTable.vue";
import SearchBox from "@/components/SearchBox.vue";
import HeroSection from "@/components/HeroSection.vue";
import AddFranchiseesToGroupModal from "@/components/AddFranchiseesToGroupModal.vue";
import { showToast } from "@/composables/useStoreHelpers";
import FranchiseeForm from "@/pages/franchisees/FranchiseeForm.vue";
import { useFranchiseeStore } from "@/stores/franchiseStore";
import { useFranchiseeGroupStore } from "@/stores/franchiseeGroupStore";
import { showPageLoader } from "@/utils/pageLoader";
import { storeToRefs } from "pinia";
import { useToast } from "primevue/usetoast";
import { computed, nextTick, onMounted, ref } from "vue";

const toast = useToast();

// Stores
const franchiseeStore = useFranchiseeStore();
const franchiseeGroupStore = useFranchiseeGroupStore();
const {
  franchisees,
  total,
  loading,
  saving,
  deleting,
  permanentDeleting,
  generatingLink,
} = storeToRefs(franchiseeStore);
const { groups, saving: groupSaving } = storeToRefs(franchiseeGroupStore);

// Computed to ensure franchisees is always an array
const franchiseesData = computed(() => {
  return Array.isArray(franchisees.value) ? franchisees.value : [];
});
const isAddingToGroup = computed(() => groupSaving.value);

// DUMMY GROUPS DATA (remove when you have real API)
const dummyGroups = ref([
  {
    id: 1,
    name: "Premium Franchises",
    description: "High-performing franchise locations with premium services",
    franchisee_count: 12,
  },
  {
    id: 2,
    name: "East Coast Region",
    description: "All franchises located on the East Coast",
    franchisee_count: 25,
  },
]);

// Use either real groups or dummy data
const availableGroups = computed(() => {
  return groups.value;
});

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

// Dialog states
const showFranchiseeForm = ref(false);
const showDeleteDialog = ref(false);
const showAddToGroupDialog = ref(false);
const formMode = ref("create");
const selectedFranchisee = ref(null);
const selectedFranchisees = ref([]);

// ========== UPDATED COLUMNS CONFIG ==========
const columns = [
  {
    field: "name",
    header: "Franchise Name",
    sortable: true,
    template: "user",
    subField: "owner_name",
    style: { minWidth: "220px" },
  },
  {
    field: "email",
    header: "Email", // Now just Email
    sortable: true,
    style: { minWidth: "200px" },
    template: "custom",
    customHTML: (rowData) =>
      `<div class="text-sm text-gray-600">${rowData.email}</div>`,
  },
  {
    field: "franchise_domain", // New Dedicated Column
    header: "Domain",
    sortable: true,
    style: { minWidth: "180px" },
    template: "custom",
    customHTML: (rowData) =>
      rowData.franchise_domain
        ? `<span class="text-sm text-blue-600 hover:underline cursor-pointer">${rowData.franchise_domain}</span>`
        : '<span class="text-gray-400 text-sm">-</span>',
  },
  {
    field: "status",
    header: "Status",
    sortable: true,
    template: "badge",
    style: { width: "120px" },
  },
  {
    field: "is_website_approved",
    header: "Approval",
    sortable: true,
    template: "custom",
    style: { minWidth: "130px" },
    customHTML: (rowData) => {
      const isApproved = rowData.is_website_approved;
      return `<span class="status-pill ${
        isApproved ? "badge-approved" : "badge-not-approved"
      }">
        <i class="pi ${
          isApproved ? "pi-check-circle" : "pi-times-circle"
        } mr-1"></i>
        ${isApproved ? "Approved" : "Not Approved"}
      </span>`;
    },
  },
];

// ========== ACTIONS CONFIG ==========
const actions = [
  {
    icon: (rowData) =>
      rowData.is_website_approved ? "pi pi-times-circle" : "pi pi-check-circle",
    label: (rowData) =>
      rowData.is_website_approved ? "Mark as Not Approved" : "Mark as Approved",
    tooltip: (rowData) =>
      rowData.is_website_approved ? "Unapprove Website" : "Approve Website",
    severity: (rowData) =>
      rowData.is_website_approved ? "warning" : "success",
    action: "toggleApproval",
  },
  {
    icon: "pi pi-pencil",
    tooltip: "Edit Franchise",
    severity: "info",
    action: "edit",
  },
  {
    icon: "pi pi-sign-in",
    tooltip: (rowData) =>
      rowData?.name
        ? `Login as ${rowData.name}`
        : "Login as franchise",
    severity: "success",
    action: "login",
    loading: (rowData) =>
      generatingLink.value && selectedFranchisee.value?.id === rowData.id,
  },
  {
    icon: "pi pi-trash",
    tooltip: "Delete Franchise",
    severity: "danger",
    action: "delete",
  },
];

// Methods
onMounted(() => {
  loadFranchiseesLazy();
  franchiseeGroupStore.fetchGroups();
});

const loadFranchiseesLazy = async () => {
  try {
    await franchiseeStore.fetchFranchiseesLazy({
      page: lazyParams.value.page,
      rows: lazyParams.value.rows,
      sortField: lazyParams.value.sortField,
      sortOrder: lazyParams.value.sortOrder,
      search: lazyParams.value.search,
    });
  } catch (error) {
    console.log("Error loading franchisees:", error);
  }
};

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

const onSort = (event) => {
  lazyParams.value.sortField = event.sortField;
  lazyParams.value.sortOrder = event.sortOrder;
  loadFranchiseesLazy();
};

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

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

const handleLoginClick = async (franchisee) => {
  if (!selectedFranchisee.value) {
    selectedFranchisee.value = franchisee;
  }
  localStorage.clear();
  const result = await franchiseeStore.generateLoginLink(franchisee.id);

  if (result.success && result.url) {
    showPageLoader();
    window.location.href = result.url;
  } else {
    selectedFranchisee.value = null;
    showToast("error", "Error", "Failed to generate login link");
  }
};

const handleToggleApproval = async (franchisee) => {
  try {
    const newVal = !franchisee.is_website_approved;
    const result = await franchiseeStore.updateFranchisee(franchisee.id, {
      is_website_approved: newVal,
    });
    if (result && result.success !== false) {
      // showToast(
      //   "success",
      //   "Success",
      //   `Website ${newVal ? "approved" : "unapproved"} successfully`,
      // );
      loadFranchiseesLazy();
    }
  } catch (error) {
    console.error("Error toggling approval:", error);
    // showToast("error", "Error", "Failed to update approval status");
  }
};

const onActionClick = ({ action, rowData }) => {
  selectedFranchisee.value = rowData;
  switch (action.action) {
    case "toggleApproval":
      handleToggleApproval(rowData);
      break;
    case "edit":
      editFranchisee(rowData);
      break;
    case "login":
      handleLoginClick(rowData);
      break;
    case "delete":
      confirmDeleteFranchisee(rowData);
      break;
  }
};

const createFranchisee = () => {
  formMode.value = "create";
  selectedFranchisee.value = null;
  showFranchiseeForm.value = true;
  nextTick(() => {
    if (franchiseeStore.clearError) franchiseeStore.clearError();
    if (typeof franchiseeStore.clearSelectedFranchisee === "function")
      franchiseeStore.clearSelectedFranchisee();
  });
};

const editFranchisee = (franchisee) => {
  formMode.value = "edit";
  selectedFranchisee.value = franchisee;
  if (franchiseeStore.setSelectedFranchisee)
    franchiseeStore.setSelectedFranchisee(franchisee);
  showFranchiseeForm.value = true;
};

const confirmDeleteFranchisee = (franchisee) => {
  selectedFranchisee.value = franchisee;
  showDeleteDialog.value = true;
};

const handleSaveFranchisee = async (formData) => {
  try {
    let result;
    if (formMode.value === "create") {
      result = await franchiseeStore.createFranchisee(formData);
    } else {
      result = await franchiseeStore.updateFranchisee(
        selectedFranchisee.value.id,
        formData,
      );
    }
    if (result && result.success === false) return;

    showFranchiseeForm.value = false;
    selectedFranchisee.value = null;
    loadFranchiseesLazy();
  } catch (error) {
    console.log("Error saving franchisee:", error);
  }
};

const handleDeleteFranchisee = async (franchisee) => {
  try {
    await franchiseeStore.deleteFranchisee(franchisee.id);
    showDeleteDialog.value = false;
    selectedFranchisee.value = null;
    if (franchiseesData.value.length === 1 && lazyParams.value.page > 1)
      lazyParams.value.page--;
    loadFranchiseesLazy();
  } catch (error) {
    console.log("Error deleting franchisee:", error);
  }
};

const handlePermanentDeleteFranchisee = async (franchisee) => {
  try {
    await franchiseeStore.permanentDeleteFranchisee(franchisee.id);
    showDeleteDialog.value = false;
    selectedFranchisee.value = null;
    if (franchiseesData.value.length === 1 && lazyParams.value.page > 1)
      lazyParams.value.page--;
    loadFranchiseesLazy();
  } catch (error) {
    console.log("Error permanently deleting franchisee:", error);
  }
};

const handleCancelForm = () => {
  showFranchiseeForm.value = false;
  selectedFranchisee.value = null;
  if (franchiseeStore.clearSelectedFranchisee)
    franchiseeStore.clearSelectedFranchisee();
};

const handleCancelDelete = () => {
  showDeleteDialog.value = false;
  selectedFranchisee.value = null;
};

const handleShowAddToGroupDialog = async () => {
  if (selectedFranchisees.value.length === 0) {
    showToast("error", "Error", "Please select at least one franchisee");
    return;
  }
  showAddToGroupDialog.value = true;
};

const handleAddToGroup = async (data) => {
  try {
    const result = await franchiseeGroupStore.addFranchiseesToGroups(
      selectedFranchisees.value.map((f) => f.id),
      data.group_ids,
    );
    if (result.success) {
      franchiseeStore.clearCache();
      await loadFranchiseesLazy();
      showAddToGroupDialog.value = false;
      selectedFranchisees.value = [];
    } else {
      throw new Error(result.message || "Failed to add franchisees to groups");
    }
  } catch (error) {
    console.error("Error adding franchisees to groups:", error);
    showToast(
      "error",
      "Error",
      error.message || "Failed to add franchisees to groups",
    );
    throw error;
  }
};
</script>

<template>
  <div class="franchisees-page-container">
    <OverlayLoader :loading="generatingLink" />

    <HeroSection
      title="Franchisees"
      subtitle="Manage your franchise network"
      icon="pi pi-briefcase"
    />

    <div class="content-wrapper">
      <div class="page-content">
        <div class="toolbar">
          <div class="toolbar-left">
            <div class="search-section">
              <SearchBox
                v-model="lazyParams.search"
                placeholder="Search franchises..."
                :loading="loading"
                @search="handleSearch"
                @clear="handleClearSearch"
                class="w-full"
              />
            </div>

            <transition name="fade">
              <ActionButton
                v-if="selectedFranchisees.length > 0"
                :label="`Add ${selectedFranchisees.length} to Group`"
                icon="pi pi-users"
                class="add-to-group-button"
                @click="handleShowAddToGroupDialog"
              />
            </transition>
          </div>

          <div class="action-buttons">
            <ActionButton
              label="New Franchise"
              icon="pi pi-plus"
              class="create-button"
              @click="createFranchisee"
            />
          </div>
        </div>

        <div class="table-container">
          <ReusableDataTable
            :data="franchiseesData"
            :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, 100]"
            selection-mode="checkbox"
            v-model:selection="selectedFranchisees"
            data-key="id"
            @page="onPage"
            @sort="onSort"
            @action-click="onActionClick"
          />
        </div>
      </div>
    </div>

    <FranchiseeForm
      :visible="showFranchiseeForm"
      @update:visible="(value) => (showFranchiseeForm = value)"
      :franchisee="selectedFranchisee"
      :mode="formMode"
      :loading="saving"
      :groups="availableGroups"
      @save="handleSaveFranchisee"
      @cancel="handleCancelForm"
    />

    <ConfirmationDialog
      v-model:visible="showDeleteDialog"
      title="Delete Franchise"
      :message="`Are you sure you want to delete the franchise '${selectedFranchisee?.name}'?`"
      :item="selectedFranchisee"
      :loading="deleting"
      :show-permanent-delete="true"
      :permanent-delete-loading="permanentDeleting"
      @confirm="handleDeleteFranchisee"
      @permanent-delete="handlePermanentDeleteFranchisee"
      @cancel="handleCancelDelete"
    />

    <AddFranchiseesToGroupModal
      :visible="showAddToGroupDialog"
      :selected-franchisees="selectedFranchisees"
      :groups="availableGroups"
      :loading="isAddingToGroup"
      @update:visible="(v) => (showAddToGroupDialog = v)"
      @submit="handleAddToGroup"
    />
  </div>
</template>

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

/* ========== CONTENT WRAPPER (OVERLAP EFFECT) ========== */
.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;
  border-bottom: none; /* Merged with Table */
  margin-bottom: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex: 1;
}

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

/* Add To Group Button (Secondary Action) */
.add-to-group-button {
  background-color: #ffffff !important;
  border: 1px solid #e2e8f0 !important;
  color: #475569 !important;
  padding: 0.6rem 1rem !important;
  font-weight: 500 !important;
  font-size: 0.9rem !important;
  border-radius: 8px !important;
  transition: all 0.2s ease !important;
}

.add-to-group-button:hover {
  background-color: #f8fafc !important;
  border-color: #cbd5e1 !important;
  color: #003b6f !important; /* Brand Blue Hover */
}

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

/* ========== TRANSITIONS ========== */
.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.2s ease,
    transform 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}

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