<script setup>
/**
 * Customer dashboard — layout and dummy KPI/lists adapted from Top-Level-Punt
 * `Company/Dashboard/Index.vue` (Maestro customer fields + internal navigation).
 */
import BaseAlert from "../../../components/base/BaseAlert.vue";
import BaseButton from "../../../components/base/BaseButton.vue";
import BaseIcon from "../../../components/base/BaseIcon.vue";
import BaseKpiCard from "../../../components/base/BaseKpiCard.vue";
import BaseSubtitle from "../../../components/base/BaseSubtitle.vue";
import BaseTextButton from "../../../components/base/BaseTextButton.vue";
import BaseTitle from "../../../components/base/BaseTitle.vue";
import {
  BADGE_BASE_CLASSES,
  PRESET_BADGE_CLASSES,
} from "../../../constants/badgeStyles.js";
import { useOffersApi } from "../../offers/composables/useOffersApi.js";
import { computed, inject, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

const ctx = inject("customerDetailContext");
if (!ctx) {
  throw new Error("CustomerShowDashboard must be used under CustomerShowLayout");
}

const { customer, loading } = ctx;

const route = useRoute();
const router = useRouter();
const { listOffers } = useOffersApi();

const customerId = computed(() => String(route.params.id ?? ""));
const error = ref(null);
const showAllDetails = ref(false);

const offersTotal = ref(0);

const DUMMY_KPIS_EXTRA = {
  activeProjects: 12,
  openTasks: 5,
};
const DUMMY_TASKS = [
  {
    id: 1,
    title: "Offerte opstellen",
    due_date: "2025-03-01",
    status: "Open",
    priority: "Hoog",
  },
  {
    id: 2,
    title: "Project kick-off voorbereiden",
    due_date: "2025-03-05",
    status: "In progress",
    priority: "Normaal",
  },
  {
    id: 3,
    title: "Contract review",
    due_date: "2025-03-10",
    status: "Open",
    priority: "Laag",
  },
  {
    id: 4,
    title: "Statusrapport Q1",
    due_date: "2025-03-15",
    status: "Open",
    priority: "Normaal",
  },
];
const DUMMY_DOCUMENTS = [
  {
    id: 1,
    name: "Offerte_2025-001.pdf",
    modified_at: "2025-02-20",
    type: "PDF",
  },
  {
    id: 2,
    name: "Contract_voorstel.docx",
    modified_at: "2025-02-18",
    type: "Document",
  },
  {
    id: 3,
    name: "Presentatie_klant.pptx",
    modified_at: "2025-02-15",
    type: "Presentatie",
  },
];

const upcomingTasks = ref(DUMMY_TASKS);
const recentDocuments = ref(DUMMY_DOCUMENTS);

const contactsCount = computed(
  () => customer.value?.contacts?.length ?? 0,
);

async function loadOffersTotal() {
  if (!customerId.value) {
    return;
  }
  error.value = null;
  try {
    const payload = await listOffers({
      customer_id: customerId.value,
      per_page: 1,
      page: 1,
    });
    offersTotal.value = Number(payload?.meta?.total ?? 0);
  } catch {
    offersTotal.value = 0;
    error.value = "Kon offertes niet laden.";
  }
}

onMounted(loadOffersTotal);

watch(customerId, () => {
  void loadOffersTotal();
});

function goTo(name) {
  const id = customerId.value;
  router.push({ name, params: { id } });
}

function toggleAllData() {
  showAllDetails.value = !showAllDetails.value;
}

function formatDate(str) {
  if (!str) return "—";
  try {
    return new Date(str).toLocaleDateString("nl-NL", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return str;
  }
}

function taskStatusClass(status) {
  const value = String(status || "").toLowerCase();
  if (value.includes("open")) return PRESET_BADGE_CLASSES.success;
  if (value.includes("progress") || value.includes("bezig")) {
    return PRESET_BADGE_CLASSES.warn;
  }
  return PRESET_BADGE_CLASSES.secondary;
}

function documentTypeClass(type) {
  const value = String(type || "").toLowerCase();
  if (value.includes("pdf")) return PRESET_BADGE_CLASSES.info;
  if (value.includes("doc")) return PRESET_BADGE_CLASSES.warn;
  if (value.includes("present")) return PRESET_BADGE_CLASSES.purple;
  return PRESET_BADGE_CLASSES.secondary;
}
</script>

<template>
  <div class="space-y-6">
    <div
      class="rounded-xl bg-surface-100 dark:bg-surface-800/80 p-5 flex flex-wrap items-start justify-between gap-4"
    >
      <div class="min-w-0 flex-1">
        <div class="flex items-center gap-2 min-w-0">
          <BaseTitle :level="1" class="mb-0 truncate">{{
            loading ? "…" : (customer?.name ?? "—")
          }}</BaseTitle>
        </div>
        <BaseSubtitle
          v-if="!loading && (customer?.email || customer?.phone)"
          :level="4"
          muted
          class="!mb-0 mt-1"
        >
          <template v-if="customer?.email">{{ customer.email }}</template>
          <template v-if="customer?.email && customer?.phone"> · </template>
          <template v-if="customer?.phone">{{ customer.phone }}</template>
        </BaseSubtitle>
        <BaseButton
          variant="primary"
          text
          :label="
            showAllDetails ? 'Verberg alle gegevens' : 'Bekijk alle gegevens'
          "
          :icon="showAllDetails ? 'chevron-up' : 'chevron-down'"
          class="!px-0 mt-2 text-sm"
          type="button"
          @click="toggleAllData"
        />
      </div>
      <div
        v-if="showAllDetails && !loading"
        class="w-full border-t border-surface-200 dark:border-surface-700 pt-4 mt-2"
      >
        <dl class="grid grid-cols-1 md:grid-cols-3 gap-x-8 gap-y-3 text-sm">
          <div class="flex flex-col gap-0.5">
            <dt class="font-medium text-surface-500 dark:text-surface-400">
              Bedrijfsnaam
            </dt>
            <dd class="text-surface-900 dark:text-surface-0">
              {{ customer?.name ?? "—" }}
            </dd>
          </div>
          <div class="flex flex-col gap-0.5">
            <dt class="font-medium text-surface-500 dark:text-surface-400">
              E-mail
            </dt>
            <dd class="text-surface-900 dark:text-surface-0">
              {{ customer?.email || "—" }}
            </dd>
          </div>
          <div class="flex flex-col gap-0.5">
            <dt class="font-medium text-surface-500 dark:text-surface-400">
              Telefoon
            </dt>
            <dd class="text-surface-900 dark:text-surface-0">
              {{ customer?.phone || "—" }}
            </dd>
          </div>
          <div class="flex flex-col gap-0.5 md:col-span-2">
            <dt class="font-medium text-surface-500 dark:text-surface-400">
              Website
            </dt>
            <dd class="text-surface-900 dark:text-surface-0">
              <a
                v-if="customer?.website"
                :href="customer.website"
                target="_blank"
                rel="noopener noreferrer"
                class="text-primary hover:underline"
                >{{ customer.website }}</a
              >
              <template v-else>—</template>
            </dd>
          </div>
        </dl>
      </div>
    </div>

    <BaseAlert v-if="error" severity="warn" class="mb-4" :closable="false">
      {{ error }}
    </BaseAlert>

    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <BaseKpiCard
          title="Actieve projecten"
          :value="DUMMY_KPIS_EXTRA.activeProjects"
          icon="briefcase"
          icon-bg-class="bg-primary-100 dark:bg-primary-900/40"
          icon-color-class="text-primary-600 dark:text-primary-400"
          @click="goTo('customers-show')"
        />
        <BaseKpiCard
          title="Open taken"
          :value="DUMMY_KPIS_EXTRA.openTasks"
          icon="list"
          icon-bg-class="bg-amber-100 dark:bg-amber-900/40"
          icon-color-class="text-amber-600 dark:text-amber-400"
          @click="goTo('customers-show')"
        />
        <BaseKpiCard
          title="Contactpersonen"
          :value="contactsCount"
          icon="users"
          icon-bg-class="bg-blue-100 dark:bg-blue-900/40"
          icon-color-class="text-blue-600 dark:text-blue-400"
          @click="goTo('customers-show-contacts')"
        />
        <BaseKpiCard
          title="Offertes"
          :value="offersTotal"
          icon="file"
          icon-bg-class="bg-green-100 dark:bg-green-900/40"
          icon-color-class="text-green-600 dark:text-green-400"
          @click="goTo('customers-show-offers')"
        />
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div
          class="rounded-xl border border-surface-200 dark:border-surface-700 bg-white dark:bg-surface-800 p-5"
        >
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-2">
              <BaseIcon name="clipboard-check" class="text-surface-500" />
              <h3 class="m-0 text-base font-semibold">Komende taken</h3>
            </div>
            <BaseTextButton
              label="Bekijk alle taken"
              icon="arrow-right"
              class="!px-0 text-sm"
              type="button"
              @click="goTo('customers-show')"
            />
          </div>
          <ul class="list-none p-0 m-0">
            <li
              v-for="t in upcomingTasks"
              :key="t.id"
              class="flex items-center justify-between gap-2 py-2 border-b border-surface-200 dark:border-surface-700 last:border-b-0 hover:bg-surface-100/60 dark:hover:bg-surface-700/30 transition-colors cursor-pointer"
              @click="goTo('customers-show')"
            >
              <div class="flex min-w-0 items-center gap-2 flex-1">
                <BaseIcon
                  name="check-circle"
                  class="text-surface-400 text-sm"
                />
                <span class="font-medium truncate">{{ t.title }}</span>
              </div>
              <div class="flex items-center gap-2 shrink-0">
                <span
                  v-if="t.status"
                  :class="[BADGE_BASE_CLASSES, taskStatusClass(t.status)]"
                  >{{ t.status }}</span
                >
                <span class="text-sm text-surface-500">{{
                  formatDate(t.due_date)
                }}</span>
              </div>
            </li>
            <li
              v-if="upcomingTasks.length === 0"
              class="text-surface-500 text-sm py-4"
            >
              Geen komende taken
            </li>
          </ul>
        </div>

        <div
          class="rounded-xl border border-surface-200 dark:border-surface-700 bg-white dark:bg-surface-800 p-5"
        >
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-2">
              <BaseIcon name="file" class="text-surface-500" />
              <h3 class="m-0 text-base font-semibold">
                Laatst gewijzigde documenten
              </h3>
            </div>
            <BaseTextButton
              label="Bekijk alle documenten"
              icon="arrow-right"
              class="!px-0 text-sm"
              type="button"
              @click="goTo('customers-show')"
            />
          </div>
          <ul class="list-none p-0 m-0">
            <li
              v-for="d in recentDocuments"
              :key="d.id"
              class="flex items-center justify-between gap-2 py-2 border-b border-surface-200 dark:border-surface-700 last:border-b-0 hover:bg-surface-100/60 dark:hover:bg-surface-700/30 transition-colors cursor-pointer"
              @click="goTo('customers-show')"
            >
              <div class="flex min-w-0 items-center gap-2 flex-1">
                <BaseIcon name="file-text" class="text-surface-400 text-sm" />
                <span class="font-medium truncate">{{ d.name }}</span>
              </div>
              <div class="flex items-center gap-2 shrink-0">
                <span
                  v-if="d.type"
                  :class="[BADGE_BASE_CLASSES, documentTypeClass(d.type)]"
                  >{{ d.type }}</span
                >
                <span class="text-sm text-surface-500">{{
                  formatDate(d.modified_at)
                }}</span>
              </div>
            </li>
            <li
              v-if="recentDocuments.length === 0"
              class="text-surface-500 text-sm py-4"
            >
              Geen documenten
            </li>
          </ul>
        </div>
      </div>
  </div>
</template>
