<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import { ref, computed } from "vue";
import { Link, router, useForm } from "@inertiajs/vue3";
import axios from "axios";
import DataTableServer from "@/Components/DataTable/DataTableServer.vue";
import PersonInfoGrid from "@/Components/PersonInfoGrid.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import Multiselect from "vue-multiselect";
import Dropdown from "@/Components/Dropdown.vue";
import DialogModal from "@/Components/DialogModal.vue";
import InputLabel from "@/Components/InputLabel.vue";

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

const fromDate = ref(props.filters?.from || "");
const toDate = ref(props.filters?.to || "");
const search = ref(props.filters?.search || "");
const selectedSegments = ref(
  props.filters?.segments
    ? props.segments.filter((s) => props.filters.segments.includes(s.id.toString()))
    : []
);
const selectedRows = ref([]);
const showSegmentModal = ref(false);
const targetSegmentId = ref(null);
const segmentForm = useForm({ segment_id: null, contracts: [] });

const exportDialogOpen = ref(false);
const exportScope = ref("current");
const exportColumns = ref(["reference", "customer", "start", "segment", "balance"]);
const exportError = ref("");
const isExporting = ref(false);

const exportableColumns = [
  { key: "reference", label: "Referenca" },
  { key: "customer", label: "Stranka" },
  { key: "start", label: "Začetek" },
  { key: "segment", label: "Segment" },
  { key: "balance", label: "Stanje" },
];

const allColumnsSelected = computed(
  () => exportColumns.value.length === exportableColumns.length
);
const exportDisabled = computed(
  () => exportColumns.value.length === 0 || isExporting.value
);
const currentPageCount = computed(() => props.contracts?.data?.length ?? 0);
const totalContracts = computed(() => props.contracts?.total ?? 0);

function toggleSelectAll() {
  if (selectedRows.value.length === props.contracts.data.length) {
    selectedRows.value = [];
  } else {
    selectedRows.value = props.contracts.data.map((row) => row.uuid);
  }
}

function toggleRowSelection(uuid) {
  const index = selectedRows.value.indexOf(uuid);
  if (index > -1) {
    selectedRows.value.splice(index, 1);
  } else {
    selectedRows.value.push(uuid);
  }
}

function isRowSelected(uuid) {
  return selectedRows.value.includes(uuid);
}

function isAllSelected() {
  return (
    props.contracts.data.length > 0 &&
    selectedRows.value.length === props.contracts.data.length
  );
}

function isIndeterminate() {
  return (
    selectedRows.value.length > 0 &&
    selectedRows.value.length < props.contracts.data.length
  );
}

function openSegmentModal() {
  if (!selectedRows.value.length) return;
  targetSegmentId.value = null;
  showSegmentModal.value = true;
}

function submitSegment() {
  if (!targetSegmentId.value || !selectedRows.value.length) return;
  segmentForm.segment_id = targetSegmentId.value;
  segmentForm.contracts = [...selectedRows.value];
  segmentForm.patch(route("contracts.segment"), {
    preserveScroll: true,
    onSuccess: () => {
      showSegmentModal.value = false;
      selectedRows.value = [];
      router.reload({ only: ["contracts"] });
    },
  });
}
function applyDateFilter() {
  const params = Object.fromEntries(
    new URLSearchParams(window.location.search).entries()
  );
  if (fromDate.value) {
    params.from = fromDate.value;
  } else {
    delete params.from;
  }
  if (toDate.value) {
    params.to = toDate.value;
  } else {
    delete params.to;
  }
  if (search.value && search.value.trim() !== "") {
    params.search = search.value.trim();
  } else {
    delete params.search;
  }
  if (selectedSegments.value && selectedSegments.value.length > 0) {
    params.segments = selectedSegments.value.map((s) => s.id).join(",");
  } else {
    delete params.segments;
  }
  delete params.page;
  router.get(route("client.contracts", { uuid: props.client.uuid }), params, {
    preserveState: true,
    replace: true,
    preserveScroll: true,
  });
}

function clearDateFilter() {
  fromDate.value = "";
  toDate.value = "";
  selectedSegments.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;
  }
}

function toggleAllColumns(checked) {
  exportColumns.value = checked ? exportableColumns.map((col) => col.key) : [];
}

function openExportDialog() {
  exportDialogOpen.value = true;
  exportError.value = "";
}

function closeExportDialog() {
  exportDialogOpen.value = false;
}

async function submitExport() {
  if (exportColumns.value.length === 0) {
    exportError.value = "Izberi vsaj en stolpec.";
    return;
  }

  try {
    exportError.value = "";
    isExporting.value = true;

    const payload = {
      scope: exportScope.value,
      columns: [...exportColumns.value],
      from: fromDate.value || "",
      to: toDate.value || "",
      search: search.value || "",
      segments:
        selectedSegments.value.length > 0
          ? selectedSegments.value.map((s) => s.id).join(",")
          : "",
      page: props.contracts.current_page,
      per_page: props.contracts.per_page,
    };

    const response = await axios.post(
      route("client.contracts.export", { uuid: props.client.uuid }),
      payload,
      { responseType: "blob" }
    );

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    const filename =
      extractFilenameFromHeaders(response.headers) || buildDefaultFilename();
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    exportDialogOpen.value = false;
  } catch (error) {
    console.error("Export error:", error);
    console.error("Error response:", error.response);

    let errorMessage = "Izvoz je spodletel. Poskusi znova.";

    if (error.response?.status === 404) {
      errorMessage = "Pot za izvoz ne obstaja. Prosim kontaktiraj administratorja.";
    } else if (error.response?.status === 500) {
      errorMessage = "Napaka na strežniku. Poskusi znova.";
    } else if (error.response?.data) {
      try {
        const text = await error.response.data.text();
        const json = JSON.parse(text);
        errorMessage = json.message || errorMessage;
      } catch (e) {
        console.error("Could not parse error response:", e);
      }
    }

    exportError.value = errorMessage;
  } finally {
    isExporting.value = false;
  }
}

function slugify(value) {
  if (!value) {
    return "data";
  }
  const slug = value.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "");
  return slug || "data";
}

function buildDefaultFilename() {
  const now = new Date();
  const dd = String(now.getDate()).padStart(2, "0");
  const mm = String(now.getMonth() + 1).padStart(2, "0");
  const yy = String(now.getFullYear()).slice(-2);
  const clientName = props.client?.person?.full_name || "stranka";
  return `${dd}${mm}${yy}_${slugify(clientName)}-Pogodbe.xlsx`;
}

function extractFilenameFromHeaders(headers) {
  if (!headers) {
    return null;
  }
  const disposition =
    headers["content-disposition"] || headers["Content-Disposition"] || "";
  if (!disposition) {
    return null;
  }
  const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
  if (utf8Match?.[1]) {
    try {
      return decodeURIComponent(utf8Match[1]);
    } catch (error) {
      return utf8Match[1];
    }
  }
  const asciiMatch = disposition.match(/filename="?([^";]+)"?/i);
  return asciiMatch?.[1] || null;
}
</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>
            <nav class="mt-2 border-b border-gray-200">
              <ul class="flex gap-6 -mb-px">
                <li>
                  <Link
                    :href="route('client.show', { uuid: client.uuid })"
                    :class="[
                      'inline-flex items-center px-3 py-2 text-sm font-medium border-b-2',
                      route().current('client.show')
                        ? 'text-indigo-600 border-indigo-600'
                        : 'text-gray-600 border-transparent hover:text-gray-800 hover:border-gray-300',
                    ]"
                  >
                    Primeri
                  </Link>
                </li>
                <li>
                  <Link
                    :href="route('client.contracts', { uuid: client.uuid })"
                    :class="[
                      'inline-flex items-center px-3 py-2 text-sm font-medium border-b-2',
                      route().current('client.contracts')
                        ? 'text-indigo-600 border-indigo-600'
                        : 'text-gray-600 border-transparent hover:text-gray-800 hover:border-gray-300',
                    ]"
                  >
                    Pogodbe
                  </Link>
                </li>
              </ul>
            </nav>
          </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">
            <!-- Filters Section -->
            <div class="bg-gray-50 rounded-lg border border-gray-200 p-3 mb-4">
              <div class="flex flex-wrap items-center gap-x-6 gap-y-3">
                <!-- Date Range -->
                <div class="flex flex-col gap-3">
                  <InputLabel value="Datum začetka" />
                  <div class="flex items-center gap-2">
                    <span class="text-xs text-gray-500">Od</span>
                    <input
                      type="date"
                      v-model="fromDate"
                      @change="applyDateFilter"
                      class="rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 text-sm py-1.5"
                    />
                    <span class="text-xs text-gray-500">Do</span>
                    <input
                      type="date"
                      v-model="toDate"
                      @change="applyDateFilter"
                      class="rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 text-sm py-1.5"
                    />
                  </div>
                </div>

                <!-- Segments -->
                <div class="flex flex-col gap-3">
                  <InputLabel for="segmentSelect" value="Segmenti" />
                  <Multiselect
                    v-model="selectedSegments"
                    :options="segments"
                    :multiple="true"
                    :close-on-select="false"
                    :clear-on-select="false"
                    :preserve-search="true"
                    :taggable="true"
                    :append-to-body="true"
                    placeholder="Izberi segmente"
                    label="name"
                    track-by="id"
                    id="segmentSelect"
                    :preselect-first="false"
                    @update:modelValue="applyDateFilter"
                    class="w-80"
                  >
                  </Multiselect>
                </div>

                <!-- Clear Button -->
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition ml-auto"
                  :disabled="!fromDate && !toDate && selectedSegments.length === 0"
                  @click="clearDateFilter"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-4 w-4 mr-1.5"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                  Počisti filtre
                </button>
              </div>
            </div>
            <DataTableServer
              class="mt-3"
              :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,
              }"
              route-name="client.contracts"
              :route-params="{ uuid: client.uuid }"
              :query="{
                from: fromDate || undefined,
                to: toDate || undefined,
                segments:
                  selectedSegments.length > 0
                    ? selectedSegments.map((s) => s.id).join(',')
                    : undefined,
              }"
              :search="search"
              row-key="uuid"
              :only-props="['contracts']"
            >
              <template #toolbar-extra>
                <div class="flex items-center gap-2">
                  <button
                    type="button"
                    class="inline-flex items-center rounded-md border border-indigo-200 bg-white px-3 py-2 text-sm font-medium text-indigo-700 shadow-sm hover:bg-indigo-50"
                    @click="openExportDialog"
                  >
                    Izvozi v Excel
                  </button>
                  <div v-if="selectedRows.length" class="flex items-center gap-2">
                    <div class="text-sm text-gray-700">
                      Izbrano: <span class="font-medium">{{ selectedRows.length }}</span>
                    </div>
                    <Dropdown width="48" align="left">
                      <template #trigger>
                        <button
                          type="button"
                          class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md border border-gray-300 text-gray-700 bg-white hover:bg-gray-50"
                        >
                          Akcije
                          <svg
                            class="ml-1 h-4 w-4"
                            viewBox="0 0 20 20"
                            fill="currentColor"
                            aria-hidden="true"
                          >
                            <path
                              fill-rule="evenodd"
                              d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z"
                              clip-rule="evenodd"
                            />
                          </svg>
                        </button>
                      </template>
                      <template #content>
                        <button
                          type="button"
                          class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                          @click="openSegmentModal"
                        >
                          Preusmeri v segment
                        </button>
                      </template>
                    </Dropdown>
                  </div>
                </div>
              </template>
              <template #header-select>
                <input
                  type="checkbox"
                  :checked="isAllSelected()"
                  :indeterminate="isIndeterminate()"
                  @change="toggleSelectAll"
                  class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                />
              </template>
              <template #cell-select="{ row }">
                <input
                  type="checkbox"
                  :checked="isRowSelected(row.uuid)"
                  @change="toggleRowSelection(row.uuid)"
                  class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                />
              </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>
              <template #empty>
                <div class="p-6 text-center text-gray-500">Ni zadetkov.</div>
              </template>
            </DataTableServer>

            <!-- Segment Reassignment Modal -->
            <DialogModal :show="showSegmentModal" @close="showSegmentModal = false">
              <template #title> Preusmeri v segment </template>
              <template #content>
                <div class="space-y-3">
                  <div class="text-sm text-gray-600">
                    Število izbranih pogodb:
                    <span class="font-medium">{{ selectedRows.length }}</span>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1"
                      >Ciljni segment</label
                    >
                    <select
                      v-model="targetSegmentId"
                      class="w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 text-sm"
                    >
                      <option :value="null" disabled>Izberi segment</option>
                      <option v-for="seg in segments" :key="seg.id" :value="seg.id">
                        {{ seg.name }}
                      </option>
                    </select>
                    <div
                      v-if="segmentForm.errors.segment_id"
                      class="mt-1 text-sm text-red-600"
                    >
                      {{ segmentForm.errors.segment_id }}
                    </div>
                  </div>
                </div>
              </template>
              <template #footer>
                <button
                  type="button"
                  class="px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 mr-2"
                  @click="showSegmentModal = false"
                >
                  Prekliči
                </button>
                <button
                  type="button"
                  class="px-3 py-1.5 text-sm rounded-md bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50"
                  :disabled="
                    !targetSegmentId || !selectedRows.length || segmentForm.processing
                  "
                  @click="submitSegment"
                >
                  Potrdi
                </button>
              </template>
            </DialogModal>

            <!-- Export Dialog Modal -->
            <DialogModal
              :show="exportDialogOpen"
              max-width="3xl"
              @close="closeExportDialog"
            >
              <template #title>
                <div>
                  <h3 class="text-lg font-semibold">Izvoz v Excel</h3>
                  <p class="text-sm text-gray-500">
                    Izberi stolpce in obseg podatkov za izvoz.
                  </p>
                </div>
              </template>
              <template #content>
                <form
                  id="contract-export-form"
                  class="space-y-6"
                  @submit.prevent="submitExport"
                >
                  <div>
                    <span class="text-sm font-semibold text-gray-700"
                      >Obseg podatkov</span
                    >
                    <div class="mt-2 space-y-2">
                      <label class="flex items-center gap-2 text-sm text-gray-700">
                        <input
                          type="radio"
                          name="scope"
                          value="current"
                          class="text-indigo-600"
                          v-model="exportScope"
                        />
                        Trenutna stran ({{ currentPageCount }} zapisov)
                      </label>
                      <label class="flex items-center gap-2 text-sm text-gray-700">
                        <input
                          type="radio"
                          name="scope"
                          value="all"
                          class="text-indigo-600"
                          v-model="exportScope"
                        />
                        Vse pogodbe ({{ totalContracts }} zapisov)
                      </label>
                    </div>
                  </div>

                  <div>
                    <div class="flex items-center justify-between">
                      <span class="text-sm font-semibold text-gray-700">Stolpci</span>
                      <label class="flex items-center gap-2 text-xs text-gray-600">
                        <input
                          type="checkbox"
                          :checked="allColumnsSelected"
                          @change="toggleAllColumns($event.target.checked)"
                        />
                        Označi vse
                      </label>
                    </div>
                    <div class="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
                      <label
                        v-for="col in exportableColumns"
                        :key="col.key"
                        class="flex items-center gap-2 rounded border border-gray-200 px-3 py-2 text-sm"
                      >
                        <input
                          type="checkbox"
                          name="columns[]"
                          :value="col.key"
                          v-model="exportColumns"
                          class="text-indigo-600"
                        />
                        {{ col.label }}
                      </label>
                    </div>
                    <p v-if="exportError" class="mt-2 text-sm text-red-600">
                      {{ exportError }}
                    </p>
                  </div>
                </form>
              </template>
              <template #footer>
                <div class="flex flex-row gap-2">
                  <button
                    type="button"
                    class="text-sm text-gray-600 hover:text-gray-900"
                    @click="closeExportDialog"
                  >
                    Prekliči
                  </button>
                  <button
                    type="submit"
                    form="contract-export-form"
                    class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-60"
                    :disabled="exportDisabled"
                  >
                    <span v-if="!isExporting">Prenesi Excel</span>
                    <span v-else>Pripravljam ...</span>
                  </button>
                </div>
              </template>
            </DialogModal>
          </div>
          <!-- Pagination handled by DataTableServer -->
        </div>
      </div>
    </div>
  </AppLayout>
</template>
