<script setup>
import PersonInfoGrid from "@/Components/PersonInfoGrid.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import { FwbButton } from "flowbite-vue";
import { onBeforeMount, ref, computed } from "vue";
import ContractDrawer from "./Partials/ContractDrawer.vue";
import ContractTable from "./Partials/ContractTable.vue";
import ActivityDrawer from "./Partials/ActivityDrawer.vue";
import ActivityTable from "./Partials/ActivityTable.vue";
import DocumentsTable from "@/Components/DocumentsTable.vue";
import DocumentUploadDialog from "@/Components/DocumentUploadDialog.vue";
import DocumentViewerDialog from "@/Components/DocumentViewerDialog.vue";
import { classifyDocument } from "@/Services/documents";
import { router, useForm } from '@inertiajs/vue3';
import { AngleDownIcon, AngleUpIcon } from "@/Utilities/Icons";
import Pagination from "@/Components/Pagination.vue";
import ConfirmDialog from "@/Components/ConfirmDialog.vue";
import DialogModal from '@/Components/DialogModal.vue';

const props = defineProps({
  client: Object,
  client_case: Object,
  contracts: Array,
  activities: Object,
  contract_types: Array,
  actions: Array,
  types: Object,
  documents: Array,
  segments: { type: Array, default: () => [] },
  all_segments: { type: Array, default: () => [] },
});

const showUpload = ref(false);
const openUpload = () => { showUpload.value = true; };
const closeUpload = () => { showUpload.value = false; };
const onUploaded = () => {
  // Refresh page data to include the new document
  router.reload({ only: ['documents'] });
};

const viewer = ref({ open: false, src: '', title: '' });
const openViewer = (doc) => {
  const kind = classifyDocument(doc)
  if (kind === 'preview') {
    const url = route('clientCase.document.view', { client_case: props.client_case.uuid, document: doc.uuid })
    viewer.value = { open: true, src: url, title: doc.original_name || doc.name };
  } else {
    const url = route('clientCase.document.download', { client_case: props.client_case.uuid, document: doc.uuid })
    // immediate download: navigate to URL
    window.location.href = url
  }
};
const closeViewer = () => { viewer.value.open = false; viewer.value.src = ''; };

const clientDetails = ref(false);

// Contract drawer (create/edit)
const drawerCreateContract = ref(false);
const contractEditing = ref(null);
const openDrawerCreateContract = () => {
  contractEditing.value = null;
  drawerCreateContract.value = true;
};
const openDrawerEditContract = (c) => {
  contractEditing.value = c;
  drawerCreateContract.value = true;
};

//Drawer add new activity
const drawerAddActivity = ref(false);
const activityContractUuid = ref(null);

const openDrawerAddActivity = (c = null) => {
  activityContractUuid.value = c?.uuid ?? null;
  drawerAddActivity.value = true;
};

// delete confirmation
const confirmDelete = ref({ show: false, contract: null })
const requestDeleteContract = (c) => { confirmDelete.value = { show: true, contract: c } }
const closeConfirmDelete = () => { confirmDelete.value.show = false; confirmDelete.value.contract = null }
const doDeleteContract = () => {
  const c = confirmDelete.value.contract
  if (!c) return closeConfirmDelete()
  router.delete(route('clientCase.contract.delete', { client_case: props.client_case.uuid, uuid: c.uuid }), {
    preserveScroll: true,
    onFinish: () => closeConfirmDelete(),
  })
}

//Close drawer (all)
const closeDrawer = () => {
  drawerCreateContract.value = false;
  drawerAddActivity.value = false;
};

const showClientDetails = () => {
  clientDetails.value = false;
};

const hideClietnDetails = () => {
  clientDetails.value = true;
};

// Attach segment to case
const showAttachSegment = ref(false)
const openAttachSegment = () => { showAttachSegment.value = true }
const closeAttachSegment = () => { showAttachSegment.value = false }
const attachForm = useForm({ segment_id: null })
const availableSegments = computed(() => {
  const current = new Set((props.segments || []).map(s => s.id))
  return (props.all_segments || []).filter(s => !current.has(s.id))
})
const submitAttachSegment = () => {
  if (!attachForm.segment_id) { return }
  attachForm.post(route('clientCase.segments.attach', props.client_case), {
    preserveScroll: true,
    only: ['segments'],
    onSuccess: () => {
      closeAttachSegment()
      attachForm.reset('segment_id')
    }
  })
}
</script>
<template>
  <AppLayout title="Client case">
    <template #header></template>
    <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-500"
        >
          <div class="mx-auto max-w-4x1 p-3 flex justify-between">
            <SectionTitle>
              <template #title>
                <a class="hover:text-blue-500" :href="route('client.show', client)">
                  {{ client.person.full_name }}
                </a>
              </template>
            </SectionTitle>
            <button @click="showClientDetails" :hidden="clientDetails ? false : true">
              <AngleUpIcon />
            </button>
            <button :hidden="clientDetails" @click="hideClietnDetails">
              <AngleDownIcon />
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="pt-1" :hidden="clientDetails">
      <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">
            <PersonInfoGrid :types="types" :person="client.person" />
          </div>
        </div>
      </div>
    </div>
    <div class="pt-6">
      <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-red-400"
        >
          <div class="mx-auto max-w-4x1 p-3">
            <SectionTitle>
              <template #title> Primer - oseba </template>
            </SectionTitle>
          </div>
        </div>
      </div>
    </div>
    <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-red-400"
        >
          <div class="mx-auto max-w-4x1 p-3">
            <PersonInfoGrid :types="types" tab-color="red-600" :person="client_case.person" />
          </div>
        </div>
      </div>
    </div>
    <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">
          <div class="mx-auto max-w-4x1">
            <div class="flex justify-between p-3">
              <SectionTitle>
                <template #title> Pogodbe </template>
              </SectionTitle>
              <div class="flex items-center gap-2">
                <FwbButton @click="openDrawerCreateContract">Nova</FwbButton>
                <FwbButton color="light" :disabled="availableSegments.length === 0" @click="openAttachSegment">
                  {{ availableSegments.length ? 'Dodaj segment' : 'Ni razpoložljivih segmentov' }}
                </FwbButton>
              </div>
            </div>
            <ContractTable
              :client_case="client_case"
              :contracts="contracts"
              :contract_types="contract_types"
              :segments="segments"
              @edit="openDrawerEditContract"
              @delete="requestDeleteContract"
              @add-activity="openDrawerAddActivity"
            />
          </div>
        </div>
      </div>
    </div>
    
    <div class="pt-12 pb-6">
      <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">
          <div class="mx-auto max-w-4x1">
            <div class="flex justify-between p-4">
              <SectionTitle>
                <template #title>Aktivnosti</template>
          
              </SectionTitle>
              <FwbButton @click="openDrawerAddActivity">Nova</FwbButton>
            </div>
            <ActivityTable :client_case="client_case" :activities="activities" />
            <Pagination :links="activities.links" :from="activities.from" :to="activities.to" :total="activities.total" />
          </div>
        </div>
      </div>
    </div>
    <!-- Documents section -->
    <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">
          <div class="mx-auto max-w-4x1">
            <div class="flex justify-between p-4">
              <SectionTitle>
                <template #title>Dokumenti</template>
              </SectionTitle>
              <FwbButton @click="openUpload">Dodaj</FwbButton>
            </div>
            <DocumentsTable
              :documents="documents"
              @view="openViewer"
              :download-url-builder="doc => route('clientCase.document.download', { client_case: client_case.uuid, document: doc.uuid })"
            />
          </div>
        </div>
      </div>
    </div>
    <DocumentUploadDialog
      :show="showUpload"
      @close="closeUpload"
      @uploaded="onUploaded"
      :post-url="route('clientCase.document.store', client_case)"
    />
    <DocumentViewerDialog :show="viewer.open" :src="viewer.src" :title="viewer.title" @close="closeViewer" />
  </AppLayout>
  <ContractDrawer
    :show="drawerCreateContract"
    @close="closeDrawer"
    :types="contract_types"
    :client_case="client_case"
    :contract="contractEditing"
  />
  <ActivityDrawer
    :show="drawerAddActivity"
    @close="closeDrawer"
    :client_case="client_case"
    :actions="actions"
    :contract-uuid="activityContractUuid"
  />
  <ConfirmDialog
    :show="confirmDelete.show"
    title="Izbriši pogodbo"
    message="Ali ste prepričani, da želite izbrisati pogodbo?"
    confirm-text="Izbriši"
    :danger="true"
    @close="closeConfirmDelete"
    @confirm="doDeleteContract"
  />
  <DialogModal :show="showAttachSegment" @close="closeAttachSegment">
    <template #title>Dodaj segment k primeru</template>
    <template #content>
      <div class="space-y-2">
        <label class="block text-sm font-medium text-gray-700">Segment</label>
        <select v-model="attachForm.segment_id" class="w-full rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500">
          <option :value="null" disabled>-- izberi segment --</option>
          <option v-for="s in availableSegments" :key="s.id" :value="s.id">{{ s.name }}</option>
        </select>
        <div v-if="attachForm.errors.segment_id" class="text-sm text-red-600">{{ attachForm.errors.segment_id }}</div>
      </div>
    </template>
    <template #footer>
      <FwbButton color="light" @click="closeAttachSegment">Prekliči</FwbButton>
      <FwbButton class="ml-2" :disabled="attachForm.processing || !attachForm.segment_id" @click="submitAttachSegment">Dodaj</FwbButton>
    </template>
  </DialogModal>
</template>
