<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 { Card } from "@/Components/ui/card";
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/DocumentsTable.vue";
import DocumentEditDialog from "@/Components/DocumentsTable/DocumentEditDialog.vue";
import DocumentUploadDialog from "@/Components/DocumentsTable/DocumentUploadDialog.vue";
import DocumentViewerDialog from "@/Components/DocumentsTable/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";
import { DropdownMenu } from "@/Components/ui/dropdown-menu";
import DropdownMenuContent from "@/Components/ui/dropdown-menu/DropdownMenuContent.vue";
import { Badge } from "@/Components/ui/badge";

const props = defineProps({
  client: Object,
  client_case: Object,
  contracts: Object, // Resource Collection with data/links/meta
  activities: Object, // Resource Collection with data/links/meta
  contract_types: Array,
  account_types: { type: Array, default: () => [] },
  actions: Array,
  types: Object,
  documents: Object, // Resource Collection with data property
  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 Resource Collection
const contractsArray = computed(() => {
  return props.contracts?.data || [];
});

// Contracts are always paginated now (Resource Collection)
const contractsPaginated = computed(() => {
  return props.contracts?.links !== undefined;
});

// Extract documents array from Resource Collection
const documentsArray = computed(() => {
  return props.documents?.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">
      <!-- Client details -->
      <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>
        <Card class="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>
            <Badge variant="secondary" class="bg-blue-500 text-white dark:bg-blue-600">
              Naročnik
            </Badge>
          </div>
        </Card>
      </div>
    </div>
    <div class="pt-1" :hidden="clientDetails">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card class="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>
        </Card>
      </div>
    </div>
    <!-- Case details -->
    <div class="pt-6">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card class="border-l-4 border-red-400">
          <div class="mx-auto max-w-4x1 p-3 flex items-center justify-between">
            <SectionTitle>
              <template #title>{{ client_case.person.full_name }}</template>
            </SectionTitle>
            <div class="flex items-center gap-2">
              <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>
              <Badge variant="destructive" class="text-white"> Primer </Badge>
            </div>
          </div>
        </Card>
      </div>
    </div>
    <div class="pt-1">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card class="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>
        </Card>
      </div>
    </div>
    <!-- Contracts section -->
    <div class="pt-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card>
          <div class="mx-auto max-w-4x1">
            <div class="p-3">
              <SectionTitle>
                <template #title> Pogodbe </template>
              </SectionTitle>
            </div>
            <ContractTable
              :client="client"
              :client_case="client_case"
              :contracts="contractsArray"
              :contract_types="contract_types"
              :segments="segments"
              :all_segments="all_segments"
              :templates="contract_doc_templates"
              :edit="hasPerm('contract-edit')"
              :create-doc="hasPerm('create-docs')"
              @edit="openDrawerEditContract"
              @delete="requestDeleteContract"
              @add-activity="openDrawerAddActivity"
              @create="openDrawerCreateContract"
              @attach-segment="openAttachSegment"
            />
            <div v-if="contractsPaginated" class="border-t border-gray-200 p-4">
              <Pagination
                :links="contracts.links"
                :from="contracts.from"
                :to="contracts.to"
                :total="contracts.total"
                :per-page="contracts.per_page || 50"
                :last-page="contracts.last_page"
                :current-page="contracts.current_page"
                per-page-param="contracts_per_page"
                page-param="contracts_page"
              />
            </div>
          </div>
        </Card>
      </div>
    </div>
    <!-- Activities section -->
    <div class="pt-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card>
          <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')"
              :actions="actions"
              :contracts="contractsArray"
              :page-size="activities.per_page || 20"
            >
              <template #add>
                <Button variant="outline" size="sm" @click="openDrawerAddActivity">
                  Nova aktivnost
                </Button>
              </template>
            </ActivityTable>
            <div class="border-t border-gray-200 p-4">
              <Pagination
                :links="activities.links"
                :from="activities.from"
                :to="activities.to"
                :total="activities.total"
                :per-page="activities.per_page || 15"
                :last-page="activities.last_page"
                :current-page="activities.current_page"
                per-page-param="activities_per_page"
                page-param="activities_page"
              />
            </div>
          </div>
        </Card>
      </div>
    </div>
    <!-- Documents section -->
    <div class="pt-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <Card>
          <div class="mx-auto max-w-4x1">
            <div class="p-4">
              <SectionTitle>
                <template #title>Dokumenti</template>
              </SectionTitle>
            </div>
            <DocumentsTable
              :documents="documents"
              :client-case="client_case"
              :edit="hasPerm('doc-edit')"
              :page-size="documents.per_page || 15"
              :page-size-options="[10, 15, 25, 50, 100]"
              @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,
                      });
                }
              "
            >
              <template #add>
                <Button variant="outline" @click="openUpload">Novi document</Button>
              </template>
            </DocumentsTable>
            <div class="border-t border-gray-200 p-4">
              <Pagination
                :links="documents.links"
                :from="documents.from"
                :to="documents.to"
                :total="documents.total"
                :per-page="documents.per_page || 15"
                :last-page="documents.last_page"
                :current-page="documents.current_page"
                per-page-param="documentsPerPage"
                page-param="documentsPage"
              />
            </div>
          </div>
        </Card>
      </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="documentsArray"
    :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>
