<script setup>
import AppPhoneLayout from '@/Layouts/AppPhoneLayout.vue';
import { computed, ref } from 'vue';

const props = defineProps({
  jobs: { type: Array, default: () => [] },
});

const items = computed(() => props.jobs || []);

// Search filter (contract reference or person full name)
const search = ref('');
const filteredJobs = computed(() => {
  const term = search.value.trim().toLowerCase();
  if (!term) return items.value;
  return items.value.filter(job => {
    const refStr = (job.contract?.reference || job.contract?.uuid || '').toString().toLowerCase();
    const nameStr = (job.contract?.client_case?.person?.full_name || '').toLowerCase();
    return refStr.includes(term) || nameStr.includes(term);
  });
});

function formatDateDMY(d) {
  if (!d) return '-';
  // Handle date-only strings from Laravel JSON casts (YYYY-MM-DD...)
  if (/^\d{4}-\d{2}-\d{2}/.test(d)) {
    const [y, m, rest] = d.split('-');
    const day = (rest || '').slice(0, 2) || '01';
    return `${day}.${m}.${y}`;
  }
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return String(d);
  const dd = String(dt.getDate()).padStart(2, '0');
  const mm = String(dt.getMonth() + 1).padStart(2, '0');
  const yyyy = dt.getFullYear();
  return `${dd}.${mm}.${yyyy}`;
}

function formatAmount(val) {
  if (val === null || val === undefined) return '0,00';
  const num = typeof val === 'number' ? val : parseFloat(val);
  if (Number.isNaN(num)) return String(val);
  return num.toLocaleString('sl-SI', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
</script>

<template>
  <AppPhoneLayout title="Phone">
    <template #header>
      <h2 class="font-semibold text-xl text-gray-800 leading-tight">Moja terenska opravila</h2>
    </template>

    <div class="py-4 sm:py-8">
      <div class="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
        <div class="mb-4 flex items-center gap-2">
          <input v-model="search" type="text" placeholder="Išči po referenci ali imenu..."
            class="flex-1 rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500" />
          <button v-if="search" type="button" @click="search = ''"
            class="text-xs px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 text-gray-600">Počisti</button>
        </div>
        <div class="grid grid-cols-1 gap-3 sm:gap-4 md:grid-cols-2 lg:grid-cols-3">
          <template v-if="filteredJobs.length">
            <div v-for="job in filteredJobs" :key="job.id" class="bg-white rounded-lg shadow border p-3 sm:p-4">
              <div class="mb-4 flex gap-2">
                <a :href="route('phone.case', { client_case: job.contract?.client_case?.uuid })"
                  class="inline-flex-1 flex-1 text-center px-3 py-2 rounded-md bg-blue-600 text-white text-sm hover:bg-blue-700">Odpri
                  primer</a>
              </div>
              <div class="flex items-center justify-between">
                <p class="text-sm text-gray-500">Dodeljeno: <span class="font-medium text-gray-700">{{
                  formatDateDMY(job.assigned_at) }}</span></p>
                <span v-if="job.priority"
                  class="inline-block text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700">Prioriteta</span>
              </div>
              <div class="mt-2">
                <p class="text-base sm:text-lg font-semibold text-gray-800">
                  {{ job.contract?.client_case?.person?.full_name || '—' }}
                </p>
                <p class="text-sm text-gray-600 truncate">Kontrakt: {{ job.contract?.reference || job.contract?.uuid }}
                </p>
                <p class="text-sm text-gray-600">Tip: {{ job.contract?.type?.name || '—' }}</p>
                <p class="text-sm text-gray-600"
                  v-if="job.contract?.account && job.contract.account.balance_amount !== null && job.contract.account.balance_amount !== undefined">
                  Odprto: {{ formatAmount(job.contract.account.balance_amount) }} €
                </p>
              </div>
              <div class="mt-3 text-sm text-gray-600">
                <p>
                  <span class="font-medium">Naslov:</span>
                  {{ job.contract?.client_case?.person?.addresses?.[0]?.address || '—' }}
                </p>
                <p>
                  <span class="font-medium">Telefon:</span>
                  {{ job.contract?.client_case?.person?.phones?.[0]?.nu || '—' }}
                </p>
              </div>

            </div>
          </template>
          <div v-else class="col-span-full bg-white rounded-lg shadow border p-6 text-center text-gray-600">
            <span v-if="search">Ni zadetkov za podani filter.</span>
            <span v-else>Trenutno nimate dodeljenih terenskih opravil.</span>
          </div>
        </div>
      </div>
    </div>
  </AppPhoneLayout>
</template>
