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

const props = defineProps({
  activities: { type: Object, required: true },
  today: { type: String, required: true },
  // Optional: full list of clients with unread items to populate filter dropdown
  clients: { type: Array, default: () => [] },
});

function fmtDate(d) {
  if (!d) return "";
  try {
    return new Date(d).toLocaleDateString("sl-SI");
  } catch {
    return String(d);
  }
}
function fmtEUR(value) {
  if (value === null || value === undefined) return "—";
  const num = typeof value === "string" ? Number(value) : value;
  if (Number.isNaN(num)) return String(value);
  const formatted = new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(num);
  return formatted.replace("\u00A0", " ");
}

// --- Client filter (like Segments/Show.vue) ---
const urlParams = new URLSearchParams(window.location.search);
const initialClient = urlParams.get("client") || urlParams.get("client_id") || "";
const selectedClient = ref(initialClient);

const clientOptions = computed(() => {
  // Prefer server-provided clients list; fallback to deriving from rows
  const list = Array.isArray(props.clients) && props.clients.length
    ? props.clients
    : (Array.isArray(props.activities?.data) ? props.activities.data : [])
        .map((row) => {
          const client = row.contract?.client_case?.client || row.client_case?.client;
          if (!client?.uuid) return null;
          return { value: client.uuid, label: client.person?.full_name || "(neznana stranka)" };
        })
        .filter(Boolean)
        .reduce((acc, cur) => {
          if (!acc.find((x) => x.value === cur.value)) acc.push(cur);
          return acc;
        }, []);
  return list.sort((a, b) => (a.label || "").localeCompare(b.label || ""));
});

watch(selectedClient, (val) => {
  const query = {};
  if (val) query.client = val;
  router.get(route("notifications.unread"), query, {
    preserveState: true,
    preserveScroll: true,
    only: ["activities"],
    replace: true,
  });
});

async function markRead(id) {
  try {
    await window.axios.post(route("notifications.activity.read"), { activity_id: id });
    router.reload({ only: ["activities"] });
  } catch (e) {}
}
</script>

<template>
  <AppLayout title="Obvestila">
    <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>Neprikazana obvestila</template>
                <template #description>Do danes: {{ fmtDate(today) }}</template>
              </SectionTitle>
            </div>

            <!-- Filters -->
            <div class="mb-4 flex items-center gap-3">
              <div class="flex-1 max-w-sm">
                <label class="block text-sm font-medium text-gray-700 mb-1">Partner</label>
                <div class="flex items-center gap-2">
                  <select
                    v-model="selectedClient"
                    class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm"
                  >
                    <option value="">Vsi partnerji</option>
                    <option v-for="opt in clientOptions" :key="opt.value || opt.label" :value="opt.value">
                      {{ opt.label }}
                    </option>
                  </select>
                  <button
                    v-if="selectedClient"
                    type="button"
                    class="text-sm text-gray-600 hover:text-gray-900"
                    @click="selectedClient = ''"
                  >
                    Počisti
                  </button>
                </div>
              </div>
            </div>

            <DataTableServer
              :columns="[
                { key: 'what', label: 'Zadeva', sortable: false },
                { key: 'partner', label: 'Partner', sortable: false },
                {
                  key: 'balance',
                  label: 'Stanje',
                  sortable: false,
                  align: 'right',
                  class: 'w-40',
                },
                { key: 'due', label: 'Zapadlost', sortable: true, class: 'w-28' },
              ]"
              :rows="activities.data || []"
              :meta="{
                current_page: activities.current_page,
                per_page: activities.per_page,
                total: activities.total,
                last_page: activities.last_page,
              }"
              route-name="notifications.unread"
              page-param-name="unread-page"
              :only-props="['activities']"
              :query="{ client: selectedClient || undefined }"
            >
              <template #cell-what="{ row }">
                <div class="font-medium text-gray-800 truncate">
                  <template v-if="row.contract?.uuid">
                    Pogodba:
                    <Link
                      v-if="row.contract?.client_case?.uuid"
                      :href="
                        route('clientCase.show', {
                          client_case: row.contract.client_case.uuid,
                        })
                      "
                      class="text-indigo-600 hover:underline"
                    >
                      {{ row.contract?.reference || "—" }}
                    </Link>
                    <span v-else>{{ row.contract?.reference || "—" }}</span>
                  </template>
                  <template v-else>
                    Primer:
                    <Link
                      v-if="row.client_case?.uuid"
                      :href="
                        route('clientCase.show', { client_case: row.client_case.uuid })
                      "
                      class="text-indigo-600 hover:underline"
                    >
                      {{ row.client_case?.person?.full_name || "—" }}
                    </Link>
                    <span v-else>{{ row.client_case?.person?.full_name || "—" }}</span>
                  </template>
                </div>
              </template>
              <template #cell-partner="{ row }">
                <div class="truncate">
                  {{
                    (row.contract?.client_case?.client?.person?.full_name) ||
                    (row.client_case?.client?.person?.full_name) ||
                    '—'
                  }}
                </div>
              </template>
              <template #cell-balance="{ row }">
                <div class="text-right">
                  <span v-if="row.contract">{{
                    fmtEUR(row.contract?.account?.balance_amount)
                  }}</span>
                  <span v-else>—</span>
                </div>
              </template>
              <template #cell-due="{ row }">
                {{ fmtDate(row.due_date) }}
              </template>
              <template #actions="{ row }">
                <button
                  type="button"
                  class="text-[12px] text-gray-500 hover:text-gray-700"
                  @click="markRead(row.id)"
                >
                  Označi kot prebrano
                </button>
              </template>
              <template #empty>
                <div class="p-6 text-center text-gray-500">
                  Trenutno ni neprikazanih obvestil.
                </div>
              </template>
            </DataTableServer>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>
