<script setup>
import { onMounted, reactive, ref } from "vue";
import { useSearcher, apiURL } from "@Services/Api";
import { transl } from "./Module";

import PageHeader from "@Holos/PageHeader.vue";
import Checkout from "@App/CheckoutDelivery.vue";
import Table from "@Holos/Table.vue";
import { DateTime } from "luxon";

const models = ref({
  data: [],
  total: 0,
});

const filters = reactive({
  type: "",
  start_date: "",
  end_date: "",
});

const expandedRows = ref(new Set());

const toggleRow = (id) => {
  if (expandedRows.value.has(id)) {
    expandedRows.value.delete(id);
  } else {
    expandedRows.value.add(id);
  }
};

const isRowExpanded = (id) => {
  return expandedRows.value.has(id);
};

const getConceptsSummary = (model) => {
  if (!model.details || model.details.length === 0) return "-";

  const allConcepts = model.details
    .flatMap(
      (detail) =>
        detail.payment?.details?.map((pd) => pd.charge_concept?.name) || []
    )
    .filter(Boolean);

  const uniqueConcepts = [...new Set(allConcepts)];

  if (uniqueConcepts.length === 0) return "-";
  if (uniqueConcepts.length === 1) return uniqueConcepts[0];

  return `${uniqueConcepts[0]} y ${uniqueConcepts.length - 1} más...`;
};

const searcher = useSearcher({
  url: apiURL("cash-cuts"),
  filters,
  onSuccess: (data) => {
    models.value = data.models || { data: [] };
  },
});

onMounted(() => {
  searcher.search();
});
</script>

<template>
  <PageHeader title="Entrega de Caja" />
  <Checkout />
  <div class="mx-4 mb-4">
    <div class="bg-white rounded-lg shadow-md p-4 mb-4">
      <div class="flex items-center gap-4">
        <label class="text-sm font-medium text-gray-700"
          >Filtrar por tipo:</label
        >
        <select
          v-model="filters.type"
          @change="searcher.search()"
          class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
          <option value="">Todos</option>
          <option value="membership">Membresías</option>
          <option value="fine">Multas</option>
        </select>
        <label class="text-sm font-medium text-gray-700"
          >Fecha de inicio:</label
        >
        <input
          type="date"
          v-model="filters.start_date"
          @change="searcher.search()"
          class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        />
        <label class="text-sm font-medium text-gray-700"
          >Fecha de fin:</label
        >
        <input
          type="date"
          v-model="filters.end_date"
          @change="searcher.search()"
          class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        />
      </div>
    </div>
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
      <Table
        :items="models"
        :processing="searcher.processing"
        @send-pagination="(page) => searcher.pagination(page)"
      >
        <template #head>
          <th
            class="px-6 py-3 text-left text-sm font-semibold"
            v-text="transl('concept')"
          />
          <th
            class="px-6 py-3 text-left text-sm font-semibold"
            v-text="transl('amount')"
          />
          <th
            class="px-6 py-3 text-left text-sm font-semibold"
            v-text="transl('user')"
          />
          <th
            class="px-6 py-3 text-left text-sm font-semibold"
            v-text="transl('date')"
          />
        </template>
        <template #body="{ items }">
          <template v-for="model in items" :key="model.id">
            <!-- Fila principal -->
            <tr
              class="border-b border-gray-200 hover:bg-gray-50 transition-colors cursor-pointer"
              @click="toggleRow(model.id)"
            >
              <td class="px-6 py-4 text-sm text-gray-700">
                <div class="flex items-center gap-2">
                  <svg
                    class="w-4 h-4 transition-transform duration-200"
                    :class="{ 'rotate-90': isRowExpanded(model.id) }"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 5l7 7-7 7"
                    />
                  </svg>
                  <span>{{ getConceptsSummary(model) }}</span>
                </div>
              </td>
              <td class="px-6 py-4 text-sm text-gray-700">
                ${{ parseFloat(model.total_amount || 0).toFixed(2) }}
              </td>
              <td class="px-6 py-4 text-sm text-gray-700">
                {{ model.closed_by?.full_name || "-" }}
              </td>
              <td class="px-6 py-4 text-sm text-gray-700">
                {{
                  model.end_at
                    ? new Date(model.end_at).toLocaleDateString()
                    : "-"
                }}
              </td>
            </tr>

            <!-- Fila expandida con detalles -->
            <tr v-if="isRowExpanded(model.id)" class="bg-gray-50">
              <td colspan="4" class="px-6 py-4">
                <div
                  class="bg-white rounded-lg shadow-sm p-4 border border-gray-200"
                >
                  <h4 class="font-semibold text-gray-800 mb-3">
                    Detalle del corte de caja
                  </h4>

                  <div
                    v-if="model.details && model.details.length > 0"
                    class="space-y-3"
                  >
                    <div
                      v-for="detail in model.details"
                      :key="detail.id"
                      class="border-b border-gray-200 pb-3 last:border-b-0"
                    >
                      <div
                        v-for="paymentDetail in detail.payment?.details || []"
                        :key="paymentDetail.id"
                        class="flex justify-between items-center py-2"
                      >
                        <div class="flex-1">
                          <p class="font-medium text-gray-700">
                            {{ paymentDetail.charge_concept?.name || "-" }}
                          </p>
                          <p class="text-xs text-gray-500">
                            Cantidad: {{ paymentDetail.quantity || 1 }}
                          </p>
                        </div>
                        <div class="text-right">
                          <p class="font-semibold text-gray-800">
                            ${{
                              parseFloat(paymentDetail.amount || 0).toFixed(2)
                            }}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div
                      class="flex justify-between items-center pt-3 border-t-2 border-gray-300"
                    >
                      <div>
                        <p class="font-bold text-gray-800">Total del corte</p>
                        <p class="text-xs text-gray-500">
                          Fecha:
                          {{
                            model.end_at
                              ? new Date(model.end_at).toLocaleDateString()
                              : "-"
                          }}
                        </p>
                      </div>
                      <p class="text-xl font-bold text-blue-600">
                        ${{ parseFloat(model.total_amount || 0).toFixed(2) }}
                      </p>
                    </div>
                  </div>

                  <div v-else class="text-center text-gray-500 py-4">
                    No hay detalles disponibles
                  </div>
                </div>
              </td>
            </tr>
          </template>
        </template>
        <template #empty>
          <td colspan="4" class="px-6 py-8 text-center text-gray-500 text-sm">
            {{ transl("list.empty") }}
          </td>
        </template>
      </Table>
    </div>
  </div>
</template>
