<template>
  <v-container fluid class="">
    <!-- Header -->
    <v-row no-gutters class="mb-6">
      <v-col cols="12">
        <h1 class="text-h4 text-md-h3 font-weight-bold">
          Dashboard{{ currentSiteName ? ` - ${currentSiteName}` : "" }}
        </h1>
      </v-col>
    </v-row>

    <!-- Count Cards -->
    <v-row class="mb-4">
      <v-col
        v-for="card in countCardList"
        :key="card.id"
        cols="12"
        sm="6"
        md="6"
        lg="4"
        xl="2.4"
      >
        <v-card flat border class="h-100 card-hover" elevation="0">
          <v-card-text class="pa-4 pa-md-6">
            <v-row no-gutters class="align-start">
              <v-col cols="8">
                <p class="text-caption text-grey-darken-1 mb-2 text-uppercase">
                  {{ card.label }}
                </p>
                <h2 class="text-h4 text-md-h3 font-weight-bold mb-3">
                  {{ card.value }}
                </h2>
                <v-chip :color="card.chipColor" size="small" variant="flat">
                  <v-icon
                    size="14"
                    icon="mdi-trending-up"
                    class="mr-1"
                  ></v-icon>
                  {{ card.percentage }}
                </v-chip>
              </v-col>
              <v-col cols="4" class="text-right">
                <div class="d-flex justify-end">
                  <div
                    class="avatar-custom"
                    :style="{ backgroundColor: card.color }"
                  >
                    <v-icon :icon="card.icon" color="white" size="28"></v-icon>
                  </div>
                </div>
              </v-col>
            </v-row>
            <v-row no-gutters class="mt-4">
              <v-col cols="12">
                <v-select
                  :model-value="card.period"
                  :items="['This Week', 'This Month', 'This Year']"
                  density="compact"
                  hide-details
                  variant="outlined"
                  @update:model-value="
                    updateCardPeriodDynamic(card.label, $event)
                  "
                ></v-select>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- Line Chart -->
    <!-- <v-row class="mb-4">
      <v-col cols="12">
        <v-card flat border elevation="0">
          <v-card-title class="pa-4 pa-md-6">
            <v-row no-gutters align="center">
              <v-col cols="12" md="6" class="mb-4 mb-md-0">
                <h3 class="text-h6 text-md-h5 font-weight-medium">
                  No. of Visitors
                </h3>
              </v-col>
              <v-col cols="12" md="6" class="d-flex justify-md-end">
                <v-select
                  v-model="visitorPeriod"
                  :items="['This Week', 'This Month', 'This Year']"
                  density="compact"
                  hide-details
                  variant="outlined"
                  style="max-width: 200px"
                ></v-select>
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-text class="pa-4 pa-md-6 pt-0">
            <div
              class="chart-container"
              style="min-height: 280px; overflow-x: auto"
            >
              <svg
                viewBox="0 0 1200 300"
                style="min-width: 800px; width: 100%; height: 100%"
                preserveAspectRatio="xMidYMid meet"
              >
              
                <text x="20" y="30" font-size="12" fill="#666">6</text>
                <text x="20" y="80" font-size="12" fill="#666">5</text>
                <text x="20" y="130" font-size="12" fill="#666">4</text>
                <text x="20" y="180" font-size="12" fill="#666">3</text>
                <text x="20" y="230" font-size="12" fill="#666">2</text>
                <text x="20" y="280" font-size="12" fill="#666">1</text>
                <text x="20" y="310" font-size="12" fill="#666">0</text>

           
                <line
                  x1="60"
                  y1="20"
                  x2="1180"
                  y2="20"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="70"
                  x2="1180"
                  y2="70"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="120"
                  x2="1180"
                  y2="120"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="170"
                  x2="1180"
                  y2="170"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="220"
                  x2="1180"
                  y2="220"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="270"
                  x2="1180"
                  y2="270"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="300"
                  x2="1180"
                  y2="300"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />

             
                <polyline
                  :points="visitorPoints.map((p) => `${p.x},${p.y}`).join(' ')"
                  fill="none"
                  stroke="#2196F3"
                  stroke-width="3"
                />
             
                <circle
                  v-for="point in visitorPoints"
                  :key="point.x"
                  :cx="point.x"
                  :cy="point.y"
                  r="5"
                  fill="#2196F3"
                />
                
                <text
                  v-for="(label, idx) in visitorLabels"
                  :key="idx"
                  :x="label.x"
                  y="320"
                  font-size="11"
                  fill="#666"
                  text-anchor="middle"
                >
                  {{ label.text }}
                </text>
              </svg>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row> -->

    <!-- Bar Chart -->
    <!-- <v-row class="mb-4">
      <v-col cols="12">
        <v-card flat border elevation="0">
          <v-card-title class="pa-4 pa-md-6">
            <v-row no-gutters align="center">
              <v-col cols="12" md="6" class="mb-4 mb-md-0">
                <h3 class="text-h6 text-md-h5 font-weight-medium">
                  Feedback Tickets
                </h3>
              </v-col>
              <v-col
                cols="12"
                md="6"
                class="d-flex flex-column flex-md-row justify-md-end gap-2"
              >
                <v-select
                  v-model="selectedService"
                  :items="serviceList"
                  item-title="name"
                  item-value="_id"
                  label="Select Service"
                  density="compact"
                  hide-details
                  variant="outlined"
                  style="max-width: 200px"
                  clearable
                  class="pr-4"
                  @update:model-value="selectedService = $event"
                ></v-select>
                <v-select
                  v-model="feedbackPeriod"
                  :items="['This Week', 'This Month', 'This Year']"
                  density="compact"
                  hide-details
                  variant="outlined"
                  style="max-width: 200px"
                ></v-select>
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-text class="pa-4 pa-md-6 pt-2">
            <div class="d-flex justify-center gap-4 mb-4">
              <div class="d-flex align-center">
                <div class="legend-box mr-2" style="background: #2196f3"></div>
                <span class="text-caption">Resolved</span>
              </div>
              <div class="d-flex align-center">
                <div class="legend-box mr-2" style="background: #4caf50"></div>
                <span class="text-caption">Unresolved</span>
              </div>
            </div>

            <div
              class="chart-container"
              style="min-height: 280px; overflow-x: auto"
            >
              <svg
                viewBox="0 0 1200 300"
                style="min-width: 800px; width: 100%; height: 100%"
                preserveAspectRatio="xMidYMid meet"
              >
                <text x="20" y="20" font-size="12" fill="#999">100</text>
                <text x="20" y="80" font-size="12" fill="#999">80</text>
                <text x="20" y="140" font-size="12" fill="#999">60</text>
                <text x="20" y="200" font-size="12" fill="#999">40</text>
                <text x="20" y="260" font-size="12" fill="#999">20</text>
                <text x="30" y="295" font-size="12" fill="#999">0</text>

                <line
                  x1="60"
                  y1="20"
                  x2="1180"
                  y2="20"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="80"
                  x2="1180"
                  y2="80"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="140"
                  x2="1180"
                  y2="140"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="200"
                  x2="1180"
                  y2="200"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="260"
                  x2="1180"
                  y2="260"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />
                <line
                  x1="60"
                  y1="290"
                  x2="1180"
                  y2="290"
                  stroke="#E0E0E0"
                  stroke-width="1"
                />

                <g v-for="(bar, idx) in feedbackBars" :key="idx">
                  <rect
                    :x="bar.x"
                    :y="bar.y"
                    :width="bar.width"
                    :height="bar.height"
                    :fill="bar.color"
                    rx="4"
                  />

                  <text
                    :x="bar.x + bar.width / 2"
                    :y="bar.y - 8"
                    font-size="14"
                    font-weight="bold"
                    fill="#333"
                    text-anchor="middle"
                  >
                    {{ bar.value }}
                  </text>

                  <text
                    :x="bar.x + bar.width / 2"
                    y="310"
                    font-size="12"
                    fill="#666"
                    text-anchor="middle"
                  >
                    {{ bar.label }}
                  </text>
                </g>
              </svg>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row> -->

    <!-- Pie Charts -->
    <!-- <v-row class="mb-4">
      <v-col v-for="pie in pieChartList" :key="pie.id" cols="12" md="6" lg="4">
        <v-card flat border elevation="0" class="h-100">
          <v-card-text class="pa-4 pa-md-6">
         
            <div class="mb-3">
              <h3 class="text-h6 font-weight-bold mb-1">{{ pie.title }}</h3>
              <p class="text-body-2 text-grey-darken-1">
                Total: {{ pie.total }}
              </p>
            </div>

          
            <div class="mb-4 d-flex flex-column gap-2">
            
              <v-select
                v-if="pie.id === 1"
                v-model="selectedBooking"
                :items="bookingsList"
                item-title="name"
                item-value="_id"
                label="Select Facility"
                density="compact"
                hide-details
                variant="outlined"
                clearable
                class="pb-4"
              ></v-select>
             
              <v-select
                :model-value="pie.period"
                :items="['This Week', 'This Month', 'This Year']"
                density="compact"
                hide-details
                variant="outlined"
                @update:model-value="updatePiePeriod(pie.id, $event)"
              ></v-select>
            </div>

       
            <div class="d-flex flex-wrap gap-3 mb-4">
              <div
                v-for="(segment, idx) in pie.segments"
                :key="idx"
                class="d-flex align-center mr-4 mb-2"
              >
                <div
                  class="legend-dot mr-2"
                  :style="{ backgroundColor: segment.color }"
                ></div>
                <span class="text-caption">{{ segment.label }}</span>
              </div>
            </div>

           
            <div class="d-flex justify-center align-center">
              <div class="position-relative">
                <svg viewBox="0 0 200 200" width="220" height="220">
                  <circle
                    v-for="(segment, idx) in pie.segments"
                    :key="idx"
                    cx="100"
                    cy="100"
                    r="70"
                    fill="none"
                    :stroke="segment.color"
                    stroke-width="45"
                    :stroke-dasharray="`${segment.percentage * 4.398} 439.8`"
                    :transform="`rotate(${segment.rotation} 100 100)`"
                    class="donut-segment"
                  />
                </svg>
             
                <div class="donut-center">
                  <p class="text-h5 font-weight-bold">{{ pie.centerValue }}</p>
                </div>
              </div>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row> -->

    <!-- Facility Section -->
    <!-- <v-row v-if="facilityBookings.length" class="mt-4">
      <v-col cols="12" class="mb-4">
        <h2 class="text-h5 font-weight-bold">Facility</h2>
      </v-col>
      <v-col
        v-for="booking in facilityBookings"
        :key="booking.id"
        cols="12"
        sm="6"
        md="6"
        lg="3"
      >
        <v-card flat border elevation="0" class="h-100 card-hover">
          <v-card-text class="pa-6">
            <v-row no-gutters align="start" class="mb-3">
              <v-col>
                <p class="text-body-2 text-grey-darken-1 mb-1">
                  {{ booking.label }}
                </p>
              </v-col>
              <v-col cols="auto">
                <v-icon
                  :icon="booking.icon"
                  :color="booking.iconColor"
                  size="28"
                ></v-icon>
              </v-col>
            </v-row>
            <h3 class="text-h3 font-weight-bold">
              {{ booking.value }}
            </h3>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row> -->
  </v-container>
</template>

<script setup lang="ts">
import useDashboard from '../composables/useDashboard';

const { getServiceProviderNames } = useServiceProvider();
const { getAll: getAllBuildings } = useBuilding();
const { getSiteById } = useSite();
const route = useRoute();
const { APP_NAME } = useRuntimeConfig().public;

// Get siteId from route params
const siteId = computed(() => (route.params.site as string) || "");

// Reactive site data that updates when siteId changes
const siteData = ref<any>(null);

// Fetch site data whenever siteId changes
watchEffect(async () => {
  if (siteId.value) {
    try {
      const site = await getSiteById(siteId.value);
      siteData.value = site;
    } catch (error) {
      console.error("Error fetching site:", error);
      siteData.value = null;
    }
  } else {
    siteData.value = null;
  }
});

// Get current site name from fetched site data
const currentSiteName = computed(() => siteData.value?.name || "");

// Type definitions
type Period = "This Week" | "This Month" | "This Year";
type CardType = "guest" | "pickup" | "dropoff" | "contractor" | "delivery";

interface CardPeriods {
  guest: Period;
  pickup: Period;
  dropoff: Period;
  contractor: Period;
  delivery: Period;
}

// Loading states
const isDashboardLoading = ref(false);
const isFeedbackTicketLoading = ref(false);

// Get dashboard data based on APP_NAME
const {
  cards: dashboardCards,
  feedbackItems,
  feedbackChartDataMap,
  periodMultipliers,
} = useDashboardData(APP_NAME);

// Period states for each section
const visitorPeriod = ref<Period>("This Week");
const feedbackPeriod = ref<Period>("This Week");
const bookingsPeriod = ref<Period>("This Week");
const buildingPeriod = ref<Period>("This Week");
const workOrdersPeriod = ref<Period>("This Week");

// Service provider states - now using feedback items from composable
const selectedService = ref<any>(null);
const serviceList = ref<Array<{ _id: string; name: string }>>(feedbackItems);

// Per-card periods keyed by label
const dynamicCardPeriods = ref<Record<string, Period>>({});
function updateCardPeriodDynamic(label: string, period: string) {
  dynamicCardPeriods.value[label] = period as Period;
}

// Booking filter - list of facilities/buildings
const selectedBooking = ref<any>(null);
const bookingsList = ref<Array<{ _id: string; name: string }>>([]);

// Individual card periods
const cardPeriods = ref<CardPeriods>({
  guest: "This Week",
  pickup: "This Week",
  dropoff: "This Week",
  contractor: "This Week",
  delivery: "This Week",
});

// Data sets for different periods
const dataByPeriod: Record<string, any> = {
  "This Week": {
    guest: { value: "156", percentage: "12.5 %", chipColor: "success" },
    pickup: { value: "42", percentage: "8.3 %", chipColor: "success" },
    dropoff: { value: "38", percentage: "5.2 %", chipColor: "success" },
    contractor: { value: "23", percentage: "-15.4 %", chipColor: "error" },
    delivery: { value: "67", percentage: "18.9 %", chipColor: "success" },
    visitors: [
      { x: 100, y: 220 },
      { x: 200, y: 180 },
      { x: 300, y: 150 },
      { x: 400, y: 200 },
      { x: 500, y: 140 },
      { x: 600, y: 160 },
      { x: 700, y: 100 },
      { x: 800, y: 130 },
      { x: 900, y: 90 },
      { x: 1000, y: 120 },
      { x: 1100, y: 80 },
    ],
    feedback: [
      {
        x: 100,
        y: 272,
        width: 60,
        height: 18,
        value: 1,
        label: "1",
        color: "#4CAF50",
      },
      {
        x: 200,
        y: 176,
        width: 60,
        height: 114,
        value: 19,
        label: "2",
        color: "#4CAF50",
      },
      {
        x: 300,
        y: 230,
        width: 60,
        height: 60,
        value: 10,
        label: "3",
        color: "#4CAF50",
      },
      {
        x: 400,
        y: 248,
        width: 60,
        height: 42,
        value: 7,
        label: "4",
        color: "#4CAF50",
      },
      {
        x: 500,
        y: 260,
        width: 60,
        height: 30,
        value: 5,
        label: "5",
        color: "#4CAF50",
      },
      {
        x: 600,
        y: 272,
        width: 60,
        height: 18,
        value: 3,
        label: "6",
        color: "#4CAF50",
      },
      {
        x: 700,
        y: 194,
        width: 60,
        height: 96,
        value: 16,
        label: "7",
        color: "#4CAF50",
      },
      {
        x: 800,
        y: 188,
        width: 60,
        height: 102,
        value: 17,
        label: "8",
        color: "#4CAF50",
      },
      {
        x: 900,
        y: 32,
        width: 60,
        height: 258,
        value: 86,
        label: "9",
        color: "#4CAF50",
      },
    ],
  },
  "This Month": {
    guest: { value: "624", percentage: "22.3 %", chipColor: "success" },
    pickup: { value: "178", percentage: "15.7 %", chipColor: "success" },
    dropoff: { value: "156", percentage: "12.1 %", chipColor: "success" },
    contractor: { value: "89", percentage: "-8.2 %", chipColor: "error" },
    delivery: { value: "245", percentage: "28.5 %", chipColor: "success" },
    visitors: [
      { x: 100, y: 180 },
      { x: 200, y: 150 },
      { x: 300, y: 120 },
      { x: 400, y: 160 },
      { x: 500, y: 100 },
      { x: 600, y: 130 },
      { x: 700, y: 80 },
      { x: 800, y: 110 },
      { x: 900, y: 70 },
      { x: 1000, y: 90 },
      { x: 1100, y: 60 },
    ],
    feedback: [
      {
        x: 100,
        y: 254,
        width: 60,
        height: 36,
        value: 6,
        label: "1",
        color: "#4CAF50",
      },
      {
        x: 200,
        y: 140,
        width: 60,
        height: 150,
        value: 25,
        label: "2",
        color: "#4CAF50",
      },
      {
        x: 300,
        y: 194,
        width: 60,
        height: 96,
        value: 16,
        label: "3",
        color: "#4CAF50",
      },
      {
        x: 400,
        y: 212,
        width: 60,
        height: 78,
        value: 13,
        label: "4",
        color: "#4CAF50",
      },
      {
        x: 500,
        y: 230,
        width: 60,
        height: 60,
        value: 10,
        label: "5",
        color: "#4CAF50",
      },
      {
        x: 600,
        y: 248,
        width: 60,
        height: 42,
        value: 7,
        label: "6",
        color: "#4CAF50",
      },
      {
        x: 700,
        y: 158,
        width: 60,
        height: 132,
        value: 22,
        label: "7",
        color: "#4CAF50",
      },
      {
        x: 800,
        y: 176,
        width: 60,
        height: 114,
        value: 19,
        label: "8",
        color: "#4CAF50",
      },
      {
        x: 900,
        y: 50,
        width: 60,
        height: 240,
        value: 80,
        label: "9",
        color: "#4CAF50",
      },
    ],
  },
  "This Year": {
    guest: { value: "7,842", percentage: "35.6 %", chipColor: "success" },
    pickup: { value: "2,134", percentage: "28.4 %", chipColor: "success" },
    dropoff: { value: "1,987", percentage: "24.9 %", chipColor: "success" },
    contractor: { value: "1,045", percentage: "5.3 %", chipColor: "success" },
    delivery: { value: "3,256", percentage: "42.8 %", chipColor: "success" },
    visitors: [
      { x: 100, y: 240 },
      { x: 200, y: 210 },
      { x: 300, y: 190 },
      { x: 400, y: 220 },
      { x: 500, y: 170 },
      { x: 600, y: 200 },
      { x: 700, y: 140 },
      { x: 800, y: 180 },
      { x: 900, y: 130 },
      { x: 1000, y: 160 },
      { x: 1100, y: 110 },
    ],
    feedback: [
      {
        x: 100,
        y: 236,
        width: 60,
        height: 54,
        value: 9,
        label: "1",
        color: "#4CAF50",
      },
      {
        x: 200,
        y: 104,
        width: 60,
        height: 186,
        value: 31,
        label: "2",
        color: "#4CAF50",
      },
      {
        x: 300,
        y: 176,
        width: 60,
        height: 114,
        value: 19,
        label: "3",
        color: "#4CAF50",
      },
      {
        x: 400,
        y: 194,
        width: 60,
        height: 96,
        value: 16,
        label: "4",
        color: "#4CAF50",
      },
      {
        x: 500,
        y: 212,
        width: 60,
        height: 78,
        value: 13,
        label: "5",
        color: "#4CAF50",
      },
      {
        x: 600,
        y: 230,
        width: 60,
        height: 60,
        value: 10,
        label: "6",
        color: "#4CAF50",
      },
      {
        x: 700,
        y: 122,
        width: 60,
        height: 168,
        value: 28,
        label: "7",
        color: "#4CAF50",
      },
      {
        x: 800,
        y: 158,
        width: 60,
        height: 132,
        value: 22,
        label: "8",
        color: "#4CAF50",
      },
      {
        x: 900,
        y: 20,
        width: 60,
        height: 270,
        value: 90,
        label: "9",
        color: "#4CAF50",
      },
    ],
  },
};


const { getDashboardData } = useDashboard();


const {
  data: getDashboardDataReq,
  refresh: getDashboardDataRefresh,
  pending: getDashboardDataPending,
} = await useLazyAsyncData(
  `get-dashboard-data-${siteId}`,
  () => getDashboardData({}),
  {
    watch: [ () => route.query],
  }
);

watch(getDashboardDataReq, (newVal) => {
  // items.value = newVal?.items || [];
  // pages.value = newVal?.pages || 0;
  // pageRange.value = newVal?.pageRange || "-- - -- of --";
});

// Computed properties for reactive data with site-based multiplier and APP_NAME-based cards
const countCardList = computed(() => {
  // Calculate multiplier based on siteId (different sites get different multipliers)
  const siteHash = siteId.value
    ? siteId.value.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)
    : 0;
  const siteMultiplier = siteId.value ? 0.6 + (siteHash % 40) / 100 : 1; // Between 0.6 and 1.0

  const applyMultiplier = (value: number) => {
    const newValue = Math.round(value * siteMultiplier);
    return newValue >= 1000 ? newValue.toLocaleString() : newValue.toString();
  };

  // Map dashboard cards to card list format
  return dashboardCards.map((card, idx) => {
    const label = card.title;
    const period =
      dynamicCardPeriods.value[label] ||
      (dynamicCardPeriods.value[label] = "This Week");
    const periodFactor = periodMultipliers[period] ?? 1;
    const multipliedValue = Math.round(card.value * periodFactor);

    return {
      id: idx + 1,
      label,
      value: applyMultiplier(multipliedValue),
      icon: card.icon,
      color: card.color,
      percentage: `${card.percentage > 0 ? "+" : ""}${card.percentage} %`,
      chipColor: card.isPositive ? "success" : "error",
      period,
    };
  });
});

// Computed reactive data
const visitorPoints = computed(
  () => dataByPeriod[visitorPeriod.value].visitors
);

const visitorLabels = [
  { x: 100, text: "Mon" },
  { x: 300, text: "Tue" },
  { x: 500, text: "Wed" },
  { x: 700, text: "Thu" },
  { x: 900, text: "Fri" },
  { x: 1100, text: "Sat" },
];

const feedbackBars = computed(() => {
  // If no service is selected, return the base data
  if (!selectedService.value) {
    return dataByPeriod[feedbackPeriod.value].feedback;
  }

  // If a service is selected, use the feedback chart data from composable
  const chartData = feedbackChartDataMap[selectedService.value];
  if (chartData && chartData[feedbackPeriod.value]) {
    return chartData[feedbackPeriod.value];
  }

  // Fallback to base data if service data not found
  return dataByPeriod[feedbackPeriod.value].feedback;
});

// Function to update individual card periods
const updateCardPeriod = (cardType: string, period: string) => {
  const validCardType = cardType as CardType;
  cardPeriods.value[validCardType] = period as Period;
};

// Function to update pie chart periods
const updatePiePeriod = (pieId: number, period: string) => {
  const validPeriod = period as Period;
  if (pieId === 1) bookingsPeriod.value = validPeriod;
  else if (pieId === 2) buildingPeriod.value = validPeriod;
  else if (pieId === 3) workOrdersPeriod.value = validPeriod;
};

// Function to fetch bookings data based on selected facility
const fetchBookingsData = async () => {
  if (!selectedBooking.value) {
    // Reset to base data when no booking selected
    return;
  }
};

// Watch for booking selection changes
watch(selectedBooking, () => {
  fetchBookingsData();
});

// Pie chart data by period
const pieChartDataByPeriod = {
  "This Week": {
    bookings: {
      total: 186,
      centerValue: "75.4%",
      segments: [
        {
          label: "approved",
          color: "#2196F3",
          percentage: 14.0,
          rotation: -90,
        },
        {
          label: "rejected",
          color: "#4CAF50",
          percentage: 10.6,
          rotation: -39.6,
        },
        {
          label: "pending",
          color: "#FFC107",
          percentage: 75.4,
          rotation: -1.44,
        },
      ],
    },
    building: {
      total: 278,
      centerValue: "98.2%",
      segments: [
        { label: "occupied", color: "#2196F3", percentage: 1.8, rotation: -90 },
        {
          label: "unoccupied",
          color: "#4CAF50",
          percentage: 98.2,
          rotation: -83.5,
        },
      ],
    },
    workOrders: {
      total: 127,
      centerValue: "33.3%",
      segments: [
        { label: "to-do", color: "#2196F3", percentage: 33.3, rotation: -90 },
        {
          label: "in-progress",
          color: "#4CAF50",
          percentage: 33.3,
          rotation: 29.9,
        },
        {
          label: "completed",
          color: "#FFC107",
          percentage: 33.4,
          rotation: 149.8,
        },
      ],
    },
  },
  "This Month": {
    bookings: {
      total: 742,
      centerValue: "68.2%",
      segments: [
        {
          label: "approved",
          color: "#2196F3",
          percentage: 22.5,
          rotation: -90,
        },
        {
          label: "rejected",
          color: "#4CAF50",
          percentage: 9.3,
          rotation: -9.0,
        },
        {
          label: "pending",
          color: "#FFC107",
          percentage: 68.2,
          rotation: 24.48,
        },
      ],
    },
    building: {
      total: 278,
      centerValue: "95.7%",
      segments: [
        { label: "occupied", color: "#2196F3", percentage: 4.3, rotation: -90 },
        {
          label: "unoccupied",
          color: "#4CAF50",
          percentage: 95.7,
          rotation: -74.5,
        },
      ],
    },
    workOrders: {
      total: 456,
      centerValue: "42.1%",
      segments: [
        { label: "to-do", color: "#2196F3", percentage: 28.5, rotation: -90 },
        {
          label: "in-progress",
          color: "#4CAF50",
          percentage: 29.4,
          rotation: 12.6,
        },
        {
          label: "completed",
          color: "#FFC107",
          percentage: 42.1,
          rotation: 118.4,
        },
      ],
    },
  },
  "This Year": {
    bookings: {
      total: 8924,
      centerValue: "58.9%",
      segments: [
        {
          label: "approved",
          color: "#2196F3",
          percentage: 35.6,
          rotation: -90,
        },
        {
          label: "rejected",
          color: "#4CAF50",
          percentage: 5.5,
          rotation: 38.16,
        },
        {
          label: "pending",
          color: "#FFC107",
          percentage: 58.9,
          rotation: 57.96,
        },
      ],
    },
    building: {
      total: 278,
      centerValue: "89.2%",
      segments: [
        {
          label: "occupied",
          color: "#2196F3",
          percentage: 10.8,
          rotation: -90,
        },
        {
          label: "unoccupied",
          color: "#4CAF50",
          percentage: 89.2,
          rotation: -51.1,
        },
      ],
    },
    workOrders: {
      total: 5234,
      centerValue: "62.8%",
      segments: [
        { label: "to-do", color: "#2196F3", percentage: 18.4, rotation: -90 },
        {
          label: "in-progress",
          color: "#4CAF50",
          percentage: 18.8,
          rotation: -23.8,
        },
        {
          label: "completed",
          color: "#FFC107",
          percentage: 62.8,
          rotation: 43.8,
        },
      ],
    },
  },
};

// Computed Pie Charts Data
const pieChartList = computed(() => {
  // Get base bookings data
  const baseBookingsData = pieChartDataByPeriod[bookingsPeriod.value].bookings;
  let bookingsData = { ...baseBookingsData };

  if (selectedBooking.value) {
    const bookingHash = selectedBooking.value
      .split("")
      .reduce((acc, char) => acc + char.charCodeAt(0), 0);
    const multiplier = 0.35 + (bookingHash % 45) / 100; // Between 0.35 and 0.8
    const newTotal = Math.round(baseBookingsData.total * multiplier);

    const segmentMultipliers = [
      0.8 + (bookingHash % 15) / 100, // approved: 0.8-0.95
      0.4 + (bookingHash % 30) / 100, // rejected: 0.4-0.7
      0.5 + (bookingHash % 25) / 100, // pending: 0.5-0.75
    ];

    const newSegments = baseBookingsData.segments.map(
      (seg: any, idx: number) => {
        const segMultiplier = segmentMultipliers[idx] || multiplier;
        const newPercentage = seg.percentage * segMultiplier;
        return {
          ...seg,
          percentage: newPercentage,
        };
      }
    );

    // Normalize percentages to total 100% (make full circle)
    const totalPercentage = newSegments.reduce(
      (sum: number, seg: any) => sum + seg.percentage,
      0
    );
    const normalizedSegments = newSegments.map((seg: any) => ({
      ...seg,
      percentage: (seg.percentage / totalPercentage) * 100,
    }));

    // Recalculate rotations based on normalized percentages
    let currentRotation = -90;
    const adjustedSegments = normalizedSegments.map((seg: any) => {
      const segmentWithRotation = {
        ...seg,
        rotation: currentRotation,
      };
      currentRotation += seg.percentage * 3.6; // 360 degrees / 100 percentage
      return segmentWithRotation;
    });

    // Calculate new center value based on the largest segment
    const maxSegment = adjustedSegments.reduce((max: any, seg: any) =>
      seg.percentage > max.percentage ? seg : max
    );
    const newCenterValue = `${Math.round(maxSegment.percentage)}%`;

    bookingsData = {
      total: newTotal,
      centerValue: newCenterValue,
      segments: adjustedSegments,
    };
  }

  return [
    {
      id: 1,
      title: "Bookings",
      total: bookingsData.total,
      centerValue: bookingsData.centerValue,
      segments: bookingsData.segments,
      period: bookingsPeriod.value,
    },
    {
      id: 2,
      title: "Building Mngm.",
      total: pieChartDataByPeriod[buildingPeriod.value].building.total,
      centerValue:
        pieChartDataByPeriod[buildingPeriod.value].building.centerValue,
      segments: pieChartDataByPeriod[buildingPeriod.value].building.segments,
      period: buildingPeriod.value,
    },
    {
      id: 3,
      title: "Work Orders",
      total: pieChartDataByPeriod[workOrdersPeriod.value].workOrders.total,
      centerValue:
        pieChartDataByPeriod[workOrdersPeriod.value].workOrders.centerValue,
      segments:
        pieChartDataByPeriod[workOrdersPeriod.value].workOrders.segments,
      period: workOrdersPeriod.value,
    },
  ];
});

// Function to fetch feedback data based on selected service
const fetchFeedbackData = async () => {
  if (!selectedService.value) {
    // Reset to base data when no service selected
    return;
  }
};

// Watch for service selection changes
watch(selectedService, () => {
  fetchFeedbackData();
});

// Fetch buildings/facilities on mount
onMounted(async () => {
  try {
    // Fetch buildings/facilities for bookings dropdown
    // Using buildings as facilities - you can adjust to use actual facilities API
    const buildingsResponse = await getAllBuildings({
      limit: 100,
      status: "active", // Only show active buildings
    });
    if (buildingsResponse && buildingsResponse.items) {
      bookingsList.value = buildingsResponse.items.map((building: any) => ({
        _id: building._id,
        name: building.name || building.block || `Building ${building._id}`,
      }));
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
});

// Base Facility Bookings Data
const baseFacilityBookings = [
  {
    id: 1,
    label: "Approved Bookings",
    value: 34,
    icon: "mdi-calendar-check",
    iconColor: "success",
  },
  {
    id: 2,
    label: "Pending Bookings",
    value: 97,
    icon: "mdi-calendar-clock",
    iconColor: "warning",
  },
  {
    id: 3,
    label: "Cancelled Bookings",
    value: 28,
    icon: "mdi-calendar-remove",
    iconColor: "error",
  },
  {
    id: 4,
    label: "Rejected Bookings",
    value: 27,
    icon: "mdi-calendar-remove",
    iconColor: "error",
  },
];

// Computed Facility Bookings - changes based on selected facility
const facilityBookings = computed(() => {
  // If no facility is selected, return base data
  if (!selectedBooking.value) {
    return baseFacilityBookings.map((booking) => ({
      ...booking,
      value: booking.value.toString(),
    }));
  }

  // If a facility is selected, multiply values
  const bookingHash = selectedBooking.value
    .split("")
    .reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const multiplier = 0.35 + (bookingHash % 45) / 100; // Between 0.35 and 0.8

  return baseFacilityBookings.map((booking) => ({
    ...booking,
    value: Math.round(booking.value * multiplier).toString(),
  }));
});
</script>

<style scoped>
.dashboard-container {
  max-width: 100%;
  background-color: #f5f5f5;
}

.card-hover {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.card-hover:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1) !important;
}

.chart-container {
  min-height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.h-100 {
  height: 100%;
}

.w-100 {
  width: 100%;
}

.position-relative {
  position: relative;
}

.position-absolute {
  position: absolute;
}

/* Responsive text sizing */
@media (max-width: 600px) {
  .dashboard-container {
    padding: 12px !important;
  }

  .chart-container {
    min-height: 250px;
    padding-bottom: 10px;
  }

  .chart-container svg {
    min-width: 700px !important;
  }
}

@media (min-width: 600px) and (max-width: 960px) {
  .chart-container {
    min-height: 260px;
  }

  .chart-container svg {
    min-width: 800px !important;
  }
}

@media (min-width: 960px) {
  .chart-container {
    min-height: 300px;
  }

  .chart-container svg {
    min-width: auto !important;
  }
}

/* SVG Animations */
svg {
  max-width: 100%;
  height: auto;
}

svg circle {
  transition: all 0.5s ease;
}

svg polyline,
svg rect {
  animation: fadeIn 1s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.3;
  }
}

/* Card styling improvements */
.v-card {
  border-radius: 12px !important;
  overflow: hidden;
}

.v-avatar {
  border-radius: 12px !important;
}

.avatar-custom {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

/* Better chip styling */
.v-chip {
  font-weight: 600;
}

/* Select dropdown styling */
.v-select {
  border-radius: 8px;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.legend-box {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.donut-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.donut-segment {
  transition: opacity 0.2s ease;
}

.donut-segment:hover {
  opacity: 0.8;
}
</style>
