<template>
  <div class="detailed-data-section">
    <div class="section-header">
      <h2 class="section-title">Date Detaliate</h2>
      <div class="section-controls">
        <!-- Selector tip date -->
        <select
          v-model="selectedType"
          @change="loadData"
          class="data-type-select"
        >
          <option value="clients">Clienți</option>
          <option value="suppliers">Furnizori</option>
          <option value="treasury">Trezorerie</option>
        </select>

        <!-- Căutare -->
        <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>

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

    <!-- Tabel cu date -->
    <div class="table-container">
      <table class="detailed-table">
        <thead>
          <tr>
            <th v-for="column in displayColumns" :key="column.field">
              {{ column.header }}
            </th>
          </tr>
        </thead>
        <tbody v-if="selectedType === 'treasury'">
          <!-- Treasury - normal table without grouping -->
          <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>
          <!-- Clients/Suppliers - grouped with expand/collapse -->
          <template v-for="group in paginatedGroups" :key="group.name">
            <!-- Single invoice: show direct row -->
            <tr
              v-if="group.facturi.length === 1"
              class="single-invoice-row"
              :class="{ 'row-restant': group.hasRestant }"
            >
              <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: show expand/collapse -->
            <template v-else>
              <!-- Group row (client/supplier header with subtotal) -->
              <tr
                class="group-row"
                :class="{ 'has-restant': group.hasRestant }"
                @click="toggleClient(group.name)"
              >
                <td class="group-name-cell">
                  <strong>{{ group.name }}</strong>
                  <span class="facturi-count"
                    >({{ group.facturi.length }})</span
                  >
                </td>
                <td colspan="5"></td>
                <td
                  class="subtotal-cell"
                  :class="{ 'sold-restant': group.hasRestant }"
                >
                  <strong>{{
                    formatValue(group.totalSold, "currency")
                  }}</strong>
                </td>
              </tr>

              <!-- Detail rows (invoices) - only if expanded -->
              <template v-if="isExpanded(group.name)">
                <tr
                  v-for="(factura, idx) in group.facturi"
                  :key="`${group.name}-${idx}`"
                  class="detail-row"
                  :class="getRowClass(factura)"
                >
                  <td class="detail-name">
                    {{ 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[
                          selectedType === "clients" ? "facturat" : "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>
    </div>

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

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

const dashboardStore = useDashboardStore();
const companyStore = useCompanyStore();
const toast = useToast();

// State
const selectedType = ref("clients");
const searchTerm = ref("");
const data = ref([]);
const firstRow = ref(0);
const rowsPerPage = ref(25);
const expandedClients = ref(new Set());

// Columns configuration based on type
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 [];
  }
});

// Display columns for header (without first column for grouped tables)
const displayColumns = computed(() => {
  if (selectedType.value === "treasury") {
    return columns.value;
  }
  // For clients/suppliers, keep all columns in header
  return columns.value;
});

// Filtered data based on search
const filteredData = computed(() => {
  if (!searchTerm.value) return data.value;

  return data.value.filter((row) => {
    return Object.values(row).some((val) =>
      String(val).toLowerCase().includes(searchTerm.value.toLowerCase()),
    );
  });
});

// Group data by client/supplier
const groupedData = computed(() => {
  if (selectedType.value === "treasury") {
    return [];
  }

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

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

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

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

  return Object.values(groups);
});

// Paginated groups
const paginatedGroups = computed(() => {
  if (selectedType.value === "treasury") {
    return [];
  }
  const start = firstRow.value;
  const end = start + rowsPerPage.value;
  return groupedData.value.slice(start, end);
});

// Paginated data (for treasury)
const paginatedData = computed(() => {
  if (selectedType.value !== "treasury") {
    return [];
  }
  const end = firstRow.value + rowsPerPage.value;
  return filteredData.value.slice(firstRow.value, end);
});

// Total records for paginator
const totalRecords = computed(() => {
  if (selectedType.value === "treasury") {
    return filteredData.value.length;
  }
  return groupedData.value.length;
});

// Expand/collapse functions
const toggleClient = (clientName) => {
  if (expandedClients.value.has(clientName)) {
    expandedClients.value.delete(clientName);
  } else {
    expandedClients.value.add(clientName);
  }
};

const isExpanded = (clientName) => {
  return expandedClients.value.has(clientName);
};

const getRowClass = (row) => {
  if (row.status === "Restant") return "row-restant";
  return "row-in-termen";
};

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

    const response = await dashboardStore.loadDetailedData(
      selectedType.value,
      companyStore.selectedCompany.id_firma,
    );
    data.value = response.data;
    // Reset expanded state when loading new data
    expandedClients.value.clear();
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "Nu s-au putut încărca datele detaliate",
    });
  }
};

const formatValue = (value, type) => {
  switch (type) {
    case "currency":
      return new Intl.NumberFormat("ro-RO", {
        style: "currency",
        currency: "RON",
      }).format(value || 0);
    case "date":
      if (!value) return "-";
      // Handle Oracle date format (YYYY-MM-DD or Date object)
      const date = new Date(value);
      if (isNaN(date.getTime())) return value; // Return original if invalid
      return date.toLocaleDateString("ro-RO", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });
    case "badge":
      return value;
    default:
      return value;
  }
};

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

const handleSearch = () => {
  firstRow.value = 0; // Reset pagination on search
  expandedClients.value.clear(); // Reset expanded state on search
};

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`);
};

onMounted(() => {
  loadData();
});

watch(selectedType, () => {
  loadData();
});

// Watch for company changes to reload data
watch(
  () => companyStore.selectedCompany,
  (newCompany) => {
    if (newCompany) {
      loadData();
    }
  },
);
</script>

<style scoped>
.detailed-data-section {
  margin-top: 2rem;
  background: var(--color-bg);
  border-radius: var(--radius-lg);
  padding: 1.5rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.section-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--color-text-primary);
}

.section-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.data-type-select {
  padding: 0.5rem 1rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg);
  color: var(--color-text-primary);
  min-width: 120px;
}

.search-wrapper {
  position: relative;
  display: inline-block;
}

.search-input {
  padding: 0.5rem 2.5rem 0.5rem 1rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg);
  color: var(--color-text-primary);
  width: 200px;
}

.search-wrapper i {
  position: absolute;
  right: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-secondary);
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: var(--radius-sm);
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  transition: all 0.2s ease;
}

.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 0.8rem;
}

.btn-outline {
  background: transparent;
  border: 1px solid var(--color-border);
  color: var(--color-text-primary);
}

.btn-outline:hover {
  background: var(--color-bg-muted);
  border-color: var(--color-primary);
}

.table-container {
  overflow-x: auto;
  margin: 1rem 0;
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-border);
}

.detailed-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 600px;
  font-family:
    system-ui,
    -apple-system,
    "Segoe UI",
    Roboto,
    sans-serif;
  font-size: 12px;
  line-height: 1.4;
}

.detailed-table th,
.detailed-table td {
  padding: 0.5rem;
  text-align: left;
  border-bottom: 1px solid var(--color-border);
  font-weight: 400;
}

.detailed-table th {
  background: var(--surface-card);
  font-weight: 500;
  color: var(--color-text-primary);
  position: sticky;
  top: 0;
  font-size: 12px;
  letter-spacing: 0.025em;
  border-bottom: 2px solid var(--color-border);
}

/* Group row styling */
.group-row {
  background: var(--surface-card);
  cursor: pointer;
  font-weight: 500;
  border-top: 1px solid var(--color-border);
  transition: background 0.15s ease;
}

.group-row:hover {
  background: var(--surface-hover);
}

.group-row.has-restant:hover {
  background: var(--surface-hover);
}

/* Single invoice row styling */
.single-invoice-row {
  background: var(--surface-card);
  font-weight: 400;
  transition: background 0.15s ease;
}

.single-invoice-row:hover {
  background: var(--surface-hover);
}

.single-invoice-row.row-restant:hover {
  background: var(--surface-hover);
}

.single-invoice-row td:first-child {
  font-weight: 500;
}

.group-name-cell {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.facturi-count {
  color: var(--color-text-secondary);
  font-size: 11px;
  font-weight: 400;
  margin-left: 4px;
}

.subtotal-cell {
  text-align: right;
  font-weight: 600;
  color: var(--color-primary);
}

/* Detail row styling */
.detail-row {
  font-size: 11px;
  transition: background 0.15s ease;
}

.detail-name {
  padding-left: 1.5rem;
  color: var(--color-text-secondary);
  font-size: 11px;
}

.detail-row.row-restant:hover {
  background: #f8f9fa;
}

.detail-row.row-in-termen:hover {
  background: #f8f9fa;
}

/* Sold restant - only color the amount text */
.sold-restant {
  color: rgb(239, 68, 68);
  font-weight: 600;
}

.detailed-table tbody tr:hover {
  background: #f8f9fa;
}

.totals-row {
  background: #f8f9fa !important;
  border-top: 2px solid var(--color-border) !important;
  font-weight: 500;
}

.pagination-wrapper {
  margin-top: 1rem;
  display: flex;
  justify-content: center;
}

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

  .section-controls {
    justify-content: space-between;
  }

  .search-input {
    width: 150px;
  }

  .table-container {
    margin: 1rem -1rem;
    border-radius: 0;
    border-left: none;
    border-right: none;
  }

  .detailed-table th,
  .detailed-table td {
    padding: 0.5rem;
    font-size: 0.875rem;
    white-space: nowrap;
  }
}

@media (max-width: 480px) {
  .section-controls {
    flex-direction: column;
    gap: 0.5rem;
  }

  .section-controls > * {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .btn {
    justify-content: center;
  }
}
</style>
