<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import { ref } from "vue";
import { Link, router } from "@inertiajs/vue3";
import DataTable from "@/Components/DataTable/DataTable.vue";
import { Button } from "@/Components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import PersonInfoGrid from "@/Components/PersonInfo/PersonInfoGrid.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import DateRangePicker from "@/Components/DateRangePicker.vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { ButtonGroup } from "@/Components/ui/button-group";

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

const dateRange = ref({
  start: props.filters?.from || null,
  end: props.filters?.to || null,
});
const search = ref(props.filters?.search || "");
const selectedSegment = ref(props.filters?.segment || null);

function applyDateFilter() {
  const params = Object.fromEntries(
    new URLSearchParams(window.location.search).entries()
  );
  if (dateRange.value?.start) {
    params.from = dateRange.value.start;
  } else {
    delete params.from;
  }
  if (dateRange.value?.end) {
    params.to = dateRange.value.end;
  } else {
    delete params.to;
  }
  if (search.value && search.value.trim() !== "") {
    params.search = search.value.trim();
  } else {
    delete params.search;
  }
  if (selectedSegment.value) {
    params.segment = String(selectedSegment.value);
  } else {
    delete params.segments;
  }
  delete params.page;
  router.get(route("client.contracts", { uuid: props.client.uuid }), params, {
    preserveState: true,
    replace: true,
    preserveScroll: true,
    only: ['contracts'],
  });
}

function clearDateFilter() {
  dateRange.value = { start: null, end: null };
  selectedSegment.value = null;
  applyDateFilter();
}

function handleDateRangeUpdate() {
  applyDateFilter();
}

function handleSegmentChange(value) {
  selectedSegment.value = 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>
          </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="mb-4">
              <ButtonGroup>
                <Button
                  as-child
                  :variant="route().current('client.show') ? 'default' : 'ghost'"
                >
                  <Link :href="route('client.show', { uuid: client.uuid })">
                    Primeri
                  </Link>
                </Button>
                <Button
                  as-child
                  :variant="route().current('client.contracts') ? 'default' : 'ghost'"
                >
                  <Link :href="route('client.contracts', { uuid: client.uuid })">
                    Pogodbe
                  </Link>
                </Button>
              </ButtonGroup>
            </div>
            <DataTable
              :show-search="true"
              :show-page-size="true"
              :show-filters="true"
              :has-active-filters="!!(dateRange?.start || dateRange?.end || selectedSegment)"
              :columns="[
                { key: 'select', label: '', sortable: false, width: '50px' },
                { 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, from: contracts.from, to: contracts.to, links: contracts.links }"
              route-name="client.contracts"
              :route-params="{ uuid: client.uuid }"
              :search="search"
              row-key="uuid"
              :only-props="['contracts']"
            >
              <template #toolbar-filters>
                <div class="space-y-4">
                  <div class="space-y-2">
                    <label class="text-sm font-medium">Datumska območja</label>
                    <DateRangePicker
                      v-model="dateRange"
                      format="dd.MM.yyyy"
                      @update:model-value="handleDateRangeUpdate"
                      placeholder="Izberi datumska območja"
                    />
                  </div>
                  <div class="space-y-2">
                    <label class="text-sm font-medium">Segment</label>
                    <Select
                      :model-value="selectedSegment"
                      @update:model-value="handleSegmentChange"
                    >
                      <SelectTrigger class="w-full">
                        <SelectValue placeholder="Vsi segmenti" />
                      </SelectTrigger>
                      <SelectContent class="w-[var(--radix-select-trigger-width)]">
                        <SelectItem :value="null">Vsi segmenti</SelectItem>
                        <SelectItem
                          v-for="segment in segments"
                          :key="segment.id"
                          :value="String(segment.id)"
                        >
                          {{ segment.name }}
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div class="flex justify-end pt-2 border-t">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      :disabled="!dateRange?.start && !dateRange?.end && !selectedSegment"
                      @click="clearDateFilter"
                    >
                      Počisti
                    </Button>
                  </div>
                </div>
              </template>
              <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>
            </DataTable>
          </div>
          <!-- Pagination handled by DataTableServer -->
        </div>
      </div>
    </div>
  </AppLayout>
</template>
