<template>
  <div class="metric-card furnizori-balance-card">
    <!-- Main value section -->
    <div class="value-section">
      <div class="metric-label">Furnizori</div>
      <div class="metric-value" :class="getBalanceClass(total)">
        {{ formatCurrency(total) }}
      </div>
    </div>
    <div
      class="value-trend trend-indicator"
      :class="getTrendClass(trend)"
      v-if="trend"
    >
      <span class="trend-icon">{{ getTrendIcon(trend) }}</span>
      <span class="trend-value">{{ Math.round(Math.abs(trend.value)) }}%</span>
    </div>

    <!-- Sparkline chart -->
    <div class="metric-sparkline" v-if="hasSparklineData">
      <div class="sparkline-chart">
        <canvas ref="chartCanvas" class="sparkline-canvas"></canvas>
      </div>
    </div>

    <!-- Breakdown section -->
    <div class="breakdown-section" v-if="breakdown">
      <!-- În termen -->
      <div class="breakdown-item">
        <span class="breakdown-label">În termen</span>
        <span class="breakdown-value">{{
          formatCurrency(breakdown.in_termen?.total || 0)
        }}</span>
      </div>

      <!-- Restant cu sub-perioade -->
      <div class="breakdown-group">
        <div class="breakdown-header" @click="toggleRestantExpanded">
          <div class="breakdown-header-left">
            <i
              class="pi pi-chevron-right breakdown-toggle"
              :class="{ expanded: isRestantExpanded }"
            ></i>
            <span class="breakdown-label">Restant</span>
          </div>
          <span class="breakdown-value">{{
            formatCurrency(breakdown.restant?.total || 0)
          }}</span>
        </div>

        <!-- Perioade restante -->
        <div v-show="isRestantExpanded" class="breakdown-subitems slide-down">
          <div
            class="breakdown-subitem"
            v-for="(value, key) in breakdown.restant?.perioade"
            :key="key"
          >
            <span class="breakdown-sublabel">{{ formatPeriodLabel(key) }}</span>
            <span class="breakdown-subvalue">{{ formatCurrency(value) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

Chart.register(...registerables);

const props = defineProps({
  total: {
    type: Number,
    required: true,
  },
  trend: {
    type: Object,
    default: null,
  },
  sparklineData: {
    type: Array,
    default: () => [],
  },
  previousSparklineData: {
    type: Array,
    default: () => [],
  },
  sparklineLabels: {
    type: Array,
    default: () => [],
  },
  previousSparklineLabels: {
    type: Array,
    default: () => [],
  },
  breakdown: {
    type: Object,
    default: null,
  },
});

// Refs
const chartCanvas = ref(null);
let chartInstance = null;
const isRestantExpanded = ref(false);

// Toggle functions
const toggleRestantExpanded = () => {
  isRestantExpanded.value = !isRestantExpanded.value;
};

// Format currency
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));
};

// Format period label
const formatPeriodLabel = (key) => {
  const labelMap = {
    "7_zile": "7 zile",
    "14_zile": "14 zile",
    "30_zile": "30 zile",
    "60_zile": "60 zile",
    "90_zile": "90 zile",
    peste_90_zile: "Peste 90 zile",
  };
  return labelMap[key] || key;
};

// Balance class
const getBalanceClass = (amount) => {
  if (!amount && amount !== 0) return "neutral";
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  return numAmount > 0 ? "positive" : numAmount < 0 ? "negative" : "neutral";
};

// Trend class
const getTrendClass = (trend) => {
  if (!trend) return "";
  return {
    "trend-up": trend.direction === "up",
    "trend-down": trend.direction === "down",
    "trend-neutral": trend.direction === "neutral",
  };
};

// Trend icon
const getTrendIcon = (trend) => {
  if (!trend) return "";
  switch (trend.direction) {
    case "up":
      return "▲";
    case "down":
      return "▼";
    case "neutral":
      return "▶";
    default:
      return "";
  }
};

// Check if sparkline data exists
const hasSparklineData = computed(() => {
  return props.sparklineData && props.sparklineData.length > 0;
});

// Initialize chart
const initializeChart = async () => {
  if (!chartCanvas.value || !hasSparklineData.value) {
    return;
  }

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

  await nextTick();

  // Double-check canvas is still available after nextTick
  if (!chartCanvas.value) {
    console.warn('[FurnizoriBalanceCard] Canvas ref not available after nextTick');
    return;
  }

  const ctx = chartCanvas.value.getContext("2d");

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

  // Calculate limits including both datasets
  const allDataPoints = [...props.sparklineData];
  if (props.previousSparklineData && props.previousSparklineData.length > 0) {
    allDataPoints.push(...props.previousSparklineData);
  }
  const dataMin = Math.min(...allDataPoints);
  const dataMax = Math.max(...allDataPoints);
  const dataRange = dataMax - dataMin;
  const dataMean =
    allDataPoints.reduce((sum, val) => sum + val, 0) / allDataPoints.length;

  // CORECT: Forțăm range minim SIMETRIC, apoi adăugăm padding
  const minVisibleRange = dataMean * 0.25; // 25% din medie = range minim vizibil
  const center = (dataMin + dataMax) / 2;
  const targetRange = Math.max(dataRange, minVisibleRange);

  // Calculează limite simetric față de centru
  let calculatedMin = center - targetRange / 2;
  let calculatedMax = center + targetRange / 2;

  // Adaugă padding PESTE range-ul asigurat (nu înăuntru!)
  const paddingAmount = targetRange * 0.1; // 10% padding suplimentar

  // Aplică limitele finale (nu permite negative dacă toate datele sunt pozitive)
  const allPositive = dataMin >= 0;
  const yMin = allPositive
    ? Math.max(0, calculatedMin - paddingAmount)
    : calculatedMin - paddingAmount;
  const yMax = calculatedMax + paddingAmount;

  // Prepare datasets
  const datasets = [
    {
      label: "Furnizori (curent)",
      data: props.sparklineData,
      borderColor: "#ef4444",
      backgroundColor: "rgba(239, 68, 68, 0.1)",
      borderWidth: 2,
      fill: true,
      tension: 0.4,
      pointRadius: 0,
      pointHoverRadius: 4,
      pointHoverBackgroundColor: "#ef4444",
      pointHoverBorderColor: "#ffffff",
      pointHoverBorderWidth: 2,
    },
  ];

  // Add previous year dataset if available
  if (props.previousSparklineData && props.previousSparklineData.length > 0) {
    datasets.push({
      label: "Furnizori (anul precedent)",
      data: props.previousSparklineData,
      borderColor: "rgba(239, 68, 68, 0.4)",
      backgroundColor: "rgba(239, 68, 68, 0.05)",
      borderWidth: 2,
      borderDash: [5, 5],
      fill: false,
      tension: 0.4,
      pointRadius: 0,
      pointHoverRadius: 4,
      pointHoverBackgroundColor: "rgba(239, 68, 68, 0.6)",
      pointHoverBorderColor: "#ffffff",
      pointHoverBorderWidth: 2,
    });
  }

  chartInstance = new Chart(ctx, {
    type: "line",
    data: {
      labels: labels,
      datasets: datasets,
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        intersect: false,
        mode: "index",
      },
      plugins: {
        legend: {
          display: true,
          position: "top",
          align: "end",
          labels: {
            boxWidth: 12,
            boxHeight: 12,
            padding: 8,
            font: {
              size: 10,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            color: "rgba(107, 114, 128, 0.8)",
            usePointStyle: true,
          },
        },
        tooltip: {
          backgroundColor: "rgba(0, 0, 0, 0.8)",
          titleColor: "#ffffff",
          bodyColor: "#ffffff",
          borderColor: "rgba(255, 255, 255, 0.2)",
          borderWidth: 1,
          cornerRadius: 6,
          displayColors: true,
          callbacks: {
            title: (context) => context[0].label || "",
            label: (context) => {
              const value = context.parsed.y;
              const label = context.dataset.label || "";
              const formattedValue = new Intl.NumberFormat("ro-RO", {
                style: "currency",
                currency: "RON",
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
              }).format(value);
              return `${label}: ${formattedValue}`;
            },
          },
        },
      },
      scales: {
        x: {
          display: true,
          grid: {
            display: false,
            drawBorder: false,
          },
          ticks: {
            color: "rgba(107, 114, 128, 0.7)",
            font: {
              size: 10,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            maxRotation: 45,
            minRotation: 45,
            maxTicksLimit: 6,
          },
          border: {
            display: false,
          },
        },
        y: {
          display: true,
          min: yMin,
          max: yMax,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          ticks: {
            color: "#ef4444",
            font: {
              size: 11,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            maxTicksLimit: 3,
            callback: function (value) {
              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,
          },
        },
      },
    },
  });
};

// Watch for data changes
watch(
  () => [
    props.sparklineData,
    props.previousSparklineData,
    props.sparklineLabels,
    props.previousSparklineLabels,
  ],
  async () => {
    await initializeChart();
  },
  { deep: true },
);

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

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

<style scoped>
/* Component-specific: FurnizoriBalanceCard layout and breakdown */

/* Override min-height for balance card */
.furnizori-balance-card {
  min-height: 320px;
}

/* Value section: horizontal layout */
.value-section {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

/* Color classes for positive/negative/neutral (component-specific logic) */
.positive {
  color: var(--color-success);
}

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

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

/* Sparkline chart dimensions */
.sparkline-chart {
  width: 100%;
  height: 150px;
  position: relative;
}

/* Chart.js canvas sizing (required for proper rendering) */
.sparkline-canvas {
  width: 100% !important;
  height: 100% !important;
  display: block;
}

/* Responsive */
@media (max-width: 768px) {
  .furnizori-balance-card {
    min-height: 280px;
  }

  .sparkline-chart {
    height: 130px;
  }
}

@media (max-width: 480px) {
  .sparkline-chart {
    height: 150px;
  }
}
</style>
