<template>
  <!-- US-602: TabView for Clienți/Furnizori -->
  <div class="maturity-card">
    <div class="card-header">
      <h3>Analiză Scadențe</h3>
      <select
        v-model="selectedPeriod"
        @change="handlePeriodChange"
        class="period-selector"
        :disabled="isLoading"
      >
        <option value="7d">7 zile</option>
        <option value="1m">1 lună</option>
        <option value="3m">3 luni</option>
        <option value="6m">6 luni</option>
        <option value="12m">12 luni</option>
        <option value="all">Toate</option>
      </select>
    </div>

    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>Se încarcă analiza scadențelor...</p>
    </div>

    <div v-else-if="error" class="error-state">
      <div class="error-icon">!</div>
      <p>{{ error }}</p>
      <button @click="loadData" class="retry-btn">Încearcă din nou</button>
    </div>

    <!-- US-602: TabView for Clienți/Furnizori -->
    <TabView v-else v-model:activeIndex="activeTabIndex" class="maturity-tabs">
      <!-- Tab Clienți -->
      <TabPanel>
        <template #header>
          <span class="tab-header">
            <i class="pi pi-users"></i>
            <span class="tab-title">Clienți</span>
            <span class="tab-total">{{ formatCurrency(clientsTotal) }}</span>
          </span>
        </template>
        <div class="tab-content">
          <div class="maturity-list">
            <div
              v-for="(client, index) in clientsData"
              :key="`client-${index}`"
              class="maturity-item"
              :class="{
                overdue: client.daysOverdue > 0,
                critical: client.daysOverdue > 30,
              }"
            >
              <div class="item-info">
                <span class="entity-name">{{ client.name }}</span>
                <span class="due-info">
                  <span v-if="client.daysOverdue > 0" class="overdue-days">
                    Restant {{ client.daysOverdue }} zile
                  </span>
                  <span v-else class="due-date">
                    Scadent în {{ Math.abs(client.daysOverdue) }} zile
                  </span>
                </span>
              </div>
              <div class="amount-bar">
                <div class="bar-container">
                  <div
                    class="bar-fill clients-bar"
                    :style="{
                      width: getBarWidth(client.amount, maxClientAmount) + '%',
                    }"
                  ></div>
                </div>
                <span class="amount-value">{{
                  formatCurrency(client.amount)
                }}</span>
              </div>
            </div>
            <div v-if="clientsData.length === 0" class="empty-state">
              <i class="pi pi-inbox empty-icon"></i>
              <p>Nu există facturi de încasat pentru această perioadă</p>
            </div>
          </div>
          <div class="tab-summary">
            <span class="summary-label">Total de încasat:</span>
            <span class="summary-value clients-value">{{ formatCurrency(clientsTotal) }}</span>
          </div>
        </div>
      </TabPanel>

      <!-- Tab Furnizori -->
      <TabPanel>
        <template #header>
          <span class="tab-header">
            <i class="pi pi-building"></i>
            <span class="tab-title">Furnizori</span>
            <span class="tab-total">{{ formatCurrency(suppliersTotal) }}</span>
          </span>
        </template>
        <div class="tab-content">
          <div class="maturity-list">
            <div
              v-for="(supplier, index) in suppliersData"
              :key="`supplier-${index}`"
              class="maturity-item"
              :class="{
                overdue: supplier.daysOverdue > 0,
                critical: supplier.daysOverdue > 30,
              }"
            >
              <div class="item-info">
                <span class="entity-name">{{ supplier.name }}</span>
                <span class="due-info">
                  <span v-if="supplier.daysOverdue > 0" class="overdue-days">
                    Restant {{ supplier.daysOverdue }} zile
                  </span>
                  <span v-else class="due-date">
                    Scadent în {{ Math.abs(supplier.daysOverdue) }} zile
                  </span>
                </span>
              </div>
              <div class="amount-bar">
                <div class="bar-container">
                  <div
                    class="bar-fill suppliers-bar"
                    :style="{
                      width:
                        getBarWidth(supplier.amount, maxSupplierAmount) + '%',
                    }"
                  ></div>
                </div>
                <span class="amount-value">{{
                  formatCurrency(supplier.amount)
                }}</span>
              </div>
            </div>
            <div v-if="suppliersData.length === 0" class="empty-state">
              <i class="pi pi-inbox empty-icon"></i>
              <p>Nu există facturi de plătit pentru această perioadă</p>
            </div>
          </div>
          <div class="tab-summary">
            <span class="summary-label">Total de plătit:</span>
            <span class="summary-value suppliers-value">{{ formatCurrency(suppliersTotal) }}</span>
          </div>
        </div>
      </TabPanel>
    </TabView>

    <!-- Balance Indicator -->
    <div v-if="!isLoading && !error" class="balance-indicator">
      <div class="balance-content">
        <div class="balance-text">
          <span class="balance-label">{{ balanceLabel }}</span>
          <span class="balance-amount" :class="balanceClass">
            {{ formatCurrency(Math.abs(balance)) }}
          </span>
        </div>
        <div v-if="recommendations.length > 0" class="recommendations">
          <details>
            <summary>Recomandări</summary>
            <ul>
              <li v-for="(rec, index) in recommendations" :key="index">
                {{ rec }}
              </li>
            </ul>
          </details>
        </div>
      </div>
    </div>

    <!-- Footer with period info -->
    <div v-if="!isLoading && !error" class="card-footer">
      <div class="period-info">
        <span class="period-label">Perioada analizată:</span>
        <span class="period-value">{{ getPeriodLabel(selectedPeriod) }}</span>
      </div>
      <div class="last-updated">
        <span class="update-label">Actualizat:</span>
        <span class="update-time">{{ formatLastUpdated(lastUpdated) }}</span>
        <button
          @click="refreshData"
          class="refresh-btn"
          :disabled="isLoading"
          title="Reîmprospătează datele"
        >
          <i
            class="pi pi-refresh refresh-icon"
            :class="{ spinning: isLoading }"
          ></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import TabView from "primevue/tabview";
import TabPanel from "primevue/tabpanel";
import { useDashboardStore } from "@reports/stores/dashboard";

// US-602: Tab state storage key
const TAB_STORAGE_KEY = "maturity_analysis_active_tab";

// Props
const props = defineProps({
  companyId: {
    type: [Number, String],
    required: true,
  },
  // US-602: Allow external tab control (e.g., from route query)
  initialTab: {
    type: Number,
    default: null,
  },
});

// Emits
const emit = defineEmits(["periodChanged", "tabChanged"]);

// Store
const dashboardStore = useDashboardStore();

// US-602: Initialize tab from prop, localStorage, or default to 0 (Clienți)
const getInitialTabIndex = () => {
  if (props.initialTab !== null) {
    return props.initialTab;
  }
  const stored = localStorage.getItem(TAB_STORAGE_KEY);
  return stored !== null ? parseInt(stored, 10) : 0;
};

// Reactive state
const activeTabIndex = ref(getInitialTabIndex());
const selectedPeriod = ref("1m");
const isLoading = ref(false);
const error = ref(null);
const lastUpdated = ref(null);

// US-602: Watch tab changes and persist to localStorage
watch(activeTabIndex, (newIndex) => {
  localStorage.setItem(TAB_STORAGE_KEY, newIndex.toString());
  emit("tabChanged", newIndex);
});

// Mock data structure - in production this would come from API
const maturityData = ref({
  clients: [],
  suppliers: [],
  balance: 0,
  recommendations: [],
});

// Romanian currency formatter
const formatCurrency = (value) => {
  if (value === null || value === undefined) return "0,00 RON";
  return new Intl.NumberFormat("ro-RO", {
    style: "currency",
    currency: "RON",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
};

// Computed properties
const clientsData = computed(() => maturityData.value.clients || []);
const suppliersData = computed(() => maturityData.value.suppliers || []);
const recommendations = computed(
  () => maturityData.value.recommendations || [],
);

const clientsTotal = computed(() =>
  clientsData.value.reduce((sum, client) => sum + (client.amount || 0), 0),
);

const suppliersTotal = computed(() =>
  suppliersData.value.reduce(
    (sum, supplier) => sum + (supplier.amount || 0),
    0,
  ),
);

const balance = computed(() => clientsTotal.value - suppliersTotal.value);

const balanceClass = computed(() =>
  balance.value < 0 ? "deficit" : "surplus",
);

const balanceIcon = computed(() => (balance.value < 0 ? "📉" : "📈"));

const balanceLabel = computed(() =>
  balance.value < 0 ? "Deficit estimat:" : "Surplus estimat:",
);

const maxClientAmount = computed(() =>
  Math.max(...clientsData.value.map((c) => c.amount || 0), 1),
);

const maxSupplierAmount = computed(() =>
  Math.max(...suppliersData.value.map((s) => s.amount || 0), 1),
);

// Methods
const getBarWidth = (amount, maxAmount) => {
  return maxAmount > 0 ? Math.min((amount / maxAmount) * 100, 100) : 0;
};

const getPeriodLabel = (period) => {
  const labels = {
    "7d": "Toate restanțele + următoarele 7 zile",
    "1m": "Toate restanțele + următoarea lună",
    "3m": "Toate restanțele + următoarele 3 luni",
    "6m": "Toate restanțele + următoarele 6 luni",
    "12m": "Toate restanțele + următorul an",
    all: "Toate soldurile (fără filtru)",
  };
  return labels[period] || period;
};

const formatLastUpdated = (timestamp) => {
  if (!timestamp) return "Necunoscut";
  return new Date(timestamp).toLocaleString("ro-RO");
};

const handlePeriodChange = () => {
  emit("periodChanged", selectedPeriod.value);
  loadData();
};

const refreshData = () => {
  loadData(true);
};

const loadData = async (forceRefresh = false) => {
  if (!props.companyId) {
    error.value = "ID firmă necunoscut";
    return;
  }

  isLoading.value = true;
  error.value = null;

  try {
    // Apelăm API-ul real pentru a obține datele de scadențe
    const response = await dashboardStore.loadMaturityData(
      props.companyId,
      selectedPeriod.value,
    );

    if (response && response.success) {
      maturityData.value = response.data;
      lastUpdated.value = new Date();
    } else {
      throw new Error(response?.error || "Eroare la încărcarea datelor");
    }
  } catch (err) {
    console.error("Failed to load maturity data:", err);
    error.value =
      err.message ||
      "Eroare la încărcarea datelor. Vă rugăm încercați din nou.";
  } finally {
    isLoading.value = false;
  }
};

// Watchers
watch(
  () => props.companyId,
  (newCompanyId) => {
    if (newCompanyId) {
      loadData();
    }
  },
  { immediate: false },
);

// Lifecycle
onMounted(() => {
  if (props.companyId) {
    loadData();
  }
});
</script>

<style scoped>
/* Base Card Styles */
.maturity-card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--card-radius, 8px);
  padding: 0;
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-fast, 0.3s ease);
  overflow: hidden;
}

.maturity-card:hover {
  box-shadow: var(--shadow-md);
  border-color: var(--color-primary);
}

/* Card Header */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-lg, 1rem);
  border-bottom: 1px solid var(--color-border);
  background: transparent;
}

.card-header h3 {
  margin: 0;
  font-size: var(--text-lg, 1.125rem);
  font-weight: var(--font-semibold, 600);
  color: var(--color-text);
}

.period-selector {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm, 4px);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: var(--text-sm, 0.875rem);
  cursor: pointer;
  transition: border-color 0.2s ease;
}

.period-selector:hover {
  border-color: var(--color-primary);
}

.period-selector:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Loading and Error States */
.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl, 2rem);
  text-align: center;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--color-border);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--space-md, 1rem);
}

.error-icon {
  font-size: 2rem;
  margin-bottom: var(--space-sm, 0.5rem);
}

.retry-btn {
  margin-top: var(--space-md, 1rem);
  padding: 0.5rem 1rem;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: var(--radius-sm, 4px);
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.retry-btn:hover {
  background: var(--color-primary-dark);
}

/* US-602: TabView Styles */
.maturity-tabs {
  border: none;
}

/* Tab header styles */
.tab-header {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-xs) 0;
}

.tab-header i {
  font-size: var(--text-base);
  color: var(--text-color-secondary);
}

.tab-title {
  font-weight: var(--font-medium);
  color: var(--text-color);
}

.tab-total {
  font-size: var(--text-xs);
  font-weight: var(--font-bold);
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  color: var(--text-color);
}

/* Tab content */
.tab-content {
  padding: var(--space-md);
  min-height: 280px;
  display: flex;
  flex-direction: column;
}

/* Tab summary */
.tab-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-md);
  margin-top: auto;
  background: var(--surface-hover);
  border-radius: var(--radius-md);
}

.summary-label {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-color-secondary);
}

.summary-value {
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
}

.summary-value.clients-value {
  color: var(--color-primary);
}

.summary-value.suppliers-value {
  color: var(--color-secondary, #6b7280);
}

/* Entity name (unified for clients and suppliers) */
.entity-name {
  font-weight: var(--font-medium);
  color: var(--text-color);
  font-size: var(--text-sm);
}

/* Empty state icon */
.empty-icon {
  font-size: var(--text-4xl);
  color: var(--text-color-secondary);
  opacity: 0.5;
  margin-bottom: var(--space-md);
}

/* Maturity Lists */
.maturity-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-sm, 0.5rem);
  max-height: 250px;
  overflow-y: auto;
  padding-right: var(--space-xs, 0.25rem);
}

.maturity-list::-webkit-scrollbar {
  width: 4px;
}

.maturity-list::-webkit-scrollbar-track {
  background: var(--color-bg-secondary, #f8f9fa);
  border-radius: 2px;
}

.maturity-list::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 2px;
}

/* Maturity Items */
.maturity-item {
  padding: var(--space-sm, 0.5rem);
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm, 4px);
  transition: all 0.2s ease;
}

.maturity-item:hover {
  background: var(--color-bg-secondary, #f8f9fa);
  border-color: var(--color-primary);
}

.maturity-item.overdue {
  border: 1px solid var(--color-border);
}

.maturity-item.critical {
  border: 1px solid var(--color-border);
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-xs, 0.25rem);
}

/* entity-name defined in TabView styles above */

.due-info {
  font-size: var(--text-xs, 0.75rem);
  color: var(--color-text-secondary);
}

.overdue-days {
  color: var(--color-text);
  font-weight: var(--font-medium, 500);
}

.due-date {
  color: var(--color-text-secondary);
}

/* Amount Bars */
.amount-bar {
  display: flex;
  align-items: center;
  gap: var(--space-sm, 0.5rem);
}

.bar-container {
  flex: 1;
  height: 8px;
  background: var(--color-bg-secondary, #f8f9fa);
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.clients-bar {
  background: var(--color-primary);
}

.suppliers-bar {
  background: var(--color-secondary, #6b7280);
}

.amount-value {
  font-size: var(--text-xs, 0.75rem);
  font-weight: var(--font-bold, 700);
  color: var(--color-text);
  white-space: nowrap;
}

/* Empty State */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl, 2rem);
  text-align: center;
  color: var(--color-text-secondary);
}

/* Balance Indicator */
.balance-indicator {
  padding: var(--space-lg, 1rem) 0;
  border-top: 1px solid var(--color-border);
  background: transparent;
}

.balance-content {
  display: flex;
  align-items: center;
  gap: var(--space-md, 1rem);
}

.balance-text {
  display: flex;
  flex-direction: column;
  gap: var(--space-xs, 0.25rem);
}

.balance-label {
  font-size: var(--text-sm, 0.875rem);
  color: var(--color-text-secondary);
}

.balance-amount {
  font-size: var(--text-lg, 1.125rem);
  font-weight: var(--font-bold, 700);
  color: var(--color-text);
}

.balance-amount.surplus {
  color: var(--color-text);
}

.balance-amount.deficit {
  color: var(--color-text);
}

/* Recommendations */
.recommendations {
  margin-left: auto;
}

.recommendations details {
  cursor: pointer;
}

.recommendations summary {
  font-size: var(--text-sm, 0.875rem);
  color: var(--color-primary);
  list-style: none;
  padding: 0.5rem;
  border-radius: var(--radius-sm, 4px);
  transition: background-color 0.2s ease;
}

.recommendations summary:hover {
  background: rgba(59, 130, 246, 0.1);
}

.recommendations ul {
  margin: var(--space-sm, 0.5rem) 0 0 0;
  padding-left: var(--space-lg, 1rem);
}

.recommendations li {
  font-size: var(--text-sm, 0.875rem);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-xs, 0.25rem);
}

/* Card Footer */
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-md, 0.75rem) var(--space-lg, 1rem);
  border-top: 1px solid var(--color-border);
  background: var(--color-bg);
}

.period-info,
.last-updated {
  display: flex;
  align-items: center;
  gap: var(--space-xs, 0.25rem);
  font-size: var(--text-xs, 0.75rem);
}

.period-label,
.update-label {
  color: var(--color-text-secondary);
}

.period-value,
.update-time {
  color: var(--color-text);
  font-weight: var(--font-medium, 500);
}

.refresh-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  margin-left: var(--space-sm, 0.5rem);
  border-radius: var(--radius-sm, 4px);
  transition: background-color 0.2s ease;
}

.refresh-btn:hover {
  background: var(--color-bg-secondary, #f8f9fa);
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.refresh-icon {
  display: inline-block;
  font-size: var(--text-sm, 0.875rem);
  transition: transform 0.3s ease;
}

.refresh-icon.spinning {
  animation: spin 1s linear infinite;
}

/* Animations */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* Responsive Design */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: var(--space-sm);
    align-items: stretch;
  }

  .card-header h3 {
    text-align: center;
    font-size: var(--text-base);
  }

  .period-selector {
    width: 100%;
  }

  /* US-602: Mobile tab adjustments */
  .tab-content {
    padding: var(--space-sm);
    min-height: 250px;
  }

  .tab-header {
    flex-wrap: wrap;
    gap: var(--space-xs);
  }

  .tab-total {
    font-size: var(--text-xs);
    padding: 2px var(--space-xs);
  }

  .tab-summary {
    padding: var(--space-sm);
    flex-direction: column;
    gap: var(--space-xs);
    text-align: center;
  }

  .balance-content {
    flex-direction: column;
    text-align: center;
  }

  .recommendations {
    margin-left: 0;
    width: 100%;
  }

  .card-footer {
    flex-direction: column;
    gap: var(--space-sm);
    align-items: center;
  }
}

@media (max-width: 480px) {
  .maturity-card {
    margin: 0 calc(-1 * var(--space-sm));
  }

  .card-header,
  .balance-indicator,
  .card-footer {
    padding: var(--space-md);
  }

  .maturity-list {
    max-height: 200px;
  }

  .tab-title {
    font-size: var(--text-sm);
  }
}
</style>
