<script setup>
import PersonInfoGrid from "@/Components/PersonInfo/PersonInfoGrid.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import { Button } from "@/Components/ui/button";
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 DocumentEditDialog from "@/Components/DocumentEditDialog.vue";
import DocumentUploadDialog from "@/Components/DocumentUploadDialog.vue";
import DocumentViewerDialog from "@/Components/DocumentViewerDialog.vue";
import { classifyDocument } from "@/Services/documents";
import { router, useForm, usePage } from "@inertiajs/vue3";
import { AngleDownIcon, AngleUpIcon } from "@/Utilities/Icons";
import Pagination from "@/Components/Pagination.vue";
import DeleteDialog from "@/Components/Dialogs/DeleteDialog.vue";
import CreateDialog from "@/Components/Dialogs/CreateDialog.vue";
import { hasPermission } from "@/Services/permissions";
import ActionMenuItem from "@/Components/DataTable/ActionMenuItem.vue";
import { faPlus } from "@fortawesome/free-solid-svg-icons";

const props = defineProps({
  client: Object,
  client_case: Object,
  contracts: [Object, Array], // Can be paginated object or array (backward compatibility)
  activities: Object,
  contract_types: Array,
  account_types: { type: Array, default: () => [] },
  actions: Array,
  types: Object,
  documents: Array,
  segments: { type: Array, default: () => [] },
  all_segments: { type: Array, default: () => [] },
  current_segment: { type: Object, default: null },
  contract_doc_templates: { type: Array, default: () => [] },
});

// Extract contracts array from paginated object or use array directly
const contractsArray = computed(() => {
  if (Array.isArray(props.contracts)) {
    return props.contracts;
  }
  // Handle paginated contracts
  if (props.contracts?.data) {
    return props.contracts.data;
  }
  return [];
});

// Check if contracts are paginated
const contractsPaginated = computed(() => {
  return props.contracts && !Array.isArray(props.contracts) && props.contracts.data;
});

const page = usePage();
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"] });
};

// Helper to reload contracts while preserving pagination and segment filter
const reloadContracts = () => {
  const params = {};
  try {
    const url = new URL(window.location.href);
    const seg = url.searchParams.get("segment");
    if (seg) params.segment = seg;
    if (contractsPaginated.value) {
      const contractsPage = url.searchParams.get("contracts_page");
      if (contractsPage) params.contracts_page = contractsPage;
    }
  } catch (e) {}
  router.reload({ only: ["contracts"], data: params });
};

// Expose as a callable computed: use in templates as hasPerm('permission-slug')
const hasPerm = computed(() => (permission) =>
  hasPermission(page.props.auth?.user, permission)
);

// Document edit dialog state
const showDocEdit = ref(false);
const editingDoc = ref(null);
const openDocEdit = (doc) => {
  editingDoc.value = doc;
  showDocEdit.value = true;
};
const closeDocEdit = () => {
  showDocEdit.value = false;
  editingDoc.value = null;
};
const onDocSaved = () => {
  router.reload({ only: ["documents"] });
};

const viewer = ref({ open: false, src: "", title: "" });
const 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.value = { open: true, src: url, 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;
  }
};
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();
  // Keep segment filter and pagination in redirect
  const params = {};
  try {
    const url = new URL(window.location.href);
    const seg = url.searchParams.get("segment");
    if (seg) params.segment = seg;
    // Keep contracts page if paginated
    if (contractsPaginated.value) {
      const contractsPage = url.searchParams.get("contracts_page");
      if (contractsPage) params.contracts_page = contractsPage;
    }
  } catch (e) {}
  router.delete(
    route("clientCase.contract.delete", {
      client_case: props.client_case.uuid,
      uuid: c.uuid,
      ...params,
    }),
    {
      preserveScroll: true,
      onFinish: () => closeConfirmDelete(),
      // Reload contracts after delete to refresh pagination
      only: contractsPaginated.value ? ["contracts"] : undefined,
    }
  );
};

//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">
        <!-- Current segment badge (right aligned, above the card) -->
        <div v-if="current_segment" class="flex justify-end pb-3">
          <div class="text-sm text-gray-700">
            <span class="mr-2">Segment:</span>
            <span
              class="inline-block px-3 py-1 rounded-md border border-indigo-200 bg-indigo-50 text-indigo-800 font-medium"
            >
              {{ current_segment.name }}
            </span>
          </div>
        </div>
        <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 items-center">
            <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"
              :edit="hasPerm('client-edit')"
            />
          </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 flex items-center justify-between">
            <SectionTitle>
              <template #title> Primer - oseba </template>
            </SectionTitle>
            <div
              v-if="client_case && client_case.client_ref"
              class="text-xs text-gray-600"
            >
              <span class="mr-1">Ref:</span>
              <span
                class="inline-block px-2 py-0.5 rounded border bg-gray-50 font-mono text-gray-700"
                >{{ client_case.client_ref }}</span
              >
            </div>
          </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"
              :person-edit="hasPerm('person-edit')"
              :enable-sms="true"
              :client-case-uuid="client_case.uuid"
            />
          </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" v-if="hasPerm('contract-edit')">
                <Button @click="openDrawerCreateContract">Nova</Button>
                <Button
                  variant="outline"
                  :disabled="availableSegments.length === 0"
                  @click="openAttachSegment"
                >
                  {{
                    availableSegments.length
                      ? "Dodaj segment"
                      : "Ni razpoložljivih segmentov"
                  }}
                </Button>
              </div>
            </div>
            <ContractTable
              :client="client"
              :client_case="client_case"
              :contracts="contractsArray"
              :contract_types="contract_types"
              :segments="segments"
              :templates="contract_doc_templates"
              :edit="hasPerm('contract-edit')"
              :create-doc="hasPerm('create-docs')"
              @edit="openDrawerEditContract"
              @delete="requestDeleteContract"
              @add-activity="openDrawerAddActivity"
            />
            <div v-if="contractsPaginated" class="border-t border-gray-200">
              <Pagination
                :links="contracts.links"
                :from="contracts.from"
                :to="contracts.to"
                :total="contracts.total"
              />
            </div>
          </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>
            </div>
            <ActivityTable
              :client_case="client_case"
              :activities="activities"
              :edit="hasPerm('activity-edit')"
            >
              <template #add>
                <ActionMenuItem
                  label="Nova aktivnost"
                  :icon="faPlus"
                  @click="openDrawerAddActivity"
                />
              </template>
            </ActivityTable>
            <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>
              <Button @click="openUpload">Dodaj</Button>
            </div>
            <DocumentsTable
              :documents="documents"
              :edit="hasPerm('doc-edit')"
              @view="openViewer"
              @edit="openDocEdit"
              :download-url-builder="
                (doc) => {
                  const isContractDoc = (doc?.documentable_type || '')
                    .toLowerCase()
                    .includes('contract');
                  return isContractDoc && doc.contract_uuid
                    ? route('contract.document.download', {
                        contract: doc.contract_uuid,
                        document: doc.uuid,
                      })
                    : 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)"
      :contracts="contractsArray"
    />
    <DocumentEditDialog
      :show="showDocEdit"
      :client_case_uuid="client_case.uuid"
      :document="editingDoc"
      :contracts="contractsArray"
      @close="closeDocEdit"
      @saved="onDocSaved"
      v-if="hasPerm('doc-edit')"
    />
    <DocumentViewerDialog
      :show="viewer.open"
      :src="viewer.src"
      :title="viewer.title"
      @close="closeViewer"
    />
  </AppLayout>
  <ContractDrawer
    :show="drawerCreateContract"
    @close="closeDrawer"
    :types="contract_types"
    :account_types="account_types"
    :client_case="client_case"
    :contract="contractEditing"
  />
    <ActivityDrawer
      :show="drawerAddActivity"
      @close="closeDrawer"
      :client_case="client_case"
      :actions="actions"
      :contract-uuid="activityContractUuid"
      :documents="documents"
      :contracts="contractsArray"
    />
  <DeleteDialog
    :show="confirmDelete.show"
    title="Izbriši pogodbo"
    message="Ali ste prepričani, da želite izbrisati pogodbo?"
    confirm-text="Izbriši"
    :processing="false"
    @close="closeConfirmDelete"
    @confirm="doDeleteContract"
  />
  <CreateDialog
    :show="showAttachSegment"
    title="Dodaj segment k primeru"
    confirm-text="Dodaj"
    :processing="attachForm.processing"
    :disabled="!attachForm.segment_id"
    @close="closeAttachSegment"
    @confirm="submitAttachSegment"
  >
    <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-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-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>
  </CreateDialog>
</template>
