<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import { Link, router } from "@inertiajs/vue3";
import { ref } from "vue";
import DataTableServer from "@/Components/DataTable/DataTableServer.vue";

const props = defineProps({
  client_cases: Object,
  filters: Object,
});

// Initial search for DataTable toolbar
const search = ref(props.filters?.search || "");

// Format helpers
const fmtCurrency = (v) => {
  const n = Number(v ?? 0);
  try {
    return new Intl.NumberFormat("sl-SI", { style: "currency", currency: "EUR" }).format(
      n
    );
  } catch (e) {
    return `${n.toFixed(2)} €`;
  }
};

const fmtDateDMY = (v) => {
  if (!v) return "-";
  const d = new Date(v);
  if (isNaN(d)) return "-";
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const yyyy = d.getFullYear();
  return `${dd}.${mm}.${yyyy}`;
};
</script>
<template>
  <AppLayout title="Client cases">
    <template #header> </template>
    <div class="py-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="px-3 bg-white overflow-hidden shadow-xl sm:rounded-lg">
          <div class="mx-auto max-w-4x1 py-3">
            <div class="pb-3">
              <SectionTitle>
                <template #title>Primeri</template>
              </SectionTitle>
            </div>
            <DataTableServer
              :columns="[
                { key: 'nu', label: 'Št.', sortable: false, class: 'w-40' },
                { key: 'case', label: 'Primer', sortable: false },
                { key: 'client', label: 'Stranka', sortable: false },
                { key: 'tax', label: 'Davčna', sortable: false },
                { key: 'created_at', label: 'Ustvarjeno', sortable: false },
                {
                  key: 'active_contracts',
                  label: 'Aktivne pogodbe',
                  sortable: false,
                  align: 'right',
                },
                {
                  key: 'balance',
                  label: 'Skupaj stanje',
                  sortable: false,
                  align: 'right',
                },
              ]"
              :rows="client_cases.data || []"
              :meta="{
                current_page: client_cases.current_page,
                per_page: client_cases.per_page,
                total: client_cases.total,
                last_page: client_cases.last_page,
              }"
              :search="search"
              route-name="clientCase"
              page-param-name="client-cases-page"
              :only-props="['client_cases']"
            >
              <template #cell-nu="{ row }">
                {{ row.person?.nu || "-" }}
              </template>
              <template #cell-case="{ row }">
                <Link
                  :href="route('clientCase.show', { client_case: row.uuid })"
                  class="text-indigo-600 hover:underline"
                >
                  {{ row.person?.full_name || "-" }}
                </Link>
                <button
                  v-if="!row.person"
                  @click.prevent="
                    router.post(
                      route('clientCase.emergencyPerson', { client_case: row.uuid })
                    )
                  "
                  class="ml-2 inline-flex items-center rounded bg-red-50 px-2 py-0.5 text-xs font-semibold text-red-600 hover:bg-red-100 border border-red-200"
                  title="Emergency: recreate missing person"
                >
                  Add Person
                </button>
              </template>
              <template #cell-client="{ row }">
                {{ row.client?.person?.full_name || "-" }}
              </template>
              <template #cell-tax="{ row }">
                {{ row.person?.tax_number || "-" }}
              </template>
              <template #cell-created_at="{ row }">
                {{ fmtDateDMY(row.created_at) }}
              </template>
              <template #cell-active_contracts="{ row }">
                <div class="text-right">{{ row.active_contracts_count ?? 0 }}</div>
              </template>
              <template #cell-balance="{ row }">
                <div class="text-right">
                  {{ fmtCurrency(row.active_contracts_balance_sum) }}
                </div>
              </template>
              <template #empty>
                <div class="p-6 text-center text-gray-500">Ni zadetkov.</div>
              </template>
            </DataTableServer>
          </div>
          <!-- Pagination handled by DataTableServer -->
        </div>
      </div>
    </div>
  </AppLayout>
</template>
