<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import { computed, ref } from "vue";
import { Link, router, usePage } from "@inertiajs/vue3";
import SectionTitle from "@/Components/SectionTitle.vue";
import PersonInfoGrid from "@/Components/PersonInfo/PersonInfoGrid.vue";
import FormCreateCase from "./Partials/FormCreateCase.vue";
import DataTable from "@/Components/DataTable/DataTableNew2.vue";
import { hasPermission } from "@/Services/permissions";
import { Button } from "@/Components/ui/button";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { Card } from "@/Components/ui/card";
import Badge from "@/Components/ui/badge/Badge.vue";
import { cn } from "@/lib/utils";
import { Input } from "@/Components/ui/input";
import { UsersRoundIcon } from "lucide-vue-next";

const props = defineProps({
  client: Object,
  client_cases: Object,
  urlPrev: String,
  filters: Object,
  types: Object,
});

// Removed page-level search; DataTable or server can handle filtering elsewhere if needed
// DataTable search state
const search = ref(props.filters?.search || "");
const page = usePage();
// Expose as a callable computed: use in templates as hasPerm('permission-slug')
const hasPerm = computed(() => (permission) =>
  hasPermission(page.props.auth?.user, permission)
);

const drawerCreateCase = ref(false);

const openDrawerCreateCase = () => {
  drawerCreateCase.value = true;
};

function applySearch() {
  const params = Object.fromEntries(
    new URLSearchParams(window.location.search).entries()
  );
  const term = (search.value || "").trim();
  if (term) {
    params.search = term;
  } else {
    delete params.search;
  }
  delete params.page;
  router.get(route("client.show", { uuid: props.client.uuid }), params, {
    preserveState: true,
    replace: true,
    preserveScroll: true,
    only: ["client_cases"],
  });
}
</script>

<template>
  <AppLayout title="Client">
    <template #header> </template>
    <div class="pt-6">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card class="border-l-4 border-blue-400 p-0!">
          <div class="p-3 flex justify-between items-center">
            <SectionTitle>
              <template #title>
                {{ client.person.full_name }}
              </template>
            </SectionTitle>
            <Badge class="bg-blue-500 text-white"> Naročnik </Badge>
          </div>
        </Card>
      </div>
    </div>
    <div class="pt-1">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card class="p-0!">
          <div class="p-3">
            <PersonInfoGrid
              :types="types"
              :person="client.person"
              :edit="hasPerm('client-edit')"
            ></PersonInfoGrid>
          </div>
        </Card>
      </div>
    </div>

    <div class="py-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">
          <div class="mx-auto max-w-4x1">
            <div class="p-2 flex flex-row items-center gap-2">
              <Link
                :class="
                  cn(
                    'border border-gray-200 py-2 px-3 rounded-md hover:bg-accent hover:text-accent-foreground ',
                    route().current('client.show')
                      ? 'bg-accent text-accent-foreground'
                      : ''
                  )
                "
                :href="route('client.show', { uuid: client.uuid })"
              >
                Primeri
              </Link>

              <Link
                :class="
                  cn(
                    'border border-gray-200 py-2 px-3 rounded-md hover:bg-accent hover:text-accent-foreground ',
                    route().current('client.contracts')
                      ? 'bg-accent text-accent-foreground'
                      : ''
                  )
                "
                :href="route('client.contracts', { uuid: client.uuid })"
              >
                Pogodbe
              </Link>
            </div>
            <DataTable
              :columns="[
                { key: 'nu', label: 'Št.', sortable: false, class: 'w-40' },
                { key: 'case', label: 'Primer', sortable: false },
                { key: 'tax', label: 'Davčna', sortable: false },
                {
                  key: 'active_contracts',
                  label: 'Aktivne pogodbe',
                  sortable: false,
                  align: 'right',
                },
                {
                  key: 'balance',
                  label: 'Skupaj stanje',
                  sortable: false,
                  align: 'right',
                },
              ]"
              :data="client_cases.data || []"
              :meta="{
                current_page: client_cases.current_page,
                per_page: client_cases.per_page,
                total: client_cases.total,
                last_page: client_cases.last_page,
                from: client_cases.from,
                to: client_cases.to,
                links: client_cases.links,
              }"
              route-name="client.show"
              :route-params="{ uuid: client.uuid }"
              row-key="uuid"
              :only-props="['client_cases']"
              :page-size-options="[10, 15, 25, 50, 100]"
              :show-toolbar="true"
            >
              <template #toolbar-filters>
                <div class="flex items-center gap-2 w-full">
                  <Input
                    v-model="search"
                    placeholder="Išči po primeru, davčni, osebi..."
                    class="w-65"
                    @keydown.enter="applySearch"
                  />
                  <Button size="sm" variant="outline" @click="applySearch">Išči</Button>
                </div>
              </template>
              <template #toolbar-actions>
                <Button
                  v-if="hasPerm('case-edit')"
                  size="sm"
                  variant="outline"
                  class="gap-2"
                  @click="openDrawerCreateCase"
                >
                  <FontAwesomeIcon :icon="faPlus" class="h-4 w-4" />
                  Dodaj primer
                </Button>
              </template>
              <template #cell-nu="{ row }">
                {{ row.person?.nu || "-" }}
              </template>
              <template #cell-case="{ row }">
                <Link
                  :href="route('clientCase.show', { client_case: row.uuid })"
                  class="font-semibold hover:underline text-primary-700"
                >
                  {{ row.person?.full_name || "-" }}
                </Link>
              </template>
              <template #cell-tax="{ row }">
                {{ row.person?.tax_number || "-" }}
              </template>
              <template #cell-active_contracts="{ row }">
                <div class="text-right">{{ row.active_contracts_count ?? 0 }}</div>
              </template>
              <template #cell-balance="{ row }">
                <div class="text-right">
                  {{
                    new Intl.NumberFormat("sl-SI", {
                      style: "currency",
                      currency: "EUR",
                    }).format(Number(row.active_contracts_balance_sum ?? 0))
                  }}
                </div>
              </template>
            </DataTable>
          </div>
          <!-- Pagination handled by DataTableServer -->
        </div>
      </div>
    </div>
  </AppLayout>
  <FormCreateCase
    :show="drawerCreateCase"
    @close="drawerCreateCase = false"
    :client-uuid="client?.uuid"
  />
</template>
