<template>
  <div class="maturity-details-card">
    <!-- Header -->
    <div class="card-header">
      <h3 class="card-title">Analiză Scadențe & Date Detaliate</h3>
      <div class="header-controls">
        <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>
        <button
          @click="refreshData"
          class="refresh-btn"
          :disabled="isLoading"
          title="Reîmprospătează datele"
        >
          <i class="pi pi-refresh" :class="{ spinning: isLoading }"></i>
        </button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>Se încarcă datele...</p>
    </div>

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

    <!-- Main Content -->
    <div v-else class="card-content">
      <!-- Nivel 1: Comparație Grafică -->
      <div class="comparison-section">
        <!-- Clienți Side -->
        <div class="comparison-side clients">
          <div class="side-header">
            <span class="side-label">Clienți - De încasat</span>
            <span class="side-total">{{ formatCurrency(clientsTotal) }}</span>
          </div>
          <div class="maturity-list">
            <div
              v-for="(client, index) in clientsData"
              :key="`client-${index}`"
              class="maturity-item"
              :class="getMaturityClass(client.daysOverdue)"
            >
              <div class="item-header">
                <span class="item-name">{{ client.name }}</span>
                <span
                  class="item-status"
                  :class="getStatusClass(client.daysOverdue)"
                >
                  {{ getStatusText(client.daysOverdue) }}
                </span>
              </div>
              <div class="progress-bar">
                <div
                  class="progress-fill clients-fill"
                  :style="{
                    width: getBarWidth(client.amount, maxClientAmount) + '%',
                  }"
                ></div>
              </div>
              <span class="item-amount">{{
                formatCurrency(client.amount)
              }}</span>
            </div>
            <div v-if="clientsData.length === 0" class="empty-state">
              <p>Nu există facturi de încasat</p>
            </div>
          </div>
        </div>

        <!-- Divider -->
        <div class="comparison-divider"></div>

        <!-- Furnizori Side -->
        <div class="comparison-side suppliers">
          <div class="side-header">
            <span class="side-label">Furnizori - De plătit</span>
            <span class="side-total">{{ formatCurrency(suppliersTotal) }}</span>
          </div>
          <div class="maturity-list">
            <div
              v-for="(supplier, index) in suppliersData"
              :key="`supplier-${index}`"
              class="maturity-item"
              :class="getMaturityClass(supplier.daysOverdue)"
            >
              <div class="item-header">
                <span class="item-name">{{ supplier.name }}</span>
                <span
                  class="item-status"
                  :class="getStatusClass(supplier.daysOverdue)"
                >
                  {{ getStatusText(supplier.daysOverdue) }}
                </span>
              </div>
              <div class="progress-bar">
                <div
                  class="progress-fill suppliers-fill"
                  :style="{
                    width:
                      getBarWidth(supplier.amount, maxSupplierAmount) + '%',
                  }"
                ></div>
              </div>
              <span class="item-amount">{{
                formatCurrency(supplier.amount)
              }}</span>
            </div>
            <div v-if="suppliersData.length === 0" class="empty-state">
              <p>Nu există facturi de plătit</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Balance Indicator -->
      <div class="balance-section">
        <div class="balance-info">
          <span class="balance-label">{{ balanceLabel }}</span>
          <span class="balance-amount" :class="balanceClass">
            {{ formatCurrency(Math.abs(balance)) }}
          </span>
        </div>
        <div v-if="statusSummary" class="status-summary">
          {{ statusSummary }}
        </div>
      </div>

      <!-- Separator -->
      <div class="section-separator"></div>

      <!-- Nivel 2: Tabel Detaliat -->
      <div class="details-section">
        <div class="details-header" @click="toggleDetailsExpanded">
          <div class="details-header-left">
            <span class="collapse-icon">{{
              isDetailsExpanded ? "▼" : "▶"
            }}</span>
            <h4 class="details-title">Tabel Facturi Detaliate</h4>
          </div>
          <button class="toggle-details-btn">
            {{ isDetailsExpanded ? "Ascunde" : "Afișează" }}
          </button>
        </div>

        <!-- Details Content -->
        <div v-show="isDetailsExpanded" class="details-content">
          <!-- Controls -->
          <div class="details-controls">
            <select
              v-model="selectedType"
              @change="loadDetailedData"
              class="type-selector"
            >
              <option value="clients">Clienți</option>
              <option value="suppliers">Furnizori</option>
              <option value="treasury">Trezorerie</option>
            </select>

            <div class="search-wrapper">
              <input
                v-model="searchTerm"
                @input="handleSearch"
                type="text"
                placeholder="Căutare..."
                class="search-input"
              />
              <i class="pi pi-search"></i>
            </div>

            <div class="export-buttons">
              <button
                @click="exportExcel"
                class="export-btn"
                title="Export Excel"
              >
                <i class="pi pi-file-excel"></i>
              </button>
              <button @click="exportPDF" class="export-btn" title="Export PDF">
                <i class="pi pi-file-pdf"></i>
              </button>
            </div>
          </div>

          <!-- Table (Desktop) & Cards (Mobile) -->
          <div class="table-wrapper">
            <!-- Desktop Table -->
            <table class="details-table desktop-only">
              <thead>
                <tr>
                  <th v-for="column in displayColumns" :key="column.field">
                    {{ column.header }}
                  </th>
                </tr>
              </thead>
              <tbody v-if="selectedType === 'treasury'">
                <tr v-for="row in paginatedData" :key="row.id">
                  <td v-for="column in displayColumns" :key="column.field">
                    {{ formatValue(row[column.field], column.type) }}
                  </td>
                </tr>
              </tbody>
              <tbody v-else>
                <template v-for="group in paginatedGroups" :key="group.name">
                  <!-- Single invoice row -->
                  <tr v-if="group.facturi.length === 1" class="single-row">
                    <td>
                      <strong>{{ group.name }}</strong>
                    </td>
                    <td>{{ group.facturi[0].numar_document }}</td>
                    <td>
                      {{ formatValue(group.facturi[0].data_document, "date") }}
                    </td>
                    <td>
                      {{ formatValue(group.facturi[0].data_scadenta, "date") }}
                    </td>
                    <td>
                      {{ formatValue(group.facturi[0].facturat, "currency") }}
                    </td>
                    <td>
                      {{
                        formatValue(
                          group.facturi[0][
                            selectedType === "clients" ? "incasat" : "achitat"
                          ],
                          "currency",
                        )
                      }}
                    </td>
                    <td
                      :class="{
                        'sold-restant': group.facturi[0].status === 'Restant',
                      }"
                    >
                      {{ formatValue(group.facturi[0].sold, "currency") }}
                    </td>
                  </tr>

                  <!-- Multiple invoices -->
                  <template v-else>
                    <tr class="group-row" @click="toggleGroup(group.name)">
                      <td>
                        <strong>{{ group.name }}</strong>
                        <span class="count-badge"
                          >({{ group.facturi.length }})</span
                        >
                      </td>
                      <td colspan="5"></td>
                      <td
                        class="subtotal"
                        :class="{ 'sold-restant': group.hasRestant }"
                      >
                        <strong>{{
                          formatValue(group.totalSold, "currency")
                        }}</strong>
                      </td>
                    </tr>
                    <template v-if="isGroupExpanded(group.name)">
                      <tr
                        v-for="(factura, idx) in group.facturi"
                        :key="`${group.name}-${idx}`"
                        class="detail-row"
                      >
                        <td class="detail-indent">
                          {{ factura.client || factura.furnizor || "" }}
                        </td>
                        <td>{{ factura.numar_document }}</td>
                        <td>
                          {{ formatValue(factura.data_document, "date") }}
                        </td>
                        <td>
                          {{ formatValue(factura.data_scadenta, "date") }}
                        </td>
                        <td>{{ formatValue(factura.facturat, "currency") }}</td>
                        <td>
                          {{
                            formatValue(
                              factura[
                                selectedType === "clients"
                                  ? "incasat"
                                  : "achitat"
                              ],
                              "currency",
                            )
                          }}
                        </td>
                        <td
                          :class="{
                            'sold-restant': factura.status === 'Restant',
                          }"
                        >
                          {{ formatValue(factura.sold, "currency") }}
                        </td>
                      </tr>
                    </template>
                  </template>
                </template>
              </tbody>
              <tfoot>
                <tr class="totals-row">
                  <td><strong>TOTAL</strong></td>
                  <td
                    v-for="column in displayColumns.slice(1)"
                    :key="column.field"
                  >
                    <strong v-if="column.showTotal">
                      {{
                        formatValue(calculateTotal(column.field), column.type)
                      }}
                    </strong>
                  </td>
                </tr>
              </tfoot>
            </table>

            <!-- Mobile Cards -->
            <div class="details-cards mobile-only">
              <template v-if="selectedType === 'treasury'">
                <div
                  v-for="row in paginatedData"
                  :key="row.id"
                  class="detail-card"
                >
                  <div class="card-row">
                    <span class="card-label">Cont:</span>
                    <span class="card-value"
                      >{{ row.cont }} - {{ row.nume_cont }}</span
                    >
                  </div>
                  <div class="card-row">
                    <span class="card-label">Sold:</span>
                    <span class="card-value sold-value">{{
                      formatValue(row.sold, "currency")
                    }}</span>
                  </div>
                  <div class="card-row">
                    <span class="card-label">Valută:</span>
                    <span class="card-value">{{ row.valuta }}</span>
                  </div>
                </div>
              </template>
              <template v-else>
                <template v-for="group in paginatedGroups" :key="group.name">
                  <!-- Single invoice card -->
                  <div
                    v-if="group.facturi.length === 1"
                    class="detail-card single-card"
                  >
                    <div class="card-header-row">
                      <strong>{{ group.name }}</strong>
                      <span
                        class="status-badge"
                        :class="{
                          restant: group.facturi[0].status === 'Restant',
                        }"
                      >
                        {{ group.facturi[0].status }}
                      </span>
                    </div>
                    <div class="card-row">
                      <span class="card-label">Nr. Document:</span>
                      <span class="card-value">{{
                        group.facturi[0].numar_document
                      }}</span>
                    </div>
                    <div class="card-row">
                      <span class="card-label">Data Document:</span>
                      <span class="card-value">{{
                        formatValue(group.facturi[0].data_document, "date")
                      }}</span>
                    </div>
                    <div class="card-row">
                      <span class="card-label">Data Scadență:</span>
                      <span class="card-value">{{
                        formatValue(group.facturi[0].data_scadenta, "date")
                      }}</span>
                    </div>
                    <div class="card-row highlight">
                      <span class="card-label">Sold:</span>
                      <span
                        class="card-value sold-value"
                        :class="{
                          'sold-restant': group.facturi[0].status === 'Restant',
                        }"
                      >
                        {{ formatValue(group.facturi[0].sold, "currency") }}
                      </span>
                    </div>
                  </div>

                  <!-- Multiple invoices group card -->
                  <div v-else class="detail-card group-card">
                    <div
                      class="card-header-row"
                      @click="toggleGroup(group.name)"
                    >
                      <div>
                        <strong>{{ group.name }}</strong>
                        <span class="count-badge"
                          >({{ group.facturi.length }})</span
                        >
                      </div>
                      <div class="group-card-right">
                        <span
                          class="sold-value"
                          :class="{ 'sold-restant': group.hasRestant }"
                        >
                          {{ formatValue(group.totalSold, "currency") }}
                        </span>
                        <span class="collapse-icon">{{
                          isGroupExpanded(group.name) ? "▼" : "▶"
                        }}</span>
                      </div>
                    </div>
                    <!-- Expanded invoices -->
                    <div v-if="isGroupExpanded(group.name)" class="sub-cards">
                      <div
                        v-for="(factura, idx) in group.facturi"
                        :key="`${group.name}-${idx}`"
                        class="sub-card"
                      >
                        <div class="card-row">
                          <span class="card-label">Nr. Document:</span>
                          <span class="card-value">{{
                            factura.numar_document
                          }}</span>
                        </div>
                        <div class="card-row">
                          <span class="card-label">Scadență:</span>
                          <span class="card-value">{{
                            formatValue(factura.data_scadenta, "date")
                          }}</span>
                        </div>
                        <div class="card-row highlight">
                          <span class="card-label">Sold:</span>
                          <span
                            class="card-value sold-value"
                            :class="{
                              'sold-restant': factura.status === 'Restant',
                            }"
                          >
                            {{ formatValue(factura.sold, "currency") }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </template>
            </div>
          </div>

          <!-- Pagination -->
          <div class="pagination-wrapper">
            <Paginator
              v-model:rows="rowsPerPage"
              :totalRecords="totalRecords"
              v-model:first="firstRow"
              :rowsPerPageOptions="[10, 25, 50, 100]"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <div v-if="!isLoading && !error" class="card-footer">
      <div class="footer-info">
        <span class="info-label">Perioada:</span>
        <span class="info-value">{{ getPeriodLabel(selectedPeriod) }}</span>
      </div>
      <div class="footer-info">
        <span class="info-label">Actualizat:</span>
        <span class="info-value">{{ formatLastUpdated(lastUpdated) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useDashboardStore } from "@reports/stores/dashboard";
import { useCompanyStore } from "@reports/stores/sharedStores";
import { useAccountingPeriodStore } from "@reports/stores/sharedStores";
import { useToast } from "primevue/usetoast";
import Paginator from "primevue/paginator";
import * as XLSX from "xlsx";
import jsPDF from "jspdf";
import "jspdf-autotable";

// Props
const props = defineProps({
  companyId: {
    type: [Number, String],
    required: true,
  },
});

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

// Stores
const dashboardStore = useDashboardStore();
const companyStore = useCompanyStore();
const periodStore = useAccountingPeriodStore();
const toast = useToast();

// State - Maturity Analysis
const selectedPeriod = ref("1m");
const isLoading = ref(false);
const error = ref(null);
const lastUpdated = ref(null);
const maturityData = ref({
  clients: [],
  suppliers: [],
  balance: 0,
  recommendations: [],
});

// State - Detailed Data
const selectedType = ref("clients");
const searchTerm = ref("");
const detailedData = ref([]);
const firstRow = ref(0);
const rowsPerPage = ref(25);
const expandedGroups = ref(new Set());
const isDetailsExpanded = ref(false);

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

// Computed - Maturity Analysis
const clientsData = computed(() => maturityData.value.clients || []);
const suppliersData = computed(() => maturityData.value.suppliers || []);

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 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),
);

const statusSummary = computed(() => {
  const criticalOverdue = [...clientsData.value, ...suppliersData.value].filter(
    (item) => item.daysOverdue > 30,
  ).length;
  const upcoming = [...clientsData.value, ...suppliersData.value].filter(
    (item) => item.daysOverdue <= 0 && item.daysOverdue >= -7,
  ).length;

  if (criticalOverdue > 0 || upcoming > 0) {
    const parts = [];
    if (criticalOverdue > 0) parts.push(`${criticalOverdue} restanțe critice`);
    if (upcoming > 0) parts.push(`${upcoming} scadențe apropiate`);
    return parts.join(" • ");
  }
  return null;
});

// Computed - Detailed Data
const columns = computed(() => {
  switch (selectedType.value) {
    case "clients":
      return [
        { field: "client", header: "Client", type: "text" },
        { field: "numar_document", header: "Nr. Document", type: "text" },
        { field: "data_document", header: "Data Document", type: "date" },
        { field: "data_scadenta", header: "Data Scadență", type: "date" },
        {
          field: "facturat",
          header: "Facturat",
          type: "currency",
          showTotal: true,
        },
        {
          field: "incasat",
          header: "Încasat",
          type: "currency",
          showTotal: true,
        },
        { field: "sold", header: "Sold", type: "currency", showTotal: true },
      ];
    case "suppliers":
      return [
        { field: "furnizor", header: "Furnizor", type: "text" },
        { field: "numar_document", header: "Nr. Document", type: "text" },
        { field: "data_document", header: "Data Document", type: "date" },
        { field: "data_scadenta", header: "Data Scadență", type: "date" },
        {
          field: "facturat",
          header: "Facturat",
          type: "currency",
          showTotal: true,
        },
        {
          field: "achitat",
          header: "Achitat",
          type: "currency",
          showTotal: true,
        },
        { field: "sold", header: "Sold", type: "currency", showTotal: true },
      ];
    case "treasury":
      return [
        { field: "cont", header: "Cont", type: "text" },
        { field: "nume_cont", header: "Nume Cont", type: "text" },
        { field: "sold", header: "Sold", type: "currency", showTotal: true },
        { field: "valuta", header: "Valută", type: "text" },
        { field: "tip", header: "Tip", type: "text" },
      ];
    default:
      return [];
  }
});

const displayColumns = computed(() => columns.value);

const filteredData = computed(() => {
  if (!searchTerm.value) return detailedData.value;
  return detailedData.value.filter((row) => {
    return Object.values(row).some((val) =>
      String(val).toLowerCase().includes(searchTerm.value.toLowerCase()),
    );
  });
});

const groupedData = computed(() => {
  if (selectedType.value === "treasury") return [];

  const groups = {};
  const nameField = selectedType.value === "clients" ? "client" : "furnizor";

  filteredData.value.forEach((row) => {
    const name = row[nameField];
    if (!name) return;

    if (!groups[name]) {
      groups[name] = {
        name: name,
        facturi: [],
        totalSold: 0,
        hasRestant: false,
      };
    }

    groups[name].facturi.push(row);
    groups[name].totalSold += row.sold || 0;
    if (row.status === "Restant") {
      groups[name].hasRestant = true;
    }
  });

  return Object.values(groups);
});

// No local pagination needed - backend handles it
const paginatedGroups = computed(() => {
  if (selectedType.value === "treasury") return [];
  // Return all grouped data (already paginated by backend)
  return groupedData.value;
});

const paginatedData = computed(() => {
  if (selectedType.value !== "treasury") return [];
  // Return all filtered data (already paginated by backend)
  return filteredData.value;
});

const totalRecords = computed(() => {
  // Return total from backend response (total clients/suppliers, not invoices)
  return dashboardStore.detailedDataTotal || groupedData.value.length;
});

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

const getMaturityClass = (daysOverdue) => {
  if (daysOverdue > 30) return "critical";
  if (daysOverdue > 0) return "overdue";
  return "in-term";
};

const getStatusClass = (daysOverdue) => {
  if (daysOverdue > 30) return "status-critical";
  if (daysOverdue > 0) return "status-overdue";
  return "status-ok";
};

const getStatusText = (daysOverdue) => {
  if (daysOverdue > 0) return `Restant ${daysOverdue}z`;
  if (daysOverdue === 0) return "Scadent azi";
  return `Scadent ${Math.abs(daysOverdue)}z`;
};

const getPeriodLabel = (period) => {
  const labels = {
    "7d": "Restanțe + 7 zile",
    "1m": "Restanțe + 1 lună",
    "3m": "Restanțe + 3 luni",
    "6m": "Restanțe + 6 luni",
    "12m": "Restanțe + 1 an",
    all: "Toate soldurile",
  };
  return labels[period] || period;
};

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

// Methods - Detailed Data
const toggleGroup = (groupName) => {
  if (expandedGroups.value.has(groupName)) {
    expandedGroups.value.delete(groupName);
  } else {
    expandedGroups.value.add(groupName);
  }
};

const isGroupExpanded = (groupName) => {
  return expandedGroups.value.has(groupName);
};

const toggleDetailsExpanded = () => {
  isDetailsExpanded.value = !isDetailsExpanded.value;
  if (isDetailsExpanded.value && detailedData.value.length === 0) {
    loadDetailedData();
  }
};

const formatValue = (value, type) => {
  switch (type) {
    case "currency":
      return formatCurrency(value);
    case "date":
      if (!value) return "-";
      const date = new Date(value);
      if (isNaN(date.getTime())) return value;
      return date.toLocaleDateString("ro-RO", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });
    default:
      return value;
  }
};

const calculateTotal = (field) => {
  return filteredData.value.reduce((sum, row) => sum + (row[field] || 0), 0);
};

const handleSearch = () => {
  firstRow.value = 0;
  expandedGroups.value.clear();
};

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

// Data loading
const loadMaturityData = async () => {
  if (!props.companyId) {
    error.value = "ID firmă necunoscut";
    return;
  }

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

  const luna = periodStore.selectedPeriod?.luna || null;
  const an = periodStore.selectedPeriod?.an || null;

  try {
    const response = await dashboardStore.loadMaturityData(
      props.companyId,
      selectedPeriod.value,
      luna,
      an,
    );

    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";
  } finally {
    isLoading.value = false;
  }
};

const loadDetailedData = async () => {
  try {
    if (!companyStore.selectedCompany) {
      toast.add({
        severity: "warn",
        summary: "Atenție",
        detail: "Vă rugăm să selectați o companie",
        life: 3000,
      });
      return;
    }

    // Calculate page number from firstRow
    const page = Math.floor(firstRow.value / rowsPerPage.value) + 1;

    const luna = periodStore.selectedPeriod?.luna || null;
    const an = periodStore.selectedPeriod?.an || null;

    const response = await dashboardStore.loadDetailedData(
      selectedType.value,
      companyStore.selectedCompany.id_firma,
      page,
      rowsPerPage.value,
      searchTerm.value,
      luna,
      an,
    );
    detailedData.value = response.data;
    expandedGroups.value.clear();
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "Nu s-au putut încărca datele detaliate",
    });
  }
};

const refreshData = async () => {
  await Promise.all([
    loadMaturityData(),
    isDetailsExpanded.value ? loadDetailedData() : Promise.resolve(),
  ]);
};

const exportExcel = () => {
  const ws = XLSX.utils.json_to_sheet(filteredData.value);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, selectedType.value);
  XLSX.writeFile(wb, `${selectedType.value}_${new Date().toISOString()}.xlsx`);
};

const exportPDF = () => {
  const doc = new jsPDF();
  const tableColumns = columns.value.map((c) => c.header);
  const tableRows = filteredData.value.map((row) =>
    columns.value.map((c) => formatValue(row[c.field], c.type)),
  );

  doc.autoTable({
    head: [tableColumns],
    body: tableRows,
    theme: "grid",
  });

  doc.save(`${selectedType.value}_${new Date().toISOString()}.pdf`);
};

// Watchers
watch(
  () => props.companyId,
  (newCompanyId) => {
    if (newCompanyId) {
      loadMaturityData();
      if (isDetailsExpanded.value) {
        loadDetailedData();
      }
    }
  },
  { immediate: false },
);

watch(
  () => companyStore.selectedCompany,
  (newCompany) => {
    if (newCompany && isDetailsExpanded.value) {
      loadDetailedData();
    }
  },
);

// Watch for accounting period changes - reload data when period changes
watch(
  () => periodStore.selectedPeriod,
  (newPeriod, oldPeriod) => {
    if (newPeriod && (newPeriod.luna !== oldPeriod?.luna || newPeriod.an !== oldPeriod?.an)) {
      console.log("Period changed in MaturityAndDetailsCard:", newPeriod);
      loadMaturityData();
      if (isDetailsExpanded.value) {
        loadDetailedData();
      }
    }
  },
  { deep: true }
);

// Watch for pagination changes
watch([firstRow, rowsPerPage], () => {
  if (isDetailsExpanded.value && detailedData.value.length > 0) {
    loadDetailedData();
  }
});

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

<style scoped>
/* === TYPOGRAPHY TOKENS === */
:root {
  --card-label-size: 0.875rem;
  --card-value-size: 1.5rem;
  --breakdown-label-size: 0.875rem;
  --breakdown-value-size: 0.9375rem;

  --font-mono:
    ui-monospace, "Cascadia Code", "Source Code Pro", Menlo, Consolas, monospace;
  --font-sans:
    "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

.maturity-details-card {
  background: var(--color-bg, #ffffff);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--card-radius, 8px);
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
}

.maturity-details-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: var(--color-primary, #3b82f6);
}

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

.card-title {
  margin: 0;
  font-size: 1.125rem;
  font-weight: 600;
  color: var(--color-text, #111827);
  font-family: var(--font-sans);
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

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

.period-selector:hover {
  border-color: var(--color-primary, #3b82f6);
}

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

.refresh-btn {
  background: none;
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  padding: 0.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
  color: var(--color-text-secondary, #6b7280);
}

.refresh-btn:hover:not(:disabled) {
  background: var(--color-bg-secondary, #f8fafc);
  border-color: var(--color-primary, #3b82f6);
  color: var(--color-primary, #3b82f6);
}

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

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

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

/* Loading & 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, #e5e7eb);
  border-top: 3px solid var(--color-primary, #3b82f6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--space-md, 1rem);
}

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

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

/* Card Content */
.card-content {
  padding: var(--space-lg, 1.5rem);
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

/* Comparison Section */
.comparison-section {
  display: grid;
  grid-template-columns: 1fr 1px 1fr;
  gap: 1.5rem;
}

.comparison-divider {
  background: var(--color-border, #e5e7eb);
}

.comparison-side {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.side-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid var(--color-border, #e5e7eb);
}

.side-label {
  font-size: var(--card-label-size);
  font-weight: 500;
  color: var(--color-text-secondary, #6b7280);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  font-family: var(--font-sans);
}

.side-total {
  font-size: 1.125rem;
  font-weight: 700;
  font-family: var(--font-mono);
  color: var(--color-text, #111827);
  padding: 0.25rem 0.5rem;
  background: var(--color-bg-secondary, #f8fafc);
  border-radius: var(--radius-sm, 4px);
}

.maturity-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 0.25rem;
}

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

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

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

.maturity-item {
  padding: 0.75rem;
  background: var(--color-bg, #ffffff);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  transition: all 0.2s ease;
}

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

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.item-name {
  font-weight: 500;
  color: var(--color-text, #111827);
  font-size: 0.875rem;
  font-family: var(--font-sans);
}

.item-status {
  font-size: 0.75rem;
  padding: 0.125rem 0.5rem;
  border-radius: var(--radius-full, 9999px);
  font-weight: 500;
  font-family: var(--font-sans);
}

.status-critical {
  background: rgba(239, 68, 68, 0.1);
  color: #dc2626;
}

.status-overdue {
  background: rgba(245, 158, 11, 0.1);
  color: #d97706;
}

.status-ok {
  background: rgba(16, 185, 129, 0.1);
  color: #059669;
}

.progress-bar {
  height: 8px;
  background: var(--color-bg-secondary, #f8fafc);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

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

.clients-fill {
  background: linear-gradient(90deg, #10b981, #059669);
}

.suppliers-fill {
  background: linear-gradient(90deg, #3b82f6, #2563eb);
}

.item-amount {
  font-size: 1rem;
  font-weight: 700;
  color: var(--color-text, #111827);
  font-family: var(--font-mono);
  text-align: right;
  min-width: 90px;
  display: block;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl, 2rem);
  text-align: center;
  color: var(--color-text-secondary, #6b7280);
  font-size: 0.875rem;
}

/* Balance Section */
.balance-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: var(--color-bg-secondary, #f8fafc);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
}

.balance-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.balance-label {
  font-size: 0.875rem;
  color: var(--color-text-secondary, #6b7280);
  font-family: var(--font-sans);
}

.balance-amount {
  font-size: 1.25rem;
  font-weight: 700;
  font-family: var(--font-mono);
}

.balance-amount.surplus {
  color: #10b981;
}

.balance-amount.deficit {
  color: #ef4444;
}

.status-summary {
  font-size: 0.75rem;
  color: var(--color-text-secondary, #6b7280);
  font-family: var(--font-sans);
}

/* Section Separator */
.section-separator {
  height: 1px;
  background: repeating-linear-gradient(
    90deg,
    var(--color-border, #e5e7eb),
    var(--color-border, #e5e7eb) 5px,
    transparent 5px,
    transparent 10px
  );
  margin: 0.5rem 0;
}

/* Details Section */
.details-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  user-select: none;
  padding: 0.75rem;
  border-radius: var(--radius-sm, 4px);
  transition: background 0.2s ease;
}

.details-header:hover {
  background: var(--color-bg-secondary, #f8fafc);
}

.details-header-left {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.collapse-icon {
  font-size: 0.625rem;
  color: var(--color-text-secondary, #6b7280);
  transition: transform 0.2s ease;
  display: inline-block;
  width: 0.875rem;
}

.details-title {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  color: var(--color-text, #111827);
  font-family: var(--font-sans);
}

.toggle-details-btn {
  padding: 0.375rem 0.75rem;
  background: var(--color-primary, #3b82f6);
  color: white;
  border: none;
  border-radius: var(--radius-sm, 4px);
  cursor: pointer;
  font-size: 0.875rem;
  transition: background 0.2s ease;
  font-family: var(--font-sans);
}

.toggle-details-btn:hover {
  background: var(--color-primary-dark, #2563eb);
}

.details-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Details Controls */
.details-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.type-selector {
  padding: 0.5rem 1rem;
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  background: var(--color-bg, #ffffff);
  color: var(--color-text, #111827);
  min-width: 120px;
  font-family: var(--font-sans);
}

.search-wrapper {
  position: relative;
  flex: 1;
  min-width: 200px;
  max-width: 300px;
}

.search-input {
  width: 100%;
  padding: 0.5rem 2.5rem 0.5rem 1rem;
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  background: var(--color-bg, #ffffff);
  color: var(--color-text, #111827);
  font-family: var(--font-sans);
}

.search-wrapper i {
  position: absolute;
  right: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-secondary, #6b7280);
  pointer-events: none;
}

.export-buttons {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
}

.export-btn {
  padding: 0.5rem;
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  background: var(--color-bg, #ffffff);
  color: var(--color-text-secondary, #6b7280);
  cursor: pointer;
  transition: all 0.2s ease;
}

.export-btn:hover {
  background: var(--color-bg-secondary, #f8fafc);
  border-color: var(--color-primary, #3b82f6);
  color: var(--color-primary, #3b82f6);
}

/* Table Wrapper */
.table-wrapper {
  overflow-x: auto;
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
}

/* Desktop Table */
.details-table {
  width: 100%;
  border-collapse: collapse;
  font-family: var(--font-sans);
  font-size: 0.875rem;
}

.details-table th,
.details-table td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid var(--color-border, #e5e7eb);
}

.details-table th {
  background: var(--color-bg-secondary, #f8fafc);
  font-weight: 600;
  color: var(--color-text, #111827);
  font-size: 0.8125rem;
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.details-table tbody tr:hover {
  background: var(--color-bg-secondary, #f8fafc);
}

.group-row {
  cursor: pointer;
  font-weight: 500;
}

.count-badge {
  color: var(--color-text-secondary, #6b7280);
  font-size: 0.75rem;
  font-weight: 400;
  margin-left: 0.5rem;
}

.detail-indent {
  padding-left: 2rem;
  color: var(--color-text-secondary, #6b7280);
  font-size: 0.8125rem;
}

.subtotal {
  text-align: right;
  font-weight: 600;
  color: var(--color-primary, #3b82f6);
  font-family: var(--font-mono);
}

.sold-restant {
  color: #dc2626 !important;
  font-weight: 600;
}

.totals-row {
  background: var(--color-bg-muted, #f1f5f9);
  border-top: 2px solid var(--color-border, #e5e7eb);
  font-weight: 600;
}

/* Mobile Cards */
.details-cards {
  display: none;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
}

.detail-card {
  background: var(--color-bg, #ffffff);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.card-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--color-border, #e5e7eb);
  margin-bottom: 0.5rem;
}

.group-card .card-header-row {
  cursor: pointer;
}

.group-card-right {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.status-badge {
  font-size: 0.75rem;
  padding: 0.125rem 0.5rem;
  border-radius: var(--radius-full, 9999px);
  font-weight: 500;
  background: rgba(16, 185, 129, 0.1);
  color: #059669;
}

.status-badge.restant {
  background: rgba(239, 68, 68, 0.1);
  color: #dc2626;
}

.card-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.875rem;
}

.card-row.highlight {
  padding-top: 0.5rem;
  border-top: 1px solid var(--color-border, #e5e7eb);
  margin-top: 0.25rem;
}

.card-label {
  color: var(--color-text-secondary, #6b7280);
  font-weight: 500;
}

.card-value {
  color: var(--color-text, #111827);
  font-weight: 500;
}

.sold-value {
  font-family: var(--font-mono);
  font-weight: 600;
}

.sub-cards {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-top: 0.75rem;
  padding-top: 0.75rem;
  border-top: 1px solid var(--color-border, #e5e7eb);
}

.sub-card {
  padding: 0.75rem;
  background: var(--color-bg-secondary, #f8fafc);
  border-radius: var(--radius-sm, 4px);
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

/* Pagination */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding-top: 1rem;
}

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

.footer-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.75rem;
}

.info-label {
  color: var(--color-text-secondary, #6b7280);
}

.info-value {
  color: var(--color-text, #111827);
  font-weight: 500;
  font-family: var(--font-sans);
}

/* Responsive - Hide/Show */
.mobile-only {
  display: none;
}

.desktop-only {
  display: table;
}

/* Responsive - Tablet */
@media (max-width: 1024px) {
  .comparison-section {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }

  .comparison-divider {
    display: none;
  }
}

/* Responsive - Mobile */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  .card-title {
    text-align: center;
    font-size: 1rem;
  }

  .header-controls {
    justify-content: center;
  }

  .card-content {
    padding: var(--space-md, 1rem);
  }

  .balance-section {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }

  .balance-info {
    justify-content: space-between;
  }

  .status-summary {
    text-align: center;
  }

  .details-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .search-wrapper {
    max-width: none;
  }

  .export-buttons {
    margin-left: 0;
    justify-content: center;
  }

  /* Switch to card-based layout */
  .desktop-only {
    display: none !important;
  }

  .mobile-only {
    display: flex !important;
  }

  .card-footer {
    flex-direction: column;
    gap: 0.5rem;
    align-items: center;
  }
}

@media (max-width: 480px) {
  .maturity-card {
    padding: 0.5rem 0.25rem;
    border-radius: 0;
  }

  .card-header {
    padding: 0.5rem 0.25rem;
  }

  .card-title {
    font-size: 0.875rem;
  }

  .card-content {
    padding: 0.25rem;
  }

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

  .card-footer {
    padding: 0.5rem 0.25rem;
  }

  .footer-stats {
    font-size: 0.75rem;
  }

  .item-amount {
    font-size: 1.125rem;
    font-weight: 800;
    min-width: 100px;
    text-align: right;
  }
}
</style>
