<script setup>
import AppPhoneLayout from "@/Layouts/AppPhoneLayout.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import PersonDetailPhone from "@/Components/PersonDetailPhone.vue";
// Removed table-based component for phone; render a list instead
// import DocumentsTable from '@/Components/DocumentsTable.vue';
import DocumentViewerDialog from "@/Components/DocumentViewerDialog.vue";
import { classifyDocument } from "@/Services/documents";
import { reactive, ref, computed } from "vue";
import DialogModal from "@/Components/DialogModal.vue";
import InputLabel from "@/Components/InputLabel.vue";
import TextInput from "@/Components/TextInput.vue";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import BasicButton from "@/Components/buttons/BasicButton.vue";
import { useForm } from "@inertiajs/vue3";
import ActivityDrawer from "@/Pages/Cases/Partials/ActivityDrawer.vue";
import ConfirmationModal from "@/Components/ConfirmationModal.vue";

const props = defineProps({
  client: Object,
  client_case: Object,
  contracts: Array,
  documents: Array,
  types: Object,
  actions: Array,
  activities: Array,
});

const viewer = reactive({ open: false, src: "", title: "" });
function openViewer(doc) {
  const kind = classifyDocument(doc);
  const isContractDoc = (doc?.documentable_type || "").toLowerCase().includes("contract");
  if (kind === "preview") {
    const url =
      isContractDoc && doc.contract_uuid
        ? route("contract.document.view", {
            contract: doc.contract_uuid,
            document: doc.uuid,
          })
        : route("clientCase.document.view", {
            client_case: props.client_case.uuid,
            document: doc.uuid,
          });
    viewer.open = true;
    viewer.src = url;
    viewer.title = doc.original_name || doc.name;
  } else {
    const url =
      isContractDoc && doc.contract_uuid
        ? route("contract.document.download", {
            contract: doc.contract_uuid,
            document: doc.uuid,
          })
        : route("clientCase.document.download", {
            client_case: props.client_case.uuid,
            document: doc.uuid,
          });
    window.location.href = url;
  }
}
function closeViewer() {
  viewer.open = false;
  viewer.src = "";
}

function formatAmount(val) {
  if (val === null || val === undefined) return "0,00";
  const num = typeof val === "number" ? val : parseFloat(val);
  if (Number.isNaN(num)) return String(val);
  return num.toLocaleString("sl-SI", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

function formatDateShort(val) {
  if (!val) return "";
  try {
    const d = new Date(val);
    if (Number.isNaN(d.getTime())) return "";
    return d.toLocaleDateString("sl-SI", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  } catch {
    return "";
  }
}

function activityActionLine(a) {
  const base = a?.action?.name || "";
  const decision = a?.decision?.name ? ` → ${a.decision.name}` : "";
  return base + decision;
}

// Activity drawer state
const drawerAddActivity = ref(false);
const activityContractUuid = ref(null);
const openDrawerAddActivity = (c = null) => {
  activityContractUuid.value = c?.uuid ?? null;
  drawerAddActivity.value = true;
};
const closeDrawer = () => {
  drawerAddActivity.value = false;
};

// Document upload state
const docDialogOpen = ref(false);
const docForm = useForm({
  file: null,
  name: "",
  description: "",
  is_public: true,
  contract_uuid: null,
});
const onPickDocument = (e) => {
  const f = e?.target?.files?.[0];
  if (f) {
    docForm.file = f;
  }
};
const openDocDialog = (c = null) => {
  docForm.contract_uuid = c?.uuid ?? null;
  docDialogOpen.value = true;
};
const closeDocDialog = () => {
  docDialogOpen.value = false;
};
const submitDocument = () => {
  if (!docForm.file) {
    return;
  }
  docForm.post(
    route("clientCase.document.store", { client_case: props.client_case.uuid }),
    {
      forceFormData: true,
      onSuccess: () => {
        closeDocDialog();
        docForm.reset("file", "name", "description", "is_public", "contract_uuid");
      },
    }
  );
};

const selectedContract = computed(() => {
  if (!docForm.contract_uuid) return null;
  return props.contracts?.find((c) => c.uuid === docForm.contract_uuid) || null;
});

// Complete flow
const confirmComplete = ref(false);
const submitComplete = () => {
  // POST to phone.case.complete and redirect handled by server
  // Use a small form post via Inertia
  const form = useForm({});
  form.post(route("phone.case.complete", { client_case: props.client_case.uuid }), {
    onFinish: () => {
      confirmComplete.value = false;
    },
  });
};

// Contracts objects (Predmeti) modal state
const objectsModal = reactive({ open: false, items: [], contract: null });
function getContractObjects(c) {
  if (!c) return [];
  // Try a few common property names; fallback empty
  return c.objects || c.contract_objects || c.items || [];
}
function openObjectsModal(c) {
  objectsModal.contract = c;
  objectsModal.items = getContractObjects(c) || [];
  objectsModal.open = true;
}
function closeObjectsModal() {
  objectsModal.open = false;
  objectsModal.items = [];
  objectsModal.contract = null;
}

// Client details (Stranka) summary
const clientSummary = computed(() => {
  const p = props.client?.person || {};
  return {
    name: p.full_name || p.name || "—",
    tax: p.tax_number || p.davcna || p.tax || null,
    emso: p.emso || p.ems || null,
    trr: p.trr || p.bank_account || null,
  };
});
</script>

<template>
  <AppPhoneLayout :title="`Primer: ${client_case?.person?.full_name || ''}`">
    <template #header>
      <div class="flex items-center justify-between gap-3">
        <div class="flex items-center gap-3 min-w-0">
          <a
            :href="route('phone.index')"
            class="text-sm text-blue-600 hover:underline shrink-0"
            >← Nazaj</a
          >
          <h2 class="font-semibold text-xl text-gray-800 truncate">
            {{ client_case?.person?.full_name }}
          </h2>
        </div>
        <div class="shrink-0">
          <button
            type="button"
            class="px-3 py-2 rounded bg-green-600 text-white hover:bg-green-700"
            @click="confirmComplete = true"
          >
            Zaključi
          </button>
        </div>
      </div>
    </template>

    <div class="py-4 sm:py-6">
      <div class="mx-auto max-w-5xl px-2 sm:px-4">
        <!-- Client details (account holder) -->
        <div class="bg-white rounded-lg shadow border overflow-hidden">
          <div class="p-3 sm:p-4">
            <h3
              class="text-base font-semibold text-gray-900 leading-tight flex items-center gap-2"
            >
              <span class="truncate">{{ clientSummary.name }}</span>
              <span class="chip-base chip-indigo">Naročnik</span>
            </h3>
            <div class="mt-4 pt-4 border-t border-dashed">
              <PersonDetailPhone
                :types="types"
                :person="client.person"
                default-tab="phones"
              />
            </div>
          </div>
        </div>

        <!-- Person (case person) -->
        <div class="bg-white rounded-lg shadow border overflow-hidden">
          <div class="p-3 sm:p-4">
            <h3
              class="text-base font-semibold text-gray-900 leading-tight flex items-center gap-2"
            >
              <span class="truncate">{{ client_case.person.full_name }}</span>
              <span class="chip-base chip-indigo">Primer</span>
            </h3>
            <div class="mt-4 pt-4 border-t border-dashed">
              <PersonDetailPhone
                :types="types"
                :person="client_case.person"
                default-tab="addresses"
              />
            </div>
          </div>
        </div>

        <!-- Contracts assigned to me -->
        <div class="mt-4 sm:mt-6 bg-white rounded-lg shadow border overflow-hidden">
          <div class="p-3 sm:p-4">
            <SectionTitle>
              <template #title>Pogodbe</template>
            </SectionTitle>
            <div class="mt-3 space-y-3">
              <div
                v-for="c in contracts"
                :key="c.uuid || c.id"
                class="rounded border p-3 sm:p-4 bg-white shadow-sm"
              >
                <!-- Header Row -->
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0">
                    <div class="flex items-center gap-2 flex-wrap">
                      <p
                        class="font-semibold text-gray-900 text-sm leading-tight truncate"
                      >
                        {{ c.reference || c.uuid }}
                      </p>
                      <span
                        v-if="c.type?.name"
                        class="inline-flex items-center px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 text-[11px] font-medium"
                      >
                        {{ c.type.name }}
                      </span>
                    </div>
                    <div v-if="c.account" class="mt-2 flex items-baseline gap-2">
                      <span class="uppercase tracking-wide text-[11px] text-gray-400"
                        >Odprto</span
                      >
                      <span
                        class="text-lg font-semibold text-gray-900 leading-none tracking-tight"
                        >{{ formatAmount(c.account.balance_amount) }} €</span
                      >
                    </div>
                  </div>
                  <div class="flex flex-col gap-1.5 w-32 text-right shrink-0">
                    <button
                      type="button"
                      class="text-sm px-3 py-2 rounded-md bg-indigo-600 text-white hover:bg-indigo-700 active:scale-[.97] transition shadow"
                      @click="openDrawerAddActivity(c)"
                    >
                      + Aktivnost
                    </button>
                    <button
                      type="button"
                      class="text-sm px-3 py-2 rounded-md bg-indigo-600 text-white hover:bg-indigo-700 active:scale-[.97] transition shadow"
                      @click="openDocDialog(c)"
                    >
                      + Dokument
                    </button>
                    <!--button
                      type="button"
                      :disabled="!getContractObjects(c).length"
                      @click="openObjectsModal(c)"
                      class="relative text-sm px-3 py-2 rounded-md flex items-center justify-center transition disabled:cursor-not-allowed disabled:opacity-50 bg-slate-600 text-white hover:bg-slate-700 active:scale-[.97] shadow"
                    >
                      Predmeti
                      <span
                        class="ml-1 inline-flex items-center justify-center min-w-[1.1rem] h-5 text-[11px] px-1.5 rounded-full bg-white/90 text-slate-700 font-medium"
                        >{{ getContractObjects(c).length }}</span
                      >
                    </button-->
                  </div>
                </div>
                <!-- Subject / Last Object -->
                <div v-if="c.last_object" class="mt-3 border-t pt-3">
                  <p class="text-[11px] uppercase tracking-wide text-gray-400 mb-1">
                    Zadnji predmet
                  </p>
                  <div class="text-sm font-medium text-gray-800">
                    {{ c.last_object.name || c.last_object.reference }}
                    <span
                      v-if="c.last_object.type"
                      class="ml-2 text-xs font-normal text-gray-500"
                      >({{ c.last_object.type }})</span
                    >
                  </div>
                  <div
                    v-if="c.last_object.description"
                    class="mt-1 text-sm text-gray-600 leading-snug"
                  >
                    {{ c.last_object.description }}
                  </div>
                </div>
              </div>
              <p v-if="!contracts?.length" class="text-sm text-gray-600">
                Ni pogodbenih obveznosti dodeljenih vam za ta primer.
              </p>
            </div>
          </div>
        </div>

        <!-- Activities -->
        <div class="mt-4 sm:mt-6 bg-white rounded-lg shadow border overflow-hidden">
          <div class="p-3 sm:p-4">
            <div class="flex items-center justify-between">
              <SectionTitle>
                <template #title>Aktivnosti</template>
              </SectionTitle>
              <button
                class="text-xs font-medium px-3 py-2 rounded-md bg-indigo-600 text-white shadow-sm active:scale-[.98] hover:bg-indigo-700"
                @click="openDrawerAddActivity()"
              >
                Nova
              </button>
            </div>
            <div class="mt-3 space-y-3">
              <div
                v-for="a in activities"
                :key="a.id"
                class="rounded-md border border-gray-200 bg-gray-50/70 px-3 py-3 shadow-sm text-[13px]"
              >
                <!-- Top line: action + date/user -->
                <div class="flex items-start justify-between gap-3">
                  <div class="font-medium text-gray-800 leading-snug truncate">
                    {{ activityActionLine(a) || "Aktivnost" }}
                  </div>
                  <div
                    class="shrink-0 text-right text-[11px] text-gray-500 leading-tight"
                  >
                    <div v-if="a.created_at">{{ formatDateShort(a.created_at) }}</div>
                    <div v-if="(a.user && a.user.name) || a.user_name" class="truncate">
                      {{ a.user?.name || a.user_name }}
                    </div>
                  </div>
                </div>

                <!-- Badges row -->
                <div class="mt-2 flex flex-wrap gap-1.5">
                  <span
                    v-if="a.contract"
                    class="inline-flex items-center rounded-full bg-indigo-100 text-indigo-700 px-2 py-0.5 text-[10px] font-medium"
                    >Pogodba: {{ a.contract.reference }}</span
                  >
                  <span
                    v-if="a.due_date"
                    class="inline-flex items-center rounded-full bg-amber-100 text-amber-700 px-2 py-0.5 text-[10px] font-medium"
                    >Zapadlost: {{ formatDateShort(a.due_date) || a.due_date }}</span
                  >
                  <span
                    v-if="a.amount != null"
                    class="inline-flex items-center rounded-full bg-emerald-100 text-emerald-700 px-2 py-0.5 text-[10px] font-medium"
                    >Znesek: {{ formatAmount(a.amount) }} €</span
                  >
                  <span
                    v-if="a.status"
                    class="inline-flex items-center rounded-full bg-gray-200 text-gray-700 px-2 py-0.5 text-[10px] font-medium"
                    >{{ a.status }}</span
                  >
                </div>

                <!-- Note -->
                <div v-if="a.note" class="mt-2 text-gray-700 leading-snug">
                  {{ a.note }}
                </div>
              </div>
              <div
                v-if="!activities?.length"
                class="text-gray-600 text-sm py-2 text-center"
              >
                Ni aktivnosti.
              </div>
            </div>
          </div>
        </div>

        <!-- Documents (case + assigned contracts) -->
        <div class="mt-4 sm:mt-6 bg-white rounded-lg shadow border overflow-hidden">
          <div class="p-3 sm:p-4">
            <div class="flex items-center justify-between">
              <SectionTitle>
                <template #title>Dokumenti</template>
              </SectionTitle>
              <button
                class="text-sm px-3 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700"
                @click="openDocDialog()"
              >
                Dodaj
              </button>
            </div>

            <div class="mt-3 divide-y">
              <div v-for="d in documents" :key="d.uuid || d.id" class="py-3">
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0">
                    <div class="font-medium text-gray-900 truncate">
                      {{ d.name || d.original_name }}
                    </div>
                    <div class="text-xs text-gray-500 mt-0.5">
                      <span v-if="d.contract_reference"
                        >Pogodba: {{ d.contract_reference }}</span
                      >
                      <span v-else>Primer</span>
                      <span v-if="d.created_at" class="ml-2"
                        >· {{ new Date(d.created_at).toLocaleDateString("sl-SI") }}</span
                      >
                    </div>
                    <div
                      v-if="d.description"
                      class="text-gray-600 text-sm mt-1 line-clamp-2"
                    >
                      {{ d.description }}
                    </div>
                  </div>
                  <div class="shrink-0 flex flex-col items-end gap-2">
                    <button
                      type="button"
                      class="text-xs px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 text-gray-800"
                      @click="openViewer(d)"
                    >
                      Ogled
                    </button>
                    <a
                      class="text-xs px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 text-gray-800"
                      :href="
                        (() => {
                          const isC = (d?.documentable_type || '')
                            .toLowerCase()
                            .includes('contract');
                          return isC && d.contract_uuid
                            ? route('contract.document.download', {
                                contract: d.contract_uuid,
                                document: d.uuid,
                              })
                            : route('clientCase.document.download', {
                                client_case: client_case.uuid,
                                document: d.uuid,
                              });
                        })()
                      "
                      >Prenesi</a
                    >
                  </div>
                </div>
              </div>
              <div v-if="!documents?.length" class="text-gray-600 text-sm py-2">
                Ni dokumentov.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <DocumentViewerDialog
      :show="viewer.open"
      :src="viewer.src"
      :title="viewer.title"
      @close="closeViewer"
    />
    <ActivityDrawer
      :show="drawerAddActivity"
      @close="closeDrawer"
      :client_case="client_case"
      :actions="actions"
      :contract-uuid="activityContractUuid"
    />

    <ConfirmationModal :show="confirmComplete" @close="confirmComplete = false">
      <template #title>Potrditev</template>
      <template #content> Ali ste prepričani da želite že zaključit stranko? </template>
      <template #footer>
        <button
          type="button"
          class="px-3 py-2 rounded bg-gray-100 hover:bg-gray-200"
          @click="confirmComplete = false"
        >
          Prekliči
        </button>
        <button
          type="button"
          class="px-3 py-2 rounded bg-green-600 text-white hover:bg-green-700 ml-2"
          @click="submitComplete"
        >
          Potrdi
        </button>
      </template>
    </ConfirmationModal>

    <!-- Contract Objects (Predmeti) Modal -->
    <DialogModal :show="objectsModal.open" @close="closeObjectsModal">
      <template #title>
        Predmeti
        <span
          v-if="objectsModal.contract"
          class="block text-xs font-normal text-gray-500 mt-0.5"
        >
          {{ objectsModal.contract.reference || objectsModal.contract.uuid }}
        </span>
      </template>
      <template #content>
        <div
          v-if="objectsModal.items.length"
          class="space-y-3 max-h-[60vh] overflow-y-auto pr-1"
        >
          <div
            v-for="(o, idx) in objectsModal.items"
            :key="o.id || o.uuid || idx"
            class="rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm"
          >
            <div class="font-medium text-gray-800 truncate">
              {{ o.name || o.reference || "#" + (o.id || o.uuid || idx + 1) }}
            </div>
            <div class="mt-0.5 text-xs text-gray-500 flex flex-wrap gap-x-2 gap-y-0.5">
              <span
                v-if="o.type"
                class="inline-flex items-center bg-indigo-100 text-indigo-700 px-1.5 py-0.5 rounded-full"
                >{{ o.type }}</span
              >
              <span
                v-if="o.status"
                class="inline-flex items-center bg-gray-200 text-gray-700 px-1.5 py-0.5 rounded-full"
                >{{ o.status }}</span
              >
              <span
                v-if="o.amount != null"
                class="inline-flex items-center bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full"
                >{{ formatAmount(o.amount) }} €</span
              >
            </div>
            <div v-if="o.description" class="mt-1 text-gray-600 leading-snug">
              {{ o.description }}
            </div>
          </div>
        </div>
        <div v-else class="text-gray-600 text-sm">Ni predmetov.</div>
      </template>
      <template #footer>
        <button
          type="button"
          class="px-3 py-2 rounded bg-gray-100 hover:bg-gray-200"
          @click="closeObjectsModal"
        >
          Zapri
        </button>
      </template>
    </DialogModal>

    <!-- Upload Document Modal -->
    <DialogModal :show="docDialogOpen" @close="closeDocDialog">
      <template #title>Dodaj dokument</template>
      <template #content>
        <div class="space-y-4">
          <div v-if="selectedContract" class="text-sm text-gray-700">
            Dokument bo dodan k pogodbi:
            <span class="font-medium">{{
              selectedContract.reference || selectedContract.uuid
            }}</span>
          </div>
          <div>
            <InputLabel for="docFile" value="Datoteka" />
            <input
              id="docFile"
              type="file"
              class="mt-1 block w-full"
              @change="onPickDocument"
            />
            <div v-if="docForm.errors.file" class="text-sm text-red-600 mt-1">
              {{ docForm.errors.file }}
            </div>
          </div>
          <div>
            <InputLabel for="docName" value="Ime" />
            <TextInput id="docName" v-model="docForm.name" class="mt-1 block w-full" />
            <div v-if="docForm.errors.name" class="text-sm text-red-600 mt-1">
              {{ docForm.errors.name }}
            </div>
          </div>
          <div>
            <InputLabel for="docDesc" value="Opis" />
            <TextInput
              id="docDesc"
              v-model="docForm.description"
              class="mt-1 block w-full"
            />
            <div v-if="docForm.errors.description" class="text-sm text-red-600 mt-1">
              {{ docForm.errors.description }}
            </div>
          </div>
          <div class="flex items-center gap-2">
            <input id="docPublic" type="checkbox" v-model="docForm.is_public" />
            <InputLabel for="docPublic" value="Javno" />
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-end gap-2">
          <button
            type="button"
            class="px-3 py-2 rounded bg-gray-100 hover:bg-gray-200"
            @click="closeDocDialog"
          >
            Prekliči
          </button>
          <button
            type="button"
            class="px-3 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700"
            :disabled="docForm.processing || !docForm.file"
            @click="submitDocument"
          >
            Naloži
          </button>
        </div>
      </template>
    </DialogModal>
  </AppPhoneLayout>
</template>

<style scoped>
/* Using basic CSS since @apply is not processed in this scoped block by default */
.chip-base {
  display: inline-flex;
  align-items: center;
  padding: 0.125rem 0.5rem; /* py-0.5 px-2 */
  border-radius: 9999px;
  font-size: 11px;
  font-weight: 500;
  line-height: 1.1;
}
.chip-indigo {
  background: #eef2ff;
  color: #3730a3;
} /* approx indigo-50 / indigo-700 */
.chip-default {
  background: #f1f5f9;
  color: #334155;
} /* slate-100 / slate-700 */
.chip-emerald {
  background: #ecfdf5;
  color: #047857;
} /* emerald-50 / emerald-700 */
</style>
