<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 });
}

// 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; },
  });
};
</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">
            <SectionTitle>
              <template #title>Stranka</template>
            </SectionTitle>
            <div class="mt-2">
              <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">
            <SectionTitle>
              <template #title>Primer - oseba</template>
            </SectionTitle>
            <div class="mt-2">
              <PersonDetailPhone :types="types" :person="client_case.person" default-tab="phones" />
            </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"
              >
                <div class="flex items-center justify-between">
                  <div>
                    <p class="font-medium text-gray-900">{{ c.reference || c.uuid }}</p>
                    <p class="text-sm text-gray-600">Tip: {{ c.type?.name || '—' }}</p>
                  </div>
                    <div class="text-right">
                      <div class="space-y-2">
                        <p v-if="c.account" class="text-sm text-gray-700">Odprto: {{ formatAmount(c.account.balance_amount) }} €</p>
                        <button
                          type="button"
                          class="text-sm px-3 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700 w-full sm:w-auto"
                          @click="openDrawerAddActivity(c)"
                        >+ Aktivnost</button>
                        <button
                          type="button"
                          class="text-sm px-3 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700 w-full sm:w-auto"
                          @click="openDocDialog(c)"
                        >+ Dokument</button>
                      </div>
                    </div>
                </div>
                  <div v-if="c.last_object" class="mt-2 text-sm text-gray-700">
                    <p class="font-medium">Predmet:</p>
                    <p>
                      <span class="text-gray-900">{{ c.last_object.name || c.last_object.reference }}</span>
                      <span v-if="c.last_object.type" class="ml-2 text-gray-500">({{ c.last_object.type }})</span>
                    </p>
                    <p v-if="c.last_object.description" class="text-gray-600 mt-1">{{ c.last_object.description }}</p>
                  </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>

        <!-- 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>

        <!-- 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-sm px-3 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700"
                @click="openDrawerAddActivity()"
              >Nova</button>
            </div>
            <div class="mt-2 divide-y">
              <div v-for="a in activities" :key="a.id" class="py-2 text-sm">
                <div class="flex items-center justify-between">
                  <div class="text-gray-800">{{ a.action?.name }}<span v-if="a.decision"> → {{ a.decision?.name }}</span></div>
                  <div class="text-right text-gray-500">
                    <div v-if="a.contract">Pogodba: {{ a.contract.reference }}</div>
                    <div class="text-xs" v-if="a.created_at || a.user || a.user_name">
                      <span v-if="a.created_at">{{ new Date(a.created_at).toLocaleDateString('sl-SI') }}</span>
                      <span v-if="(a.user && a.user.name) || a.user_name" class="ml-1">· {{ a.user?.name || a.user_name }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="a.note" class="text-gray-600">{{ a.note }}</div>
                <div class="text-gray-500">
                  <span v-if="a.due_date">Zapadlost: {{ a.due_date }}</span>
                  <span v-if="a.amount != null" class="ml-2">Znesek: {{ formatAmount(a.amount) }} €</span>
                </div>
              </div>
              <div v-if="!activities?.length" class="text-gray-600 py-2">Ni aktivnosti.</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>

    <!-- 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>
</style>
