<script setup>
import AppPhoneLayout from "@/Layouts/AppPhoneLayout.vue";
import PersonDetailPhone from "@/Components/PersonDetailPhone.vue";
import DocumentViewerDrawer from "@/Components/DocumentsTable/DocumentViewerDrawer.vue";
import { classifyDocument } from "@/Services/documents";
import { reactive, ref, computed, watch } from "vue";
import { useForm, router } from "@inertiajs/vue3";
import ActivityDrawerMobile from "@/Pages/Cases/Partials/ActivityDrawerMobile.vue";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
  CardFooter,
} from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { Separator } from "@/Components/ui/separator";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/Components/ui/accordion";
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerFooter,
  DrawerClose,
} from "@/Components/ui/drawer";
import { ScrollArea } from "@/Components/ui/scroll-area";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Checkbox } from "@/Components/ui/checkbox";
import {
  ArrowLeft,
  CheckCircle2,
  FileText,
  Calendar,
  Euro,
  User,
  Plus,
  Upload,
  Download,
  Eye,
  Building2,
  Activity,
  ChevronDown,
  ChevronUp,
  NotebookIcon,
  NotebookPenIcon,
  ListPlusIcon,
  HouseIcon,
} from "lucide-vue-next";
import { fmtCurrency, fmtDateDMY } from "@/Utilities/functions";

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

const viewer = reactive({ open: false, src: "", title: "", mimeType: "", filename: "" });
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;
    viewer.mimeType = doc.mime_type || "";
    viewer.filename = 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 = "";
  viewer.mimeType = "";
  viewer.filename = "";
}

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 textTrancate(text, maxLength = 100, showAll = false) {
  if (!text) return "";

  if (showAll) return text;

  return text.length > maxLength ? text.slice(0, maxLength) + "…" : text;
}

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) => {
  if (c && c.uuid) {
    activityContractUuid.value = c.uuid;
  } else if (Array.isArray(props.contracts) && props.contracts.length === 1) {
    activityContractUuid.value = props.contracts[0]?.uuid ?? null;
  } else {
    activityContractUuid.value = null;
  }
  drawerAddActivity.value = true;
};
const closeDrawer = () => {
  drawerAddActivity.value = false;
};

// After an activity is saved, if there are no contracts left for this case (assigned to me),
// redirect back to the Phone index to pick the next case.
const onActivitySaved = () => {
  // Inertia onSuccess already refreshed props, so props.contracts reflects current state.
  const count = Array.isArray(props.contracts) ? props.contracts.length : 0;
  if (count === 0) {
    router.visit(route("phone.index"));
  }
};

// Also react if the page is reloaded with zero contracts (e.g., after EndFieldJob moves the only contract):
const redirectIfNoContracts = () => {
  const count = Array.isArray(props.contracts) ? props.contracts.length : 0;
  if (count === 0) {
    router.visit(route("phone.index"));
  }
};

/*onMounted(() => {
  redirectIfNoContracts();
});*/

watch(
  () => (Array.isArray(props.contracts) ? props.contracts.length : null),
  (len) => {
    if (len === 0) {
      router.visit(route("phone.index"));
    }
  }
);

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

// Expanded activity notes
const expandedNotes = ref(new Set());
const toggleNote = (id) => {
  const next = new Set(expandedNotes.value);
  if (next.has(id)) {
    next.delete(id);
  } else {
    next.add(id);
  }
  expandedNotes.value = next;
};

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

// Normalise contract meta: handles JSON strings and PHP numeric-keyed wrappers.
// When a top-level value has no {title, value, type} shape but is itself a plain
// object, we flatten one level so the real meta entries become the top-level keys.
function normalizeMeta(meta) {
  if (!meta) return {};
  let obj = meta;
  if (typeof obj === "string") {
    try {
      obj = JSON.parse(obj);
    } catch {
      return {};
    }
  }
  if (typeof obj !== "object" || Array.isArray(obj)) return {};
  const result = {};
  for (const [key, val] of Object.entries(obj)) {
    if (
      val &&
      typeof val === "object" &&
      !Array.isArray(val) &&
      !("value" in val) &&
      !("title" in val)
    ) {
      // Nested meta map — flatten it one level
      Object.assign(result, val);
    } else {
      result[key] = val;
    }
  }
  return result;
}
</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">
          <Button variant="outline" size="sm" @click="router.visit(route('phone.index'))">
            <ArrowLeft />
            Nazaj
          </Button>
          <h2 class="font-semibold text-gray-800 dark:text-gray-100 truncate">
            {{ client_case?.person?.full_name }}
          </h2>
        </div>
        <div class="shrink-0">
          <Badge
            v-if="props.completed_mode"
            variant="secondary"
            class="bg-emerald-100 text-emerald-700 hover:bg-emerald-100"
          >
            <CheckCircle2 class="w-4 h-4" />
            Zaključeno danes
          </Badge>
          <Button
            v-else
            @click="confirmComplete = true"
            class="bg-green-600 hover:bg-green-700"
          >
            <CheckCircle2 class="w-4 h-4" />
            Zaključi
          </Button>
        </div>
      </div>
    </template>

    <div class="py-4 sm:py-2">
      <div class="mx-auto max-w-5xl px-2 sm:px-4 space-y-4">
        <!-- Client details (account holder) -->
        <Card class="p-0 py-2! gap-2">
          <CardHeader class="px-3 py-2! border-b">
            <CardTitle class="flex items-center gap-2 text-base justify-between">
              <div class="flex flex-row items-center gap-1">
                <Building2 class="w-5 h-5" />
                <p class="wrap-break-word max-w-36">{{ clientSummary.name }}</p>
              </div>
              <Badge variant="secondary">Naročnik</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent class="px-2">
            <PersonDetailPhone
              :types="types"
              :person="client.person"
              default-tab="phones"
            />
          </CardContent>
        </Card>

        <!-- Person (case person) -->
        <Card class="p-0 py-2! gap-2">
          <CardHeader class="px-3 py-2! border-b">
            <CardTitle class="flex items-center gap-2 text-base justify-between">
              <div class="flex flex-row items-center gap-1">
                <User class="w-5 h-5" />
                <p class="wrap-break-word max-w-36">{{ client_case.person.full_name }}</p>
              </div>
              <Badge variant="secondary">Primer</Badge>
            </CardTitle>
            <CardDescription
              v-if="client_case?.person?.description"
              class="mt-2 whitespace-pre-line"
            >
              {{ client_case.person.description }}
            </CardDescription>
            <p
              v-if="client_case?.person?.employer"
              class="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1 mt-1"
            >
              <Building2 class="w-3.5 h-3.5 shrink-0" />
              {{ client_case.person.employer }}
            </p>
          </CardHeader>
          <CardContent class="px-2">
            <PersonDetailPhone
              :types="types"
              :person="client_case.person"
              default-tab="addresses"
            />
          </CardContent>
        </Card>

        <!-- Contracts assigned to me -->
        <Card class="p-0 py-2! gap-2">
          <CardHeader class="px-3 py-2! border-b">
            <CardTitle class="flex items-center justify-between">
              <div class="flex flex-row items-center gap-1">
                <FileText class="w-5 h-5" />
                <span>Pogodbe</span>
              </div>
              <Badge v-if="contracts?.length" variant="secondary" class="ml-1 text-sm">
                {{ contracts.length }}
              </Badge>
            </CardTitle>
          </CardHeader>
          <CardContent class="px-0">
            <Accordion v-if="contracts?.length" type="multiple" class="w-full mb-2">
              <AccordionItem
                v-for="c in contracts"
                :key="c.uuid || c.id"
                :value="c.uuid || c.id"
                class="py-2 last:border-b-0"
              >
                <AccordionTrigger
                  class="px-3 py-2 text-sm font-medium tracking-wide flex items-center gap-2"
                >
                  <div class="flex items-center gap-2">
                    <p
                      class="font-bold rounded-md bg-accent max-w-36 px-3 py-2 wrap-break-word"
                    >
                      {{ c.reference || "Šifra pogodbe ni določena" }}
                    </p>
                    <span
                      class="font-bold rounded-md px-3 py-2 bg-red-50 text-red-600 border-red-100 tabular-nums"
                      >{{ fmtCurrency(c.account.balance_amount) || "0,00" }}</span
                    </span>
                  </div>
                  <div class="flex flex-row gap-2 flex-1 justify-end-safe pr-3">
                    <Button variant="outline" @click.stop="openDrawerAddActivity(c)">
                      <Activity class="w-4 h-4" />
                    </Button>
                    <Button variant="outline" @click.stop="openDocDialog(c)">
                      <Upload class="w-4 h-4" />
                    </Button>
                  </div>
                </AccordionTrigger>
                <AccordionContent class="px-4">
                  <div class="flex flex-col gap-1">
                    <div class="flex items-center justify-between border-b p-2">
                      <span class="font-bold"> Opis </span>
                      <NotebookPenIcon :size="18" />
                    </div>
                    <p class="wrap-break-word p-2 max-w-xs">
                      {{ textTrancate(c.description, 50, false) }}
                    </p>
                  </div>
                  <template v-if="Object.keys(normalizeMeta(c.meta)).length > 0">
                    <Separator class="my-1" />
                    <div
                      v-if="Object.keys(normalizeMeta(c.meta)).length > 0"
                      class="flex flex-col gap-1"
                    >
                      <div class="flex items-center justify-between border-b p-2">
                        <span class="font-bold"> Dodatno </span>
                        <ListPlusIcon :size="18" />
                      </div>
                      <div class="grid grid-cols-2 gap-1">
                        <div
                          v-for="(val, key) in normalizeMeta(c.meta)"
                          :key="key"
                          class="flex flex-col gap-2 px-2 py-2 bg-gray-50 dark:bg-gray-800/50 even:bg-gray-100 dark:even:bg-gray-700/50 rounded-lg"
                        >
                          <p
                            class="text-xs text-gray-500 dark:text-gray-400 shrink-0 uppercase wrap-break-word"
                          >
                            {{ val?.title?.replace(/_/g, " ") || key }}
                          </p>
                          <p
                            class="text-xs wrap-break-word font-semibold text-gray-800 dark:text-gray-200 text-right"
                          >
                            <template v-if="val?.type === 'date'">{{
                              formatDateShort(val.value) || val.value || ""
                            }}</template>
                            <template v-else-if="val?.type === 'number'">{{
                              val.value.toString().replace(/\./, ",") ?? ""
                            }}</template>
                            <template v-else>{{ val?.value ?? val ?? "" }}</template>
                          </p>
                        </div>
                      </div>
                    </div>
                  </template>
                  <template v-if="c.latest_object">
                    <Separator class="my-1" />
                    <div class="flex flex-col gap-1">
                      <div class="flex items-center justify-between border-b p-2">
                        <span class="font-bold"> Zadnji predmet </span>
                        <HouseIcon :size="18" />
                      </div>
                      <div class="p-2 max-w-xs flex items-center gap-1">
                        <p class="font-medium wrap-break-word">
                          {{ c.latest_object.name || c.latest_object.reference }}
                        </p>
                        <Badge variant="outline" v-if="c.latest_object.type">{{
                          c.latest_object.type
                        }}</Badge>
                        <p
                          v-if="c.latest_object.description"
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          {{ c.latest_object.description }}
                        </p>
                      </div>
                    </div>
                  </template>
                </AccordionContent>
              </AccordionItem>
            </Accordion>
            <p
              v-if="!contracts?.length"
              class="text-sm text-gray-600 dark:text-gray-400 text-center py-4"
            >
              Ni pogodbenih obveznosti dodeljenih vam za ta primer.
            </p>
          </CardContent>
        </Card>

        <!-- Activities -->
        <Card class="p-0 py-2 gap-2">
          <CardHeader class="px-3 py-1! border-b">
            <div class="flex items-center justify-between">
              <CardTitle class="flex items-center gap-2">
                <Activity class="w-4 h-4" />
                Aktivnosti
              </CardTitle>
              <Button size="lg" @click="openDrawerAddActivity()">
                <span class="text-sm">Nova Aktivnost</span>
                <Plus :size="14" />
              </Button>
            </div>
          </CardHeader>
          <CardContent class="p-0">
            <Card
              v-for="a in activities"
              :key="a.id"
              class="p-0 py-2 gap-0 rounded-none border-x-0 border-t-0 border-b-2 border-gray-200 dark:border-gray-700 last:border-b-0 shadow-none"
            >
              <CardHeader class="px-3 py-2">
                <div class="flex items-start justify-between">
                  <div class="flex flex-col gap-1">
                    <CardTitle class="text-sm font-medium wrap-break-word">
                      {{ activityActionLine(a) || "Aktivnost" }}
                    </CardTitle>
                    <CardDescription class="flex flex-wrap gap-1.5">
                      <Badge v-if="a.contract" variant="secondary" class="text-xs">
                        <FileText class="w-3 h-3" />
                        Pogodba: {{ a.contract.reference }}
                      </Badge>
                      <Badge
                        v-if="a.due_date"
                        variant="secondary"
                        class="bg-amber-100 text-amber-700 hover:bg-amber-100"
                      >
                        <Calendar class="w-3 h-3" />
                        Zapadlost: {{ fmtDateDMY(a.due_date) || "" }}
                      </Badge>
                      <Badge
                        v-if="a.amount != null"
                        variant="secondary"
                        class="bg-emerald-100 text-emerald-700 hover:bg-emerald-100"
                      >
                        <Euro class="w-3 h-3" />
                        Znesek: {{ fmtCurrency(a.amount) }}
                      </Badge>
                      <Badge v-if="a.status" variant="outline" class="text-[10px]">
                        {{ a.status }}
                      </Badge>
                    </CardDescription>
                  </div>
                  <div
                    class="shrink-0 text-right text-xs text-gray-500 dark:text-gray-400"
                  >
                    <div v-if="a.created_at" class="flex items-center gap-1">
                      <Calendar class="w-3 h-3" />
                      {{ formatDateShort(a.created_at) }}
                    </div>
                    <div
                      v-if="(a.user && a.user.name) || a.user_name"
                      class="truncate flex items-center gap-1 mt-1"
                    >
                      <User class="w-3 h-3" />
                      {{ a.user?.name || a.user_name }}
                    </div>
                  </div>
                </div>
              </CardHeader>
              <CardContent class="px-2 py-0">
                <div
                  v-if="a.note"
                  class="flex flex-col gap-1 cursor-pointer bg-accent rounded-lg p-2"
                  @click="toggleNote(a.id)"
                >
                  <p class="leading-7 wrap-break-word text-sm whitespace-pre-line">
                    {{ textTrancate(a.note, 50, expandedNotes.has(a.id)) }}
                  </p>
                  <div class="flex justify-end">
                    <Badge variant="outline" v-if="a.note?.length > 50">
                      <ChevronDown v-if="!expandedNotes.has(a.id)" :size="14" />
                      <ChevronUp v-else :size="14" />
                      {{ expandedNotes.has(a.id) ? "Skrij" : "Pokaži več" }}</Badge
                    >
                  </div>
                </div>
              </CardContent>
            </Card>
            <p
              v-if="!activities?.length"
              class="text-sm text-gray-600 dark:text-gray-400 text-center py-4"
            >
              Ni aktivnosti.
            </p>
          </CardContent>
        </Card>

        <!-- Documents (case + assigned contracts) -->
        <Card class="p-0 py-2 gap-2">
          <CardHeader class="px-3 py-1! border-b">
            <div class="flex items-center justify-between">
              <CardTitle class="flex items-center gap-1">
                <FileText class="w-4 h-4" />
                Dokumenti
              </CardTitle>
              <Button size="lg" variant="secondary" @click="openDocDialog()">
                Dodaj
                <Upload class="w-4 h-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent class="p-0">
            <div class="divide-y">
              <div v-for="d in documents" :key="d.uuid || d.id" class="p-3 first:pt-0">
                <div class="flex items-start justify-between gap-3">
                  <div class="flex-1">
                    <div
                      class="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2"
                    >
                      <FileText class="w-4 h-4 text-gray-400 shrink-0" />
                      <p class="wrap-break-word">{{ d.name || d.original_name }}</p>
                    </div>
                    <div
                      class="text-xs text-gray-500 dark:text-gray-400 mt-1 flex items-center gap-2 flex-wrap"
                    >
                      <Badge
                        v-if="d.contract_reference"
                        variant="outline"
                        class="text-[10px]"
                      >
                        Pogodba: {{ d.contract_reference }}
                      </Badge>
                      <Badge v-else variant="outline" class="text-[10px]"> Primer </Badge>
                      <span
                        v-if="d.mime_type"
                        class="text-[10px] text-gray-400 font-mono"
                        >{{ d.mime_type }}</span
                      >
                      <span v-if="d.created_at" class="flex items-center gap-1">
                        <Calendar class="w-3 h-3" />
                        {{ new Date(d.created_at).toLocaleDateString("sl-SI") }}
                      </span>
                    </div>
                    <p
                      v-if="d.description"
                      class="text-sm text-gray-600 dark:text-gray-400 mt-1 line-clamp-2"
                    >
                      {{ d.description }}
                    </p>
                  </div>
                  <div class="flex gap-1">
                    <Button size="sm" variant="ghost" @click="openViewer(d)">
                      <Eye class="w-4 h-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      as="a"
                      :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,
                              });
                        })()
                      "
                    >
                      <Download class="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </div>
              <p
                v-if="!documents?.length"
                class="text-sm text-gray-600 dark:text-gray-400 text-center py-4"
              >
                Ni dokumentov.
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>

    <DocumentViewerDrawer
      :show="viewer.open"
      :src="viewer.src"
      :title="viewer.title"
      :mime-type="viewer.mimeType"
      :filename="viewer.filename"
      @close="closeViewer"
    />
    <ActivityDrawerMobile
      :show="drawerAddActivity"
      @close="closeDrawer"
      @saved="onActivitySaved"
      :client_case="client_case"
      :actions="actions"
      :contract-uuid="activityContractUuid"
      :phone-mode="true"
      :documents="documents"
      :contracts="contracts"
    />

    <!-- Complete Case Confirmation -->
    <AlertDialog :open="confirmComplete" @update:open="confirmComplete = $event">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Potrditev</AlertDialogTitle>
          <AlertDialogDescription>
            Ali ste prepričani da želite že zaključit stranko?
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel @click="confirmComplete = false">
            Prekliči
          </AlertDialogCancel>
          <AlertDialogAction
            @click="submitComplete"
            class="bg-green-600 hover:bg-green-700"
          >
            Potrdi
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- Upload Document Drawer -->
    <Drawer :open="docDialogOpen" @update:open="(val) => !val && closeDocDialog()">
      <DrawerContent class="flex flex-col h-[90vh]">
        <DrawerHeader class="border-b px-4 py-3 shrink-0">
          <DrawerTitle>Dodaj dokument</DrawerTitle>
          <p v-if="selectedContract" class="text-sm text-muted-foreground mt-1">
            Dokument bo dodan k pogodbi:
            <strong>{{ selectedContract.reference || selectedContract.uuid }}</strong>
          </p>
        </DrawerHeader>
        <ScrollArea class="flex-1 min-h-0">
          <div class="px-4 py-4 space-y-4 w-full min-w-0">
            <div>
              <Label for="docFile">Datoteka</Label>
              <Input id="docFile" type="file" class="mt-1" @change="onPickDocument" />
              <p v-if="docForm.errors.file" class="text-sm text-red-600 mt-1">
                {{ docForm.errors.file }}
              </p>
            </div>
            <div>
              <Label for="docName">Ime</Label>
              <Input id="docName" v-model="docForm.name" class="mt-1" />
              <p v-if="docForm.errors.name" class="text-sm text-red-600 mt-1">
                {{ docForm.errors.name }}
              </p>
            </div>
            <div>
              <Label for="docDesc">Opis</Label>
              <Input id="docDesc" v-model="docForm.description" class="mt-1" />
              <p v-if="docForm.errors.description" class="text-sm text-red-600 mt-1">
                {{ docForm.errors.description }}
              </p>
            </div>
            <div class="flex items-center gap-2">
              <Checkbox id="docPublic" :model-value="docForm.is_public" />
              <Label for="docPublic">Javno</Label>
            </div>
          </div>
        </ScrollArea>
        <DrawerFooter class="border-t shrink-0 flex-row gap-2 px-4 py-3">
          <Button
            class="flex-1"
            :disabled="docForm.processing || !docForm.file"
            @click="submitDocument"
          >
            <Upload class="w-4 h-4" />
            Naloži
          </Button>
          <DrawerClose as-child>
            <Button variant="outline" class="flex-1" @click="closeDocDialog"
              >Prekliči</Button
            >
          </DrawerClose>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  </AppPhoneLayout>
</template>
