<template>
  <div class="metric-card">
    <!-- Header with icon and title -->
    <div class="metric-header">
      <span class="metric-icon bg-primary-light text-primary">{{ icon }}</span>
      <span class="metric-label">{{ title }}</span>
    </div>

    <!-- Main value display -->
    <div class="metric-value" :class="valueClass">
      {{ formatCurrency(value) }}
    </div>

    <!-- Trend indicator -->
    <div class="trend-indicator" :class="trendClass" v-if="trend">
      <span class="trend-icon">{{ trendIcon }}</span>
      <span class="trend-value"
        >{{ Math.round(Math.abs(trend.value), 2) }}%</span
      >
    </div>

    <!-- Sparkline mini-chart - STACKED BELOW (Best Practice) -->
    <div
      class="sparkline-container"
      v-if="sparklineData && sparklineData.length > 0"
    >
      <canvas ref="sparklineCanvas" class="sparkline-canvas"></canvas>
    </div>

    <!-- Breakdown display section - Suport ierarhic -->
    <div class="metric-breakdown" v-if="breakdown">
      <div
        v-for="(value, key) in breakdown"
        :key="key"
        class="breakdown-section"
      >
        <!-- Valoare simplă (backward compatible) -->
        <div v-if="!isHierarchical(value)" class="breakdown-item">
          <span class="breakdown-label">{{ formatBreakdownLabel(key) }}:</span>
          <span class="breakdown-value">{{ formatCurrency(value) }}</span>
        </div>

        <!-- Valoare ierarhică (cu sub-items) -->
        <div v-else class="breakdown-group">
          <div class="breakdown-header" @click="() => toggleExpanded(key)">
            <div class="breakdown-header-left">
              <i
                class="pi pi-chevron-right breakdown-toggle"
                :class="{ expanded: isItemExpanded(key) }"
              ></i>
              <span class="breakdown-label"
                >{{ formatBreakdownLabel(key) }}:</span
              >
            </div>
            <span class="breakdown-value">{{
              formatCurrency(value.total)
            }}</span>
          </div>

          <!-- Sub-items (collapsible) -->
          <div
            v-if="value.items && value.items.length > 0"
            v-show="isItemExpanded(key)"
            class="breakdown-subitems slide-down"
          >
            <div
              v-for="(item, idx) in value.items"
              :key="idx"
              class="breakdown-subitem"
            >
              <span class="breakdown-sublabel">
                {{ item.nume }}
                <span v-if="item.cont" class="breakdown-cont"
                  >({{ item.cont }})</span
                >
              </span>
              <span class="breakdown-subvalue">{{
                formatCurrency(item.sold)
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  computed,
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from "vue";
import { Chart, registerables } from "chart.js";

// Register Chart.js components
Chart.register(...registerables);

// Props definition with validation
const props = defineProps({
  icon: {
    type: String,
    required: true,
    validator: (value) => value.length > 0,
  },
  title: {
    type: String,
    required: true,
    validator: (value) => value.length > 0,
  },
  value: {
    type: Number,
    required: true,
  },
  trend: {
    type: Object,
    default: null,
    validator: (value) => {
      if (value === null) return true;
      return (
        typeof value.value === "number" &&
        ["up", "down", "neutral"].includes(value.direction)
      );
    },
  },
  sparklineData: {
    type: Array,
    default: () => [],
    validator: (value) => {
      return value.every((item) => typeof item === "number");
    },
  },
  sparklineLabels: {
    type: Array,
    default: () => [],
  },
  breakdown: {
    type: Object,
    required: false,
    default: null,
  },
});

// Refs
const sparklineCanvas = ref(null);
let chartInstance = null;
const expandedStates = ref({});

// Toggle breakdown expansion for a specific key
const toggleExpanded = (key) => {
  expandedStates.value[key] = !expandedStates.value[key];
};

// Check if a specific breakdown item is expanded
const isItemExpanded = (key) => {
  return !!expandedStates.value[key];
};

// Format currency value
const formatCurrency = (amount) => {
  if (!amount && amount !== 0) return "0 RON";

  return new Intl.NumberFormat("ro-RO", {
    style: "currency",
    currency: "RON",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  })
    .format(Math.abs(amount))
    .replace("RON", "RON");
};

// Format breakdown label
const formatBreakdownLabel = (key) => {
  const labelMap = {
    casa: "Casă",
    banca: "Bancă",
    clienti: "Clienți",
    furnizori: "Furnizori",
    clienti_in_termen: "Clienți în termen",
    clienti_restanti: "Clienți restanți",
    furnizori_termen: "Furnizori în termen",
    furnizori_scadent: "Furnizori scadenți",
    numerar: "Numerar",
    cont: "Cont",
    depozit: "Depozit",
    credit: "Credit",
    debit: "Debit",
    sold: "Sold",
    total: "Total",
  };

  return (
    labelMap[key.toLowerCase()] || key.charAt(0).toUpperCase() + key.slice(1)
  );
};

// Check if value is hierarchical (has total and items)
const isHierarchical = (value) => {
  return (
    value !== null &&
    typeof value === "object" &&
    "total" in value &&
    "items" in value
  );
};

// Computed properties for styling
const iconClass = computed(() => {
  return `icon-${props.title.toLowerCase().replace(/\s+/g, "-")}`;
});

const valueClass = computed(() => {
  if (!props.value && props.value !== 0) return "";
  return props.value < 0 ? "negative" : "positive";
});

const trendClass = computed(() => {
  if (!props.trend) return "";

  return {
    "trend-up": props.trend.direction === "up",
    "trend-down": props.trend.direction === "down",
    "trend-neutral": props.trend.direction === "neutral",
  };
});

const trendIcon = computed(() => {
  if (!props.trend) return "";

  switch (props.trend.direction) {
    case "up":
      return "▲";
    case "down":
      return "▼";
    case "neutral":
      return "▶";
    default:
      return "";
  }
});

// Sparkline color based on trend
const sparklineColor = computed(() => {
  if (!props.trend) {
    return "#3b82f6"; // Primary blue
  }

  switch (props.trend.direction) {
    case "up":
      return "#10b981"; // Success green
    case "down":
      return "#ef4444"; // Danger red
    default:
      return "#3b82f6"; // Primary blue
  }
});

// Initialize Chart.js sparkline
const initializeSparkline = async () => {
  if (
    !sparklineCanvas.value ||
    !props.sparklineData ||
    props.sparklineData.length === 0
  ) {
    return;
  }

  // Destroy existing chart instance
  if (chartInstance) {
    chartInstance.destroy();
    chartInstance = null;
  }

  await nextTick();

  const ctx = sparklineCanvas.value.getContext("2d");
  const color = sparklineColor.value;

  // Generate labels: use provided labels or generate generic ones
  const labels =
    props.sparklineLabels.length > 0
      ? props.sparklineLabels
      : props.sparklineData.map((_, i) => `L${i + 1}`);

  chartInstance = new Chart(ctx, {
    type: "line",
    data: {
      labels: labels,
      datasets: [
        {
          data: props.sparklineData,
          borderColor: color,
          backgroundColor: `${color}20`, // 20 = 12.5% opacity in hex
          borderWidth: 2,
          fill: true,
          tension: 0.4,
          pointRadius: 0, // Hide points by default
          pointHoverRadius: 4,
          pointHoverBackgroundColor: color,
          pointHoverBorderColor: "#ffffff",
          pointHoverBorderWidth: 2,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        intersect: false,
        mode: "index",
      },
      plugins: {
        legend: {
          display: false,
        },
        tooltip: {
          backgroundColor: "rgba(0, 0, 0, 0.8)",
          titleColor: "#ffffff",
          bodyColor: "#ffffff",
          borderColor: "rgba(255, 255, 255, 0.2)",
          borderWidth: 1,
          cornerRadius: 6,
          displayColors: false,
          callbacks: {
            title: (context) => {
              // Show period label in tooltip
              return context[0].label || "";
            },
            label: (context) => {
              const value = context.parsed.y;
              return new Intl.NumberFormat("ro-RO", {
                style: "currency",
                currency: "RON",
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
              }).format(value);
            },
          },
        },
      },
      scales: {
        x: {
          display: true,
          grid: {
            display: false,
            drawBorder: false,
          },
          ticks: {
            color: "rgba(107, 114, 128, 0.7)",
            font: {
              size: 9,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            maxRotation: 45,
            minRotation: 45,
            maxTicksLimit: 6,
          },
          border: {
            display: false,
          },
        },
        y: {
          display: true,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          ticks: {
            color: "rgba(107, 114, 128, 0.7)",
            font: {
              size: 9,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            maxTicksLimit: 4,
            callback: function (value) {
              // Format as compact currency
              if (value >= 1000000) {
                return (value / 1000000).toFixed(1) + "M";
              } else if (value >= 1000) {
                return (value / 1000).toFixed(0) + "k";
              }
              return value.toFixed(0);
            },
          },
          border: {
            display: false,
          },
        },
      },
      elements: {
        line: {
          borderCapStyle: "round",
          borderJoinStyle: "round",
        },
      },
    },
  });
};

// Watch for data changes
watch(
  () => props.sparklineData,
  async () => {
    await initializeSparkline();
  },
  { deep: true },
);

watch(
  () => props.sparklineLabels,
  async () => {
    await initializeSparkline();
  },
  { deep: true },
);

watch(
  () => props.trend,
  async () => {
    await initializeSparkline();
  },
  { deep: true },
);

// Lifecycle hooks
onMounted(async () => {
  await initializeSparkline();
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.destroy();
    chartInstance = null;
  }
});
</script>

<style scoped>
/* Component-specific styles only - Base patterns now in global CSS */

/* Trend indicator styles - Component specific */
.trend-indicator {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.trend-up {
  color: var(--color-success);
}

.trend-down {
  color: var(--color-error);
}

.trend-neutral {
  color: var(--color-text-secondary);
}

.trend-icon {
  font-size: 0.75rem;
}

.trend-value {
  font-weight: var(--font-semibold);
}

/* Value styling - Component specific colors */
.metric-value.positive {
  color: var(--color-success);
}

.metric-value.negative {
  color: var(--color-error);
}

/* Breakdown section - Component specific layout */
.metric-breakdown {
  margin-top: var(--space-lg);
  padding-top: var(--space-md);
  border-top: 1px solid var(--color-border);
}

.breakdown-section {
  margin-bottom: var(--space-sm);
}

.breakdown-section:last-child {
  margin-bottom: 0;
}

.breakdown-group {
  margin-bottom: var(--space-sm);
}

/* Breakdown item - Component specific styles */
.breakdown-item {
  margin-bottom: var(--space-xs);
}

.breakdown-item:last-child {
  margin-bottom: 0;
}

/* Breakdown cont label - Component specific */
.breakdown-cont {
  font-size: var(--text-sm);
  opacity: 0.7;
  margin-left: var(--space-xs);
}
</style>
