<script setup>
import AppPhoneLayout from "@/Layouts/AppPhoneLayout.vue";
import PersonDetailPhone from "@/Components/PersonDetailPhone.vue";
import DocumentViewerDialog from "@/Components/DocumentsTable/DocumentViewerDialog.vue";
import { classifyDocument } from "@/Services/documents";
import { reactive, ref, computed, watch } from "vue";
import { useForm, router } from "@inertiajs/vue3";
import ActivityDrawer from "@/Pages/Cases/Partials/ActivityDrawer.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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/Components/ui/dialog";
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,
  Phone,
  Mail,
  MapPin,
  Activity,
} from "lucide-vue-next";

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

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

// 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,
  };
});
</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="ghost"
            size="sm"
            @click="router.visit(route('phone.index'))"
            class="shrink-0"
          >
            <ArrowLeft class="w-4 h-4 mr-1" />
            Nazaj
          </Button>
          <h2 class="font-semibold text-xl 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-3 h-3 mr-1" />
            Zaključeno danes
          </Badge>
          <Button
            v-else
            @click="confirmComplete = true"
            class="bg-green-600 hover:bg-green-700"
          >
            <CheckCircle2 class="w-4 h-4 mr-2" />
            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 space-y-4">
        <!-- Client details (account holder) -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2 text-base">
              <Building2 class="w-5 h-5 text-gray-500" />
              <span class="truncate">{{ clientSummary.name }}</span>
              <Badge variant="secondary">Naročnik</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Separator class="mb-4" />
            <PersonDetailPhone
              :types="types"
              :person="client.person"
              default-tab="phones"
            />
          </CardContent>
        </Card>

        <!-- Person (case person) -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2 text-base">
              <User class="w-5 h-5 text-gray-500" />
              <span class="truncate">{{ client_case.person.full_name }}</span>
              <Badge variant="secondary">Primer</Badge>
            </CardTitle>
            <CardDescription
              v-if="client_case?.person?.description"
              class="mt-2 whitespace-pre-line"
            >
              {{ client_case.person.description }}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Separator class="mb-4" />
            <PersonDetailPhone
              :types="types"
              :person="client_case.person"
              default-tab="addresses"
            />
          </CardContent>
        </Card>

        <!-- Contracts assigned to me -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <FileText class="w-5 h-5" />
              Pogodbe
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-3">
            <Card
              v-for="c in contracts"
              :key="c.uuid || c.id"
              class="border-l-4 border-l-indigo-500"
            >
              <CardHeader class="pb-3">
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0 flex-1">
                    <div class="flex items-center gap-2 flex-wrap">
                      <CardTitle class="text-sm">
                        {{ c.reference || c.uuid }}
                      </CardTitle>
                      <Badge v-if="c.type?.name" variant="secondary" class="text-[11px]">
                        {{ c.type.name }}
                      </Badge>
                    </div>
                    <div v-if="c.account" class="mt-3 flex items-center gap-2">
                      <Euro class="w-4 h-4 text-gray-400" />
                      <div class="flex items-baseline gap-2">
                        <span class="text-xs text-gray-500 uppercase">Odprto</span>
                        <span
                          class="text-lg font-semibold text-gray-900 dark:text-gray-100"
                        >
                          {{ formatAmount(c.account.balance_amount) }} €
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="flex flex-col gap-2 shrink-0">
                    <Button size="sm" @click="openDrawerAddActivity(c)">
                      <Plus class="w-4 h-4 mr-1" />
                      Aktivnost
                    </Button>
                    <Button size="sm" variant="secondary" @click="openDocDialog(c)">
                      <Upload class="w-4 h-4 mr-1" />
                      Dokument
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent v-if="c.last_object" class="pt-0">
                <Separator class="mb-3" />
                <div class="space-y-1">
                  <p class="text-xs text-gray-500 uppercase">Zadnji predmet</p>
                  <div class="text-sm font-medium text-gray-800 dark:text-gray-200">
                    {{ c.last_object.name || c.last_object.reference }}
                    <span
                      v-if="c.last_object.type"
                      class="ml-2 text-xs font-normal text-gray-500"
                    >
                      ({{ c.last_object.type }})
                    </span>
                  </div>
                  <div
                    v-if="c.last_object.description"
                    class="text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ c.last_object.description }}
                  </div>
                </div>
              </CardContent>
            </Card>
            <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>
          <CardHeader>
            <div class="flex items-center justify-between">
              <CardTitle class="flex items-center gap-2">
                <Activity class="w-5 h-5" />
                Aktivnosti
              </CardTitle>
              <Button size="sm" @click="openDrawerAddActivity()">
                <Plus class="w-4 h-4 mr-1" />
                Nova
              </Button>
            </div>
          </CardHeader>
          <CardContent class="space-y-3">
            <Card
              v-for="a in activities"
              :key="a.id"
              class="bg-gray-50/70 dark:bg-gray-800/50"
            >
              <CardHeader>
                <div class="flex items-start justify-between gap-3">
                  <CardTitle class="text-sm font-medium truncate">
                    {{ activityActionLine(a) || "Aktivnost" }}
                  </CardTitle>
                  <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="pt-0 space-y-2">
                <div class="flex flex-wrap gap-1.5">
                  <Badge v-if="a.contract" variant="secondary" class="text-[10px]">
                    <FileText class="w-3 h-3 mr-1" />
                    Pogodba: {{ a.contract.reference }}
                  </Badge>
                  <Badge
                    v-if="a.due_date"
                    variant="secondary"
                    class="bg-amber-100 text-amber-700 hover:bg-amber-100 text-[10px]"
                  >
                    <Calendar class="w-3 h-3 mr-1" />
                    Zapadlost: {{ formatDateShort(a.due_date) || a.due_date }}
                  </Badge>
                  <Badge
                    v-if="a.amount != null"
                    variant="secondary"
                    class="bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px]"
                  >
                    <Euro class="w-3 h-3 mr-1" />
                    Znesek: {{ formatAmount(a.amount) }} €
                  </Badge>
                  <Badge v-if="a.status" variant="outline" class="text-[10px]">
                    {{ a.status }}
                  </Badge>
                </div>
                <p v-if="a.note" class="text-sm text-gray-700 dark:text-gray-300">
                  {{ a.note }}
                </p>
              </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>
          <CardHeader>
            <div class="flex items-center justify-between">
              <CardTitle class="flex items-center gap-2">
                <FileText class="w-5 h-5" />
                Dokumenti
              </CardTitle>
              <Button size="sm" variant="secondary" @click="openDocDialog()">
                <Upload class="w-4 h-4 mr-1" />
                Dodaj
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div class="divide-y">
              <div v-for="d in documents" :key="d.uuid || d.id" class="py-3 first:pt-0">
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0 flex-1">
                    <div
                      class="font-medium text-gray-900 dark:text-gray-100 truncate flex items-center gap-2"
                    >
                      <FileText class="w-4 h-4 text-gray-400 shrink-0" />
                      {{ d.name || d.original_name }}
                    </div>
                    <div
                      class="text-xs text-gray-500 dark:text-gray-400 mt-1 flex items-center gap-2"
                    >
                      <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.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="shrink-0 flex gap-2">
                    <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>

    <DocumentViewerDialog
      :show="viewer.open"
      :src="viewer.src"
      :title="viewer.title"
      @close="closeViewer"
    />
    <ActivityDrawer
      :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 Dialog -->
    <Dialog :open="docDialogOpen" @update:open="docDialogOpen = $event">
      <DialogContent class="max-w-md">
        <DialogHeader>
          <DialogTitle>Dodaj dokument</DialogTitle>
          <DialogDescription v-if="selectedContract">
            Dokument bo dodan k pogodbi:
            <strong>{{ selectedContract.reference || selectedContract.uuid }}</strong>
          </DialogDescription>
        </DialogHeader>
        <div class="space-y-4">
          <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>
        <DialogFooter>
          <Button variant="outline" @click="closeDocDialog"> Prekliči </Button>
          <Button :disabled="docForm.processing || !docForm.file" @click="submitDocument">
            <Upload class="w-4 h-4 mr-2" />
            Naloži
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </AppPhoneLayout>
</template>
