<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { apiDelete, apiGet, apiPost, apiPut } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import { liveUpdateState } from "../realtime";
import type { Communication, EntityLink } from "../types";

const emptyForm = () => ({
  communication_type: "internal_note",
  direction: "internal",
  subject: "",
  body: "",
  status: "open",
  occurred_at: null as string | null,
  links: [] as EntityLink[]
});

const records = ref<Communication[]>([]);
const selectedId = ref<string | null>(null);
const form = reactive(emptyForm());
const linkType = ref("customer");
const linkId = ref("");
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");

async function load() {
  const result = await apiGet<Communication[]>("/api/v1/communications");
  if (result.ok) records.value = result.data;
  else { status.value = result.message; kind.value = "error"; }
}

function createNew() {
  selectedId.value = null;
  Object.assign(form, emptyForm());
}

function select(record: Communication) {
  selectedId.value = record.id;
  Object.assign(form, { ...record, links: [...record.links] });
}

function addLink() {
  if (!linkId.value.trim()) return;
  form.links.push({ entity_type: linkType.value, entity_id: linkId.value.trim() });
  linkId.value = "";
}

function removeLink(index: number) {
  form.links.splice(index, 1);
}

async function save() {
  const result = selectedId.value
    ? await apiPut<Communication>(`/api/v1/communications/${selectedId.value}`, form)
    : await apiPost<Communication>("/api/v1/communications", form);
  status.value = result.ok ? "Kommunikation gespeichert." : result.message;
  kind.value = result.ok ? "success" : "error";
  if (result.ok) { selectedId.value = result.data.id; await load(); }
}

async function archiveRecord() {
  if (!selectedId.value) return;
  const result = await apiDelete(`/api/v1/communications/${selectedId.value}`);
  status.value = result.ok ? "Kommunikation archiviert." : result.message;
  kind.value = result.ok ? "success" : "error";
  if (result.ok) await load();
}

onMounted(load);
watch(() => liveUpdateState.revision, load);
</script>

<template>
  <PageHeader title="Kommunikation" description="E-Mails, Telefonate, Briefe, Besprechungen und interne Notizen." />
  <div class="workspace-split">
    <section class="panel list-panel">
      <div class="section-title"><h2>Verlauf</h2><button type="button" @click="createNew">Neu</button></div>
      <button v-for="record in records" :key="record.id" type="button" class="list-row" :class="{ selected: selectedId === record.id }" @click="select(record)">
        <strong>{{ record.subject }}</strong>
        <span>{{ record.communication_type }} · {{ record.direction }}</span>
        <small>{{ record.status }}</small>
      </button>
      <p v-if="records.length === 0" class="empty">Keine Kommunikation vorhanden.</p>
    </section>
    <section class="panel detail-panel">
      <form @submit.prevent="save">
        <div class="form-grid">
          <label class="field"><span>Typ</span><select v-model="form.communication_type"><option value="email">E-Mail</option><option value="phone">Telefon</option><option value="letter">Brief</option><option value="meeting">Besprechung</option><option value="internal_note">Interne Notiz</option></select></label>
          <label class="field"><span>Richtung</span><select v-model="form.direction"><option value="inbound">Eingehend</option><option value="outbound">Ausgehend</option><option value="internal">Intern</option></select></label>
          <label class="field"><span>Status</span><select v-model="form.status"><option value="open">Offen</option><option value="done">Erledigt</option><option value="archived">Archiviert</option></select></label>
          <label class="field"><span>Zeitpunkt</span><input v-model="form.occurred_at" placeholder="optional, ISO-Zeit" /></label>
          <label class="field full-width"><span>Betreff</span><input v-model="form.subject" required /></label>
          <label class="field full-width"><span>Inhalt</span><textarea v-model="form.body" rows="8" /></label>
        </div>
        <div class="sub-panel">
          <h2>Bezüge</h2>
          <div class="form-grid">
            <label class="field"><span>Typ</span><select v-model="linkType"><option value="customer">Kunde</option><option value="supplier">Lieferant</option><option value="activity">Aktivität</option><option value="quote">Angebot</option><option value="outgoing_invoice">Ausgangsrechnung</option><option value="incoming_invoice">Eingangsrechnung</option><option value="item">Artikel</option><option value="document">Dokument</option></select></label>
            <label class="field"><span>ID</span><input v-model="linkId" /></label>
          </div>
          <button type="button" class="secondary" @click="addLink">Bezug hinzufügen</button>
          <div v-for="(link, index) in form.links" :key="`${link.entity_type}-${link.entity_id}`" class="data-row">
            <strong>{{ link.entity_type }}</strong><span>{{ link.entity_id }}</span><button type="button" class="secondary" @click="removeLink(index)">Entfernen</button>
          </div>
        </div>
        <div class="form-actions"><button type="submit">Speichern</button><button v-if="selectedId" type="button" class="secondary" @click="archiveRecord">Archivieren</button></div>
        <FormStatus :message="status" :kind="kind" />
      </form>
    </section>
  </div>
</template>
