<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import { ref } from "vue";
import { Link, router } from "@inertiajs/vue3";
import Pagination from "@/Components/Pagination.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 applySearch() {
  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,
  });
}

// 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>
            <div class="mt-2 flex items-center gap-3 text-sm">
              <Link
                :href="route('client.show', { uuid: client.uuid })"
                class="px-2 py-1 rounded hover:underline"
                >Primeri</Link
              >
              <span class="text-gray-300">|</span>
              <Link
                :href="route('client.contracts', { uuid: client.uuid })"
                class="px-2 py-1 rounded text-indigo-600 hover:underline"
                >Pogodbe</Link
              >
            </div>
          </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>
              </div>
              <div class="flex items-center gap-2">
                <input
                  type="text"
                  v-model="search"
                  @keyup.enter="applySearch"
                  placeholder="Išči po referenci ali imenu"
                  class="rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 px-3 py-2 text-sm w-64"
                />
                <button
                  type="button"
                  @click="applySearch"
                  class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded"
                >
                  Išči
                </button>
              </div>
            </div>
            <div class="overflow-x-auto mt-3">
              <table class="min-w-full text-left text-sm">
                <thead>
                  <tr class="border-b">
                    <th class="py-2 pr-4">Referenca</th>
                    <th class="py-2 pr-4">Stranka</th>
                    <th class="py-2 pr-4">Začetek</th>
                    <th class="py-2 pr-4">Segment</th>
                    <th class="py-2 pr-4 text-right">Stanje</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="contract in contracts.data"
                    :key="contract.uuid"
                    class="border-b last:border-0"
                  >
                    <td class="py-2 pr-4">
                      <Link
                        :href="route('clientCase.show', caseShowParams(contract))"
                        class="text-indigo-600 hover:underline"
                      >
                        {{ contract.reference }}
                      </Link>
                    </td>
                    <td class="py-2 pr-4">
                      {{ contract.client_case?.person?.full_name || "-" }}
                    </td>
                    <td class="py-2 pr-4">
                      {{ formatDate(contract.start_date) }}
                    </td>
                    <td class="py-2 pr-4">{{ contract.segments?.[0]?.name || "-" }}</td>
                    <td class="py-2 pr-4 text-right">
                      {{
                        new Intl.NumberFormat("sl-SI", {
                          style: "currency",
                          currency: "EUR",
                        }).format(Number(contract.account?.balance_amount ?? 0))
                      }}
                    </td>
                  </tr>
                  <tr v-if="!contracts.data || contracts.data.length === 0">
                    <td colspan="5" class="py-4 text-gray-500">Ni zadetkov.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <Pagination
            :links="contracts.links"
            :from="contracts.from"
            :to="contracts.to"
            :total="contracts.total"
          />
        </div>
      </div>
    </div>
  </AppLayout>
</template>
