<script setup>
import { ref, watch } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import InputLabel from "@/Components/InputLabel.vue";
import TextInput from "@/Components/TextInput.vue";
import { Link, useForm, router } from "@inertiajs/vue3";
import ActionMessage from "@/Components/ActionMessage.vue";
import DialogModal from "@/Components/DialogModal.vue";
import Pagination from "@/Components/Pagination.vue";
import { debounce } from "lodash";

const props = defineProps({
  clients: Object,
  filters: Object,
});

const Address = {
  address: "",
  country: "",
  type_id: 1,
};

const Phone = {
  nu: "",
  country_code: "00386",
  type_id: 1,
};

const formClient = useForm({
  first_name: "",
  last_name: "",
  full_name: "",
  tax_number: "",
  social_security_number: "",
  description: "",
  address: Address,
  phone: Phone,
});

//Create client drawer
const drawerCreateClient = ref(false);

// Search state (table-friendly, SPA)
const search = ref(props.filters?.search || "");
const applySearch = debounce((term) => {
  const params = Object.fromEntries(
    new URLSearchParams(window.location.search).entries()
  );
  if (term) {
    params.search = term;
  } else {
    delete params.search;
  }
  delete params.page; // reset pagination
  router.get(route("client"), params, {
    preserveState: true,
    replace: true,
    preserveScroll: true,
  });
}, 300);
watch(search, (v) => applySearch(v));

//Open drawer create client
const openDrawerCreateClient = () => {
  drawerCreateClient.value = true;
};

//Close any drawer on page
const closeDrawer = () => {
  drawerCreateClient.value = false;
};

//Ajax call post to store new client
const storeClient = () => {
  formClient.post(route("client.store"), {
    onBefore: () => {
      formClient.address.type_id = Number(formClient.address.type_id);
    },
    onSuccess: () => {
      closeDrawer();
      formClient.reset();
    },
  });
};

// Formatting helpers
const fmtCurrency = (v) => {
  const n = Number(v ?? 0);
  try {
    return new Intl.NumberFormat("sl-SI", { style: "currency", currency: "EUR" }).format(
      n
    );
  } catch (e) {
    return `${n.toFixed(2)} €`;
  }
};
</script>

<template>
  <AppLayout title="Client">
    <template #header>
      <h2 class="font-semibold text-xl text-gray-800 leading-tight"></h2>
    </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="flex items-center justify-between gap-3">
              <PrimaryButton @click="openDrawerCreateClient" class="bg-blue-400"
                >Dodaj</PrimaryButton
              >
              <input
                v-model="search"
                type="text"
                placeholder="Iskanje po imenu"
                class="w-full sm:w-80 rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 px-3 py-2 text-sm"
              />
            </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">Št.</th>
                    <th class="py-2 pr-4">Naročnik</th>
                    <th class="py-2 pr-4 text-right">Primeri z aktivnimi pogodbami</th>
                    <th class="py-2 pr-4 text-right">Skupaj stanje</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="client in clients.data"
                    :key="client.uuid"
                    class="border-b last:border-0"
                  >
                    <td class="py-2 pr-4">{{ client.person?.nu || "-" }}</td>
                    <td class="py-2 pr-4">
                      <Link
                        :href="route('client.show', { uuid: client.uuid })"
                        class="text-indigo-600 hover:underline"
                      >
                        {{ client.person?.full_name || "-" }}
                      </Link>
                      <div v-if="!client.person" class="mt-1">
                        <PrimaryButton
                          class="!py-0.5 !px-2 bg-red-500 hover:bg-red-600 text-xs"
                          @click.prevent="
                            router.post(
                              route('client.emergencyPerson', { uuid: client.uuid })
                            )
                          "
                          >Add Person</PrimaryButton
                        >
                      </div>
                    </td>
                    <td class="py-2 pr-4 text-right">
                      {{ client.cases_with_active_contracts_count ?? 0 }}
                    </td>
                    <td class="py-2 pr-4 text-right">
                      {{ fmtCurrency(client.active_contracts_balance_sum) }}
                    </td>
                  </tr>
                  <tr v-if="!clients.data || clients.data.length === 0">
                    <td colspan="4" class="py-4 text-gray-500">Ni zadetkov.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <Pagination
            :links="clients.links"
            :from="clients.from"
            :to="clients.to"
            :total="clients.total"
          />
        </div>
      </div>
    </div>
  </AppLayout>
  <DialogModal :show="drawerCreateClient" @close="drawerCreateClient = false">
    <template #title>Novi naročnik</template>
    <template #content>
      <form @submit.prevent="storeClient">
        <div>
          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="fullname" value="Naziv" />
            <TextInput
              id="fullname"
              ref="fullnameInput"
              v-model="formClient.full_name"
              type="text"
              class="mt-1 block w-full"
              autocomplete="full-name"
            />
          </div>

          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="taxnumber" value="Davčna" />
            <TextInput
              id="taxnumber"
              ref="taxnumberInput"
              v-model="formClient.tax_number"
              type="text"
              class="mt-1 block w-full"
              autocomplete="tax-number"
            />
          </div>

          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="socialSecurityNumber" value="Matična / Emšo" />
            <TextInput
              id="socialSecurityNumber"
              ref="socialSecurityNumberInput"
              v-model="formClient.social_security_number"
              type="text"
              class="mt-1 block w-full"
              autocomplete="social-security-number"
            />
          </div>

          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="address" value="Naslov" />
            <TextInput
              id="address"
              ref="addressInput"
              v-model="formClient.address.address"
              type="text"
              class="mt-1 block w-full"
              autocomplete="address"
            />
          </div>

          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="addressCountry" value="Država" />
            <TextInput
              id="addressCountry"
              ref="addressCountryInput"
              v-model="formClient.address.country"
              type="text"
              class="mt-1 block w-full"
              autocomplete="address-country"
            />
          </div>

          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="addressType" value="Vrsta naslova" />
            <select
              class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
              id="addressType"
              v-model="formClient.address.type_id"
            >
              <option value="1">Stalni</option>
              <option value="2">Začasni</option>
              <!-- ... -->
            </select>
          </div>
          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="phoneCountyCode" value="Koda države tel." />
            <select
              class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
              id="phoneCountyCode"
              v-model="formClient.phone.country_code"
            >
              <option value="00386">+386 (Slovenija)</option>
              <option value="00385">+385 (Hrvaška)</option>
              <option value="0039">+39 (Italija)</option>
              <option value="0036">+39 (Madžarska)</option>
              <option value="0043">+43 (Avstrija)</option>
              <option value="00381">+381 (Srbija)</option>
              <option value="00387">+387 (Bosna in Hercegovina)</option>
              <option value="00382">+382 (Črna gora)</option>
              <!-- ... -->
            </select>
          </div>
          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="phoneNu" value="Telefonska št." />
            <TextInput
              id="phoneNu"
              ref="phoneNuInput"
              v-model="formClient.phone.nu"
              type="text"
              class="mt-1 block w-full"
              autocomplete="phone-nu"
            />
          </div>
          <div class="col-span-6 sm:col-span-4">
            <InputLabel for="description" value="Opis" />
            <TextInput
              id="description"
              ref="descriptionInput"
              v-model="formClient.description"
              type="text"
              class="mt-1 block w-full"
              autocomplete="description"
            />
          </div>
        </div>
        <div class="flex justify-end mt-4">
          <ActionMessage :on="formClient.recentlySuccessful" class="me-3">
            Shranjeno.
          </ActionMessage>

          <PrimaryButton
            :class="{ 'opacity-25': formClient.processing }"
            :disabled="formClient.processing"
          >
            Shrani
          </PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>
</template>
