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

const props = defineProps({
  client: Object,
  contracts: Object,
  filters: Object,
  types: Object,
});

const fromDate = ref(props.filters?.from || "");
const toDate = ref(props.filters?.to || "");
const search = ref(props.filters?.search || "");
function applyDateFilter() {
  const params = Object.fromEntries(
    new URLSearchParams(window.location.search).entries()
  );
  if (fromDate.value) {
    params.from = fromDate.value;
  } else {
    delete params.from;
  }
  if (toDate.value) {
    params.to = toDate.value;
  } else {
    delete params.to;
  }
  if (search.value && search.value.trim() !== "") {
    params.search = search.value.trim();
  } else {
    delete params.search;
  }
  delete params.page;
  router.get(route("client.contracts", { uuid: props.client.uuid }), params, {
    preserveState: true,
    replace: true,
    preserveScroll: true,
  });
}

function clearDateFilter() {
  fromDate.value = "";
  toDate.value = "";
  applyDateFilter();
}

// Search handled by DataTableServer toolbar; keep date filter applying

// Build params for navigating to client case show, including active segment if available
function caseShowParams(contract) {
  const params = { client_case: contract?.client_case?.uuid };
  const segId = contract?.segments?.[0]?.id;
  if (segId) {
    params.segment = segId;
  }
  return params;
}

// Format YYYY-MM-DD (or ISO date) to dd.mm.yyyy
function formatDate(value) {
  if (!value) return "-";
  try {
    const iso = String(value).split("T")[0];
    const parts = iso.split("-");
    if (parts.length !== 3) return value;
    const [y, m, d] = parts;
    return `${d.padStart(2, "0")}.${m.padStart(2, "0")}.${y}`;
  } catch (e) {
    return value;
  }
}
</script>

<template>
  <AppLayout title="Pogodbe">
    <template #header></template>
    <!-- Header card (matches Client/Show header style) -->
    <div class="pt-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div
          class="bg-white overflow-hidden shadow-xl sm:rounded-lg border-l-4 border-blue-400"
        >
          <div class="mx-auto max-w-4x1 p-3">
            <div class="flex items-center justify-between">
              <SectionTitle>
                <template #title>
                  {{ client.person.full_name }}
                </template>
              </SectionTitle>
            </div>
            <nav class="mt-2 border-b border-gray-200">
              <ul class="flex gap-6 -mb-px">
                <li>
                  <Link
                    :href="route('client.show', { uuid: client.uuid })"
                    :class="[
                      'inline-flex items-center px-3 py-2 text-sm font-medium border-b-2',
                      route().current('client.show')
                        ? 'text-indigo-600 border-indigo-600'
                        : 'text-gray-600 border-transparent hover:text-gray-800 hover:border-gray-300'
                    ]"
                  >
                    Primeri
                  </Link>
                </li>
                <li>
                  <Link
                    :href="route('client.contracts', { uuid: client.uuid })"
                    :class="[
                      'inline-flex items-center px-3 py-2 text-sm font-medium border-b-2',
                      route().current('client.contracts')
                        ? 'text-indigo-600 border-indigo-600'
                        : 'text-gray-600 border-transparent hover:text-gray-800 hover:border-gray-300'
                    ]"
                  >
                    Pogodbe
                  </Link>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>

    <!-- Client details card (separate container) -->
    <div class="pt-1">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div
          class="bg-white overflow-hidden shadow-xl sm:rounded-lg border-l-4 border-blue-400"
        >
          <div class="mx-auto max-w-4x1 px-2">
            <PersonInfoGrid :types="types" :person="client.person" />
          </div>
        </div>
      </div>
    </div>

    <!-- Contracts list card -->
    <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="flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
            >
              <div class="flex items-center gap-3 flex-wrap">
                <label class="font-medium mr-2">Filter po datumu:</label>
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">Od</span>
                  <input
                    type="date"
                    v-model="fromDate"
                    @change="applyDateFilter"
                    class="rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 px-3 py-2 text-sm"
                  />
                </div>
                <div class="flex items-center gap-2">
                  <span class="text-sm text-gray-600">Do</span>
                  <input
                    type="date"
                    v-model="toDate"
                    @change="applyDateFilter"
                    class="rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 px-3 py-2 text-sm"
                  />
                </div>
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-2 text-sm font-medium rounded border border-gray-300 text-gray-700 hover:bg-gray-50 disabled:opacity-50"
                  :disabled="!fromDate && !toDate"
                  @click="clearDateFilter"
                  title="Počisti datum"
                >
                  Počisti
                </button>
              </div>
              <!-- Search lives in DataTable toolbar -->
            </div>
            <DataTableServer
              class="mt-3"
              :columns="[
                { key: 'reference', label: 'Referenca', sortable: false },
                { key: 'customer', label: 'Stranka', sortable: false },
                { key: 'start', label: 'Začetek', sortable: false },
                { key: 'segment', label: 'Segment', sortable: false },
                { key: 'balance', label: 'Stanje', sortable: false, align: 'right' },
              ]"
              :rows="contracts.data || []"
              :meta="{ current_page: contracts.current_page, per_page: contracts.per_page, total: contracts.total, last_page: contracts.last_page }"
              route-name="client.contracts"
              :route-params="{ uuid: client.uuid }"
              :query="{ from: fromDate || undefined, to: toDate || undefined }"
              :search="search"
              row-key="uuid"
              :only-props="['contracts']"
            >
              <template #cell-reference="{ row }">
                <Link :href="route('clientCase.show', caseShowParams(row))" class="text-indigo-600 hover:underline">
                  {{ row.reference }}
                </Link>
              </template>
              <template #cell-customer="{ row }">
                {{ row.client_case?.person?.full_name || '-' }}
              </template>
              <template #cell-start="{ row }">
                {{ formatDate(row.start_date) }}
              </template>
              <template #cell-segment="{ row }">
                {{ row.segments?.[0]?.name || '-' }}
              </template>
              <template #cell-balance="{ row }">
                <div class="text-right">
                  {{ new Intl.NumberFormat('sl-SI', { style: 'currency', currency: 'EUR' }).format(Number(row.account?.balance_amount ?? 0)) }}
                </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>
