<template>
  <div class="produits-container p-4">
    <!-- Header -->
    <div class="flex justify-content-between align-items-center mb-4">
      <h1>{{ $t("menu.products") }}</h1>
      <Button
        v-if="products && products.length > 0"
        :label="$t('products.create_button')"
        icon="pi pi-plus"
        @click="openDialog"
      />
    </div>
    <p>{{ $t('products.description') }}</p>

    <!-- Loading state --> 
    <LoadingState v-if="loading" />

    <!-- Empty state -->
    <EmptyState
      v-else-if="!products || products.length === 0"
      :image="'empty-products.svg'"
      :title="$t('products.empty.title')"
      :description="$t('products.empty.description')"
      :buttonLabel="$t('products.create_button')"
      @action="openDialog"
    />

    <!-- Table -->
    <DataTable
      v-else
      :value="products"
      stripedRows
      paginator
      :rows="10"
      tableStyle="min-width: 50rem"
      :loading="false"
      :lazy="true"
      @page="onPage"
      :totalRecords="totalRecords"
    >
      <!-- Product -->
      <Column field="name" :header="$t('products.columns.product')" style="min-width: 200px">
        <template #body="slotProps">
          <div class="flex align-items-center gap-2">
            <Avatar :image="slotProps.data.image" shape="circle" v-if="slotProps.data.image && slotProps.data.image !== ''" />
            <Avatar icon="pi pi-box" shape="circle" v-else />
            <div>{{ slotProps.data.title }}</div>
          </div>
        </template>
      </Column>

      <!-- Assigned customers (with Popover) -->
      <Column :header="$t('products.columns.assigned_clients')" style="min-width: 150px" class="text-center">
        <template #body="slotProps">
          <div class="flex align-items-center justify-content-center">
            <div
              class="cursor-pointer clients-count font-semibold text-center"
              :class="{
                'text-primary': slotProps.data.clients.length > 0,
                'text-color-secondary': slotProps.data.clients.length === 0,
              }"
              @click="openClientsPopover(slotProps.data, $event)"
            >
              {{
                slotProps.data.clients.length > 0
                  ? slotProps.data.clients.length
                  : "0"
              }}
            </div>
          </div>
        </template>
      </Column>

      <!-- Stock / Assigned Stock -->
      <Column :header="$t('products.columns.stock')" style="min-width: 170px" class="text-center">
        <template #body="slotProps">
          <div class="flex flex-column align-items-center">
            <div class="w-10rem overflow-hidden">
              <ProgressBar
                :value="getStockPercentage(slotProps.data.stock_assigned, slotProps.data.stock)"
                :class="[
                  getProgressBarColor(slotProps.data.stock_assigned, slotProps.data.stock),
                  getStockPercentage(slotProps.data.stock_assigned, slotProps.data.stock) < 20 ? 'hide-progress-label' : ''
                ]"
              />
              <div class="text-center">
                <span class="text-xs" :class="getProgressBarColor(slotProps.data.stock_assigned, slotProps.data.stock)">
                  {{ slotProps.data.stock_assigned }} / <strong>{{ slotProps.data.stock }}</strong>
                </span>
              </div>
            </div>
          </div>
        </template>
      </Column>

      <!-- Ordered amount -->
      <Column :header="$t('products.columns.ordered_amount')" style="min-width: 170px" class="text-center">
        <template #body="slotProps">
          <span
            :class="
              slotProps.data.ordered_amount > 0
                ? 'text-primary font-medium'
                : 'text-danger'
            "
          >
            {{ formatCurrency(slotProps.data.ordered_amount) }}
          </span>
        </template>
      </Column>

      <!-- Display type -->
      <Column :header="$t('products.columns.display_type')" style="min-width: 220px" class="text-center">
        <template #body="slotProps">
          <div class="flex gap-2 justify-content-center">
            <!-- Hide product -->
            <Button
              :icon="slotProps.data.display.hide_product ? 'pi pi-eye-slash' : 'pi pi-eye'"
              text
              :severity="slotProps.data.display.hide_product ? 'success' : 'secondary'"
              :outlined="slotProps.data.display.hide_product"
              v-tooltip.top="slotProps.data.display.hide_product ? $t('products.display_options.show_product_action') : $t('products.display_options.hide_product_action') "
              @click="toggleDisplayOption(slotProps.data, 'hide_product')"
            />

            <!-- Blur product -->
            <Button
              :icon="`pi pi-crown ${isProAddonInstalled() || isUltimateAddonInstalled() ? '' : 'is-premium-menu'}`"
              text
              :severity="slotProps.data.display.blur_product ? 'success' : 'secondary'"
              :outlined="slotProps.data.display.blur_product"
              v-tooltip.top="slotProps.data.display.blur_product ? $t('products.display_options.disable_blur_action') : $t('products.display_options.enable_blur_action')"
              @click="toggleDisplayOption(slotProps.data, 'blur_product')"
            />

            <!-- Hide title -->
            <Button
              :icon="`pi pi-tag ${isProAddonInstalled() || isUltimateAddonInstalled() ? '' : 'is-premium-menu'}`"
              text
              :severity="slotProps.data.display.hide_title ? 'success' : 'secondary'"
              :outlined="slotProps.data.display.hide_title"
              v-tooltip.top="slotProps.data.display.hide_title ? $t('products.display_options.show_title_action') : $t('products.display_options.hide_title_action')"
              @click="toggleDisplayOption(slotProps.data, 'hide_title')"
            />

            <!-- Hide price -->
            <Button
              :icon="`pi pi-euro ${isProAddonInstalled() || isUltimateAddonInstalled() ? '' : 'is-premium-menu'}`"
              text
              :severity="slotProps.data.display.hide_price ? 'success' : 'secondary'"
              :outlined="slotProps.data.display.hide_price"
              v-tooltip.top="slotProps.data.display.hide_price ? $t('products.display_options.show_price_action') : $t('products.display_options.hide_price_action')"
              @click="toggleDisplayOption(slotProps.data, 'hide_price')"
            />
          </div>
        </template>
      </Column>

      <!-- Actions -->
      <Column :header="$t('products.columns.actions')" style="min-width: 100px" class="text-right">
        <template #body="slotProps">
          <div class="flex gap-2 justify-content-end">
            <!-- Edit product -->
            <Button
              icon="pi pi-pencil"
              text
              rounded
              @click="editProduct(slotProps.data)"
            />
            <!-- Delete product -->
            <Button
              icon="pi pi-trash"
              text
              rounded
              severity="danger"
              @click="confirmDeleteProduct(slotProps.data)"
            />
          </div>
        </template>
      </Column>
    </DataTable>

    <!-- Popover for customer management -->
    <Popover ref="popoverRef" :closeOnEscape="true" :showCloseIcon="true">
      <div v-if="selectedProduct" class="clients-popover">
        <div class="flex flex-column gap-1 w-full">
          <div class="mb-2 border-bottom-1 border-300 pb-1">
            <span class="font-medium">{{ $t('products.clients_popover.title') }}: {{ selectedProduct.name }}</span>
            
            <!-- Column headers -->
            <div class="flex justify-content-between text-xs text-500 mt-2">
              <div style="width: 30%">{{ $t('products.columns.user') }}</div>
              <div style="width: 25%" class="text-center">{{ $t('products.columns.stock') }}</div>
              <div style="width: 20%" class="text-right">{{ $t('products.columns.price') }}</div>
              <div style="width: 25%" class="text-right">{{ $t('products.columns.ordered_amount') }}</div>
            </div>
          </div>

          <!-- No customers -->
          <div
            v-if="selectedProduct.clients.length === 0"
            class="text-color-secondary text-center text-xs p-2"
          >
            {{ $t('products.clients_popover.empty') }}
          </div>

          <!-- List of assigned customers -->
          <div v-else>
            <ul class="list-none p-0 m-0 flex flex-column">
              <li
                v-for="client in selectedProduct.clients"
                :key="client.id"
                class="client-item py-2 border-bottom-1 border-200"
              >
                <div class="flex align-items-center justify-content-between">
                  <!-- User info (left) -->
                  <div class="flex align-items-center" style="width: 35%">
                    <div class="avatar-container mr-2">
                      <img 
                        v-if="client.avatar && client.avatar.length > 0" 
                        :src="client.avatar" 
                        class="client-avatar" 
                        @error="handleAvatarError"
                      />
                      <div v-else class="fallback-avatar">
                        <i class="pi pi-user"></i>
                      </div>
                    </div>
                    <div>
                      <div v-tooltip.top="client.user.email" class="font-medium text-sm">{{ client.user.name }}</div>
                    </div>
                  </div>
                  
                  <!-- Stock progress (center) -->
                  <div class="flex align-items-center justify-content-center" style="width: 25%">
                    <div class="w-full">
                      <ProgressBar
                        :value="getStockPercentage(client.stock_ordered, client.stock_assigned)"
                        :class="[getProgressBarColor(client.stock_ordered, client.stock_assigned), 'hide-progress-label']"
                        style="height: 6px"
                      />
                      <div class="text-center mt-1">
                        <span class="text-xs" :class="getProgressBarColor(client.stock_ordered, client.stock_assigned)">
                          {{ client.stock_ordered }} <span class="text-500">/ {{ client.stock_assigned }}</span>
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- Price (center-right) -->
                  <div class="flex align-items-center justify-content-end" style="width: 25%">
                    <div class="text-xs">
                      <span class="font-medium text-right">{{ formatCurrency(client.price_assigned) }}</span>
                      <div class="text-500 text-right"><i>({{ formatCurrency(selectedProduct.price) }})</i></div>
                    </div>
                  </div>
                  
                  <!-- Ordered amount (right) -->
                  <div class="flex align-items-center justify-content-end" style="width: 15%">
                    <div class="text-xs">
                      <span class="font-medium text-green-500">{{ formatCurrency(client.ordered_amount || 0) }}</span>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </Popover>

    <!-- AddProduct component -->
    <AddProduct
      :visible="dialogVisible"
      @update:visible="dialogVisible = $event"
      :editingProduct="productToEdit"
      @product-created="handleProductCreated"
      @product-updated="handleProductUpdated"
    />

    <!-- Delete confirmation dialog -->
    <Dialog
      :visible="deleteDialogVisible"
      @update:visible="deleteDialogVisible = $event"
      :header="$t('products.dialogs.delete.title')"
      :modal="true"
      :closable="true"
      :style="{ width: '450px' }"
    >
      <div class="flex align-items-center gap-2 mb-3">
        <i class="pi pi-exclamation-triangle text-orange-500" style="font-size: 2rem"></i>
        <span>{{ $t('products.dialogs.delete.message') }}</span>
      </div>
      <template #footer>
        <Button
          :label="$t('products.dialogs.delete.cancel')"
          icon="pi pi-times"
          text
          @click="deleteDialogVisible = false"
        />
        <Button
          :label="$t('products.dialogs.delete.confirm')"
          icon="pi pi-check"
          severity="danger"
          @click="deleteProduct"
        />
      </template>
    </Dialog>

    <!-- License Required Dialog -->
    <LicenseRequiredDialog
      :visible="licenseDialogVisible"
      @update:visible="licenseDialogVisible = $event"
      @goToLicense="goToLicense"
      @cancel="licenseDialogVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import AddProduct from "@components/AddProduct.vue";
import { formatCurrency } from "@composables/useFormatters";
import useApi from '@composables/useApi';
import { buildApiUrl } from "@/config";
import useNotification from "@composables/useNotification";
import useLicense from "@composables/useLicense";
import useProductStock from "@composables/useProductStock";
import useErrorHandler from "@composables/useErrorHandler";
import { useNavigation } from "@composables/useNavigation";
import EmptyState from "@components/EmptyState.vue";
import LoadingState from "@components/LoadingState.vue";
import { useDebugStore } from '@/stores/debug'
import LicenseRequiredDialog from "@components/LicenseRequiredDialog.vue";

const { t } = useI18n();
const api = useApi();
const { showSuccess, showError, showWarning } = useNotification();
const { handleApiError, handleError } = useErrorHandler();
const { licenseInfo, fetchLicenseInfo, isFeatureAvailable, isProAddonInstalled, isUltimateAddonInstalled } = useLicense();
const { navigateTo } = useNavigation();
const { getStockProductRatio, getStockClass } = useProductStock();
const debugStore = useDebugStore()

// Loading state
const loading = ref(true);
const totalRecords = ref(0);
const lazyParams = ref({
  first: 0,
  rows: 10,
  page: 0,
});

// Table data
const products = ref([]);

// Dialog management
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const productToDelete = ref(null);
const productToEdit = ref(null);

// New product object
const newProduct = ref({
  product: null,
  clients: [{ client: null, stock: null, price: null }],
});

// Customer management
const selectedProduct = ref(null);
const popoverRef = ref(null); // Reference for Popover

// License dialog state
const licenseDialogVisible = ref(false);

// Product loading
const loadProducts = async () => {
  loading.value = true;

  try {
    const response = await api.get(
      buildApiUrl(`products?page=${lazyParams.value.page + 1}&per_page=${lazyParams.value.rows}`)
    );
    
    if (!response.ok) {
      await handleApiError(response, {
        context: 'products.load',
        debugInfo: { page: lazyParams.value.page + 1, perPage: lazyParams.value.rows }
      });
      products.value = [];
      totalRecords.value = 0;
      return;
    }

    const data = await response.json();
    debugStore.log("ProductsView - API Response:", data);
    
    // Process data to extract display options
    const processedData = Array.isArray(data.items || data) ? (data.items || data).map(product => {
      // Default display options definition
      const defaultDisplayOptions = {
        hide_product: false,
        blur_product: false,
        hide_title: false,
        hide_price: false
      };
      
      // If product already has a display object, use it
      // Otherwise, check if options contain display parameters
      if (!product.display) {
        product.display = defaultDisplayOptions;
      } else {
        // Ensure all default properties are defined
        product.display = {
          ...defaultDisplayOptions,
          ...product.display
        };
      }
      
      return product;
    }) : [];

    // Update data
    products.value = processedData;
    totalRecords.value = data.total || (data.length ? data.length : 0);
  } catch (error) {
    handleError(error, {
      context: 'products.load',
      debugInfo: { action: 'loadProducts' }
    });
    products.value = [];
    totalRecords.value = 0;
  } finally {
    loading.value = false;
  }
};

// Pagination management
const onPage = (event) => {
  lazyParams.value = {
    first: event.first,
    rows: event.rows,
    page: event.page,
  };
  loadProducts();
};

// Toggle display options
const toggleDisplayOption = async (product, option) => {
  // Check license for premium features
  if ((option === 'blur_product' && !product.display[option] && !isFeatureAvailable('blur_product')) ||
      (option === 'hide_title' && !product.display[option] && !isFeatureAvailable('hide_title')) ||
      (option === 'hide_price' && !product.display[option] && !isFeatureAvailable('hide_price'))) {
    // Show license dialog instead of toast
    licenseDialogVisible.value = true;
    return;
  }

  // Previous option state to revert in case of error
  const previousValue = product.display[option];
  
  // Toggle option locally
  product.display[option] = !previousValue;

  try {
    // AJAX call to update option
    const response = await api.put(
      buildApiUrl(`products/${product.id}/display`),
      {
        display: product.display,
      }
    );
    
    if (!response.ok) {
      // If request fails, revert to previous state
      product.display[option] = previousValue;
      await handleApiError(response, {
        context: 'products.display_option',
        debugInfo: { productId: product.id, option, value: !previousValue }
      });
    } else {
      debugStore.log(`Display option ${option} updated successfully`);
      showSuccess(t('products.messages.display_option_success'));
    }
  } catch (error) {
    // In case of error, revert to previous state
    product.display[option] = previousValue;
    handleError(error, {
      context: 'products.display_option',
      debugInfo: { action: 'toggleDisplayOption', productId: product.id, option }
    });
  }
};

// Open dialog
const openDialog = () => {
  productToEdit.value = null;
  dialogVisible.value = true;
};

// Handler for product creation
const handleProductCreated = (newProductObj) => {
  debugStore.log("ProductsView - New VIP product created:", newProductObj);
  loadProducts();
};

// Handler for product update
const handleProductUpdated = (updatedProduct) => {
  debugStore.log("ProductsView - VIP product updated:", updatedProduct);
  loadProducts();
};

// Edit product
const editProduct = (product) => {
  productToEdit.value = product;
  dialogVisible.value = true;
};

// Confirm product deletion
const confirmDeleteProduct = (product) => {
  productToDelete.value = product;
  deleteDialogVisible.value = true;
};

// Delete product
const deleteProduct = async () => {
  if (!productToDelete.value) return;

  try {
    // AJAX call to delete product
    const response = await api.delete(
      buildApiUrl(`products/${productToDelete.value.id}`)
    );

    if (!response.ok) {
      await handleApiError(response, {
        context: 'products.delete',
        debugInfo: { productId: productToDelete.value.id }
      });
      return;
    }

    products.value = products.value.filter(
      (p) => p.id !== productToDelete.value.id
    );
    deleteDialogVisible.value = false;
    showSuccess(t('products.messages.delete_success'));
  } catch (error) {
    console.error("Error deleting product:", error);
    showError(t('products.messages.delete_error'));
  }
};

// Function to open customer popover
const openClientsPopover = (product, event) => {
  debugStore.log("ProductsView - Opening clients popover for product:", product);
  selectedProduct.value = product;
  // Open popover programmatically
  if (popoverRef.value) {
    popoverRef.value.toggle(event);
  }
};

// Determine stock progress bar class and percentage
const getStockPercentage = (assigned, total) => {
  return getStockProductRatio(assigned, total);
};

const getProgressBarColor = (assigned, total) => {
  const ratio = getStockProductRatio(assigned, total);
  return getStockClass(ratio);
};

const handleAvatarError = (event) => {
  handleError(event, {
    context: 'products.avatar',
    debugInfo: { action: 'handleAvatarError' }
  });
};

// Function to navigate to the license page
const goToLicense = () => {
  licenseDialogVisible.value = false;
  window.location.href = import.meta.env.VITE_WEBSITE_URL;
};

// Lifecycle hooks
onMounted(async () => {

  // Load license information
  await fetchLicenseInfo();
  
  // Load products
  loadProducts();
});
</script>
