<template>
  <div class="metric-card treasury-dual-card">
    <!-- Treasury items - Casa și Bancă stacked vertical cu expand individual -->
    <div class="treasury-items">
      <!-- Casa -->
      <div class="treasury-group" v-if="casaItems.length > 0 || casaTotal !== 0">
        <div class="treasury-header" @click="toggleCasaExpanded">
          <div class="treasury-header-left">
            <i
              class="pi pi-chevron-right treasury-toggle"
              :class="{ expanded: isCasaExpanded }"
            ></i>
            <span class="treasury-label">Casa</span>
          </div>
          <span class="treasury-value" :class="casaTotal >= 0 ? 'text-success' : 'text-danger'">{{ formatCurrency(casaTotal) }}</span>
        </div>

        <!-- Casa Sub-items -->
        <div v-show="isCasaExpanded && casaItems.length > 0" class="treasury-subitems slide-down">
          <div
            v-for="(item, idx) in casaItems"
            :key="idx"
            class="treasury-subitem"
          >
            <span class="treasury-sublabel">
              {{ item.nume || `Cont ${item.cont}` }}
              <span v-if="item.cont" class="treasury-cont">({{ item.cont }})</span>
            </span>
            <span class="treasury-subvalue" :class="{ 'text-danger': item.sold < 0 }">{{ formatCurrency(item.sold) }}</span>
          </div>
        </div>
      </div>

      <!-- Bancă -->
      <div class="treasury-group" v-if="bancaItems.length > 0 || bancaTotal !== 0">
        <div class="treasury-header" @click="toggleBancaExpanded">
          <div class="treasury-header-left">
            <i
              class="pi pi-chevron-right treasury-toggle"
              :class="{ expanded: isBancaExpanded }"
            ></i>
            <span class="treasury-label">Bancă</span>
          </div>
          <span class="treasury-value" :class="bancaTotal >= 0 ? 'text-primary' : 'text-danger'">{{ formatCurrency(bancaTotal) }}</span>
        </div>

        <!-- Bancă Sub-items -->
        <div v-show="isBancaExpanded && bancaItems.length > 0" class="treasury-subitems slide-down">
          <div
            v-for="(item, idx) in bancaItems"
            :key="idx"
            class="treasury-subitem"
          >
            <span class="treasury-sublabel">
              {{ item.nume || `Cont ${item.cont}` }}
              <span v-if="item.cont" class="treasury-cont">({{ item.cont }})</span>
            </span>
            <span class="treasury-subvalue" :class="{ 'text-danger': item.sold < 0 }">{{ formatCurrency(item.sold) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Charts toggle header -->
    <div
      v-if="hasSparklineData"
      class="charts-toggle-header"
      @click="toggleChartsExpanded"
    >
      <span>Grafice evoluție</span>
      <i
        class="pi pi-chevron-right"
        :class="{ expanded: chartsExpanded }"
      ></i>
    </div>

    <!-- Dual sparkline charts - stacked vertical (at the end) -->
    <div v-show="chartsExpanded" class="charts-content sparkline-dual-container">
      <!-- Grafic Casa -->
      <div class="sparkline-wrapper">
        <div class="sparkline-title text-success">Casa</div>
        <div class="sparkline-chart">
          <canvas ref="casaCanvas" class="sparkline-canvas"></canvas>
        </div>
      </div>

      <!-- Grafic Bancă -->
      <div class="sparkline-wrapper">
        <div class="sparkline-title text-primary">Bancă</div>
        <div class="sparkline-chart">
          <canvas ref="bancaCanvas" class="sparkline-canvas"></canvas>
        </div>
      </div>
    </div>

    <!-- Cache Footer -->
    <CacheFooter
      :cache-hit="cacheInfo?.hit"
      :response-time-ms="cacheInfo?.time"
      :cache-source="cacheInfo?.source"
    />
  </div>
</template>

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

Chart.register(...registerables);

const props = defineProps({
  casaTotal: {
    type: Number,
    default: 0,
  },
  bancaTotal: {
    type: Number,
    default: 0,
  },
  casaItems: {
    type: Array,
    default: () => [],
  },
  bancaItems: {
    type: Array,
    default: () => [],
  },
  casaSparklineData: {
    type: Array,
    default: () => [],
  },
  bancaSparklineData: {
    type: Array,
    default: () => [],
  },
  casaPreviousSparklineData: {
    type: Array,
    default: () => [],
  },
  bancaPreviousSparklineData: {
    type: Array,
    default: () => [],
  },
  sparklineLabels: {
    type: Array,
    default: () => [],
  },
  previousSparklineLabels: {
    type: Array,
    default: () => [],
  },
  trend: {
    type: Object,
    default: null,
  },
  cacheInfo: {
    type: Object,
    default: () => ({ hit: false, time: 0, source: null }),
  },
});

// Refs pentru 2 canvas-uri separate
const casaCanvas = ref(null);
const bancaCanvas = ref(null);
let casaChartInstance = null;
let bancaChartInstance = null;
const isCasaExpanded = ref(false);
const isBancaExpanded = ref(false);
const chartsExpanded = ref(false);

// Toggle functions
const toggleCasaExpanded = () => {
  isCasaExpanded.value = !isCasaExpanded.value;
};

const toggleBancaExpanded = () => {
  isBancaExpanded.value = !isBancaExpanded.value;
};

const toggleChartsExpanded = () => {
  chartsExpanded.value = !chartsExpanded.value;
};

// Format amount (without RON suffix)
const formatCurrency = (amount) => {
  if (!amount && amount !== 0) return "0";
  return new Intl.NumberFormat("ro-RO", {
    style: "decimal",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount);
};

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

// Initialize Casa chart
const initializeCasaChart = async () => {
  if (!casaCanvas.value || props.casaSparklineData.length === 0) {
    return;
  }

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

  await nextTick();

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

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

  // Prepare datasets
  const datasets = [
    {
      label: "Casa (curent)",
      data: props.casaSparklineData,
      borderColor: "#10b981",
      backgroundColor: "rgba(16, 185, 129, 0.1)",
      borderWidth: 2,
      fill: true,
      tension: 0.4,
      pointRadius: 0,
      pointHoverRadius: 4,
      pointHoverBackgroundColor: "#10b981",
      pointHoverBorderColor: "#ffffff",
      pointHoverBorderWidth: 2,
    },
  ];

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

  // Calculate limits including both datasets
  const allDataPoints = [...props.casaSparklineData];
  if (
    props.casaPreviousSparklineData &&
    props.casaPreviousSparklineData.length > 0
  ) {
    allDataPoints.push(...props.casaPreviousSparklineData);
  }
  const dataMin = Math.min(...allDataPoints);
  const dataMax = Math.max(...allDataPoints);
  const dataRange = dataMax - dataMin;
  const dataPadding = dataRange * 0.05;

  casaChartInstance = new Chart(ctx, {
    type: "line",
    data: {
      labels: labels,
      datasets: datasets,
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        intersect: false,
        mode: "index",
      },
      plugins: {
        legend: {
          display: datasets.length > 1,
          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.9)",
            usePointStyle: true,
            pointStyle: "line",
          },
        },
        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: "decimal",
                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: dataMin - dataPadding,
          max: dataMax + dataPadding,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          ticks: {
            color: "#10b981",
            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,
          },
        },
      },
    },
  });
};

// Initialize Bancă chart
const initializeBancaChart = async () => {
  if (!bancaCanvas.value || props.bancaSparklineData.length === 0) {
    return;
  }

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

  await nextTick();

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

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

  // Prepare datasets
  const datasets = [
    {
      label: "Bancă (curent)",
      data: props.bancaSparklineData,
      borderColor: "#3b82f6",
      backgroundColor: "rgba(59, 130, 246, 0.1)",
      borderWidth: 2,
      fill: true,
      tension: 0.4,
      pointRadius: 0,
      pointHoverRadius: 4,
      pointHoverBackgroundColor: "#3b82f6",
      pointHoverBorderColor: "#ffffff",
      pointHoverBorderWidth: 2,
    },
  ];

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

  // Calculate limits including both datasets
  const allDataPoints = [...props.bancaSparklineData];
  if (
    props.bancaPreviousSparklineData &&
    props.bancaPreviousSparklineData.length > 0
  ) {
    allDataPoints.push(...props.bancaPreviousSparklineData);
  }
  const dataMin = Math.min(...allDataPoints);
  const dataMax = Math.max(...allDataPoints);
  const dataRange = dataMax - dataMin;
  const dataPadding = dataRange * 0.05;

  bancaChartInstance = new Chart(ctx, {
    type: "line",
    data: {
      labels: labels,
      datasets: datasets,
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        intersect: false,
        mode: "index",
      },
      plugins: {
        legend: {
          display: datasets.length > 1,
          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.9)",
            usePointStyle: true,
            pointStyle: "line",
          },
        },
        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: "decimal",
                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: dataMin - dataPadding,
          max: dataMax + dataPadding,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          ticks: {
            color: "#3b82f6",
            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.casaSparklineData,
    props.bancaSparklineData,
    props.sparklineLabels,
    props.casaPreviousSparklineData,
    props.bancaPreviousSparklineData,
    props.previousSparklineLabels,
  ],
  async () => {
    await Promise.all([initializeCasaChart(), initializeBancaChart()]);
  },
  { deep: true },
);

// Lifecycle hooks
onMounted(async () => {
  await Promise.all([initializeCasaChart(), initializeBancaChart()]);
});

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

<style scoped>
/* Component-specific: TreasuryDualCard (Casa | Bancă) */

/* Override min-height for treasury card */
.treasury-dual-card {
  min-height: 320px;
}

/* Treasury items container - stacked vertical */
.treasury-items {
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
}

/* Treasury group (Casa sau Bancă) */
.treasury-group {
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  overflow: hidden;
}

/* Treasury header - clickable */
.treasury-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-md);
  cursor: pointer;
  user-select: none;
  background: var(--surface-ground);
  transition: background-color var(--transition-fast);
}

.treasury-header:hover {
  background: var(--surface-hover);
}

.treasury-header-left {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

.treasury-toggle {
  color: var(--text-color-secondary);
  font-size: var(--text-xs);
  transition: transform var(--transition-fast);
}

.treasury-toggle.expanded {
  transform: rotate(90deg);
}

.treasury-label {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-color);
}

.treasury-value {
  font-size: var(--text-sm);
  font-weight: var(--font-bold);
  font-family: var(--font-mono, monospace);
}

/* Treasury sub-items */
.treasury-subitems {
  padding: var(--space-sm) var(--space-md) var(--space-md);
  background: var(--surface-card);
  border-top: 1px solid var(--surface-border);
}

.treasury-subitem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-xs) 0;
}

.treasury-sublabel {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
}

.treasury-cont {
  font-size: var(--text-xs);
  opacity: 0.7;
  margin-left: var(--space-xs);
}

.treasury-subvalue {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  font-family: var(--font-mono, monospace);
  color: var(--text-color);
}

/* Dual sparkline container (unique to this card) */
.sparkline-dual-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin: 0.5rem 0;
}

.sparkline-wrapper {
  width: 100%;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: 4px;
  padding: 0.5rem;
}

.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;
}

/* Charts toggle header */
.charts-toggle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-sm) var(--space-md);
  margin-top: var(--space-sm);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
  transition: background-color var(--transition-fast);
}

.charts-toggle-header:hover {
  background: var(--surface-border);
}

.charts-toggle-header i {
  transition: transform var(--transition-fast);
}

.charts-toggle-header i.expanded {
  transform: rotate(90deg);
}

/* Charts content wrapper */
.charts-content {
  margin-top: var(--space-sm);
}

/* Responsive: Stack vertically on mobile */
@media (max-width: 768px) {
  .treasury-dual-card {
    min-height: 280px;
  }

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

@media (max-width: 480px) {
  .treasury-dual-card {
    min-height: 240px;
  }

  .treasury-header {
    padding: var(--space-sm);
  }

  .treasury-value {
    font-size: var(--text-base);
  }

  .sparkline-chart {
    height: 120px;
  }

  .sparkline-wrapper {
    padding: 0;
    border: none;
  }
}
</style>
