<template>
  <div class="performance-card card">
    <div class="card-header">
      <div class="header-content">
        <div class="header-title">
          <span class="card-icon">📊</span>
          <h3 class="card-title">Performanță & Cash Flow</h3>
        </div>
        <div class="period-selector">
          <select
            v-model="selectedPeriod"
            @change="handlePeriodChange"
            class="period-select"
            :disabled="isLoading"
          >
            <option value="7d">7 zile</option>
            <option value="1m">1 lună</option>
            <option value="3m">3 luni</option>
            <option value="6m">6 luni</option>
            <option value="ytd">YTD</option>
            <option value="12m">12 luni</option>
          </select>
          <i class="pi pi-chevron-down select-icon"></i>
        </div>
      </div>
    </div>

    <div class="card-body">
      <!-- Loading State -->
      <div v-if="isLoading" class="loading-state">
        <div class="loading-spinner"></div>
        <span class="loading-text">Se încarcă datele...</span>
      </div>

      <!-- Error State -->
      <div v-else-if="error" class="error-state">
        <i class="pi pi-exclamation-triangle error-icon"></i>
        <span class="error-text">{{ error }}</span>
        <button @click="retryLoad" class="retry-button">
          <i class="pi pi-refresh"></i>
          Reîncarcă
        </button>
      </div>

      <!-- Content -->
      <template v-else>
        <!-- Chart Container -->
        <div class="chart-container">
          <div class="chart-placeholder" v-if="!chartData?.labels?.length">
            <div class="placeholder-content">
              <i class="pi pi-chart-line placeholder-icon"></i>
              <span class="placeholder-text">Grafic încasări vs plăți</span>
              <small class="placeholder-subtitle"
                >Datele vor fi afișate aici</small
              >
            </div>
          </div>
          <div v-else class="chart-content">
            <div class="chart-legend">
              <div class="legend-item">
                <span class="legend-color income"></span>
                <span class="legend-label">Încasări</span>
                <span class="legend-value">{{
                  formatCurrency(totalIncome)
                }}</span>
              </div>
              <div class="legend-item">
                <span class="legend-color expenses"></span>
                <span class="legend-label">Plăți</span>
                <span class="legend-value">{{
                  formatCurrency(totalExpenses)
                }}</span>
              </div>
            </div>
            <div class="chart-canvas-container">
              <canvas
                ref="performanceChart"
                v-if="chartData?.labels?.length"
                width="400"
                height="200"
              ></canvas>
            </div>
          </div>
        </div>

        <!-- Performance Indicators -->
        <div class="indicators-section">
          <div class="indicators-grid">
            <div class="indicator-card">
              <div class="indicator-icon">💰</div>
              <div class="indicator-content">
                <div class="indicator-label">Rata încasare</div>
                <div
                  class="indicator-value"
                  :class="getRateClass(performanceData.rataIncasare)"
                >
                  {{ performanceData.rataIncasare || 0 }}%
                </div>
              </div>
            </div>

            <div class="indicator-card">
              <div class="indicator-icon">⏱️</div>
              <div class="indicator-content">
                <div class="indicator-label">Cash conversion</div>
                <div class="indicator-value">
                  {{ performanceData.cashConversion || 0 }} zile
                </div>
              </div>
            </div>

            <div class="indicator-card">
              <div class="indicator-icon">📈</div>
              <div class="indicator-content">
                <div class="indicator-label">Trend</div>
                <div
                  class="indicator-value"
                  :class="getTrendClass(performanceData.trend)"
                >
                  <i :class="getTrendIcon(performanceData.trend)"></i>
                  {{ getTrendText(performanceData.trend) }}
                </div>
              </div>
            </div>

            <div class="indicator-card">
              <div class="indicator-icon">💼</div>
              <div class="indicator-content">
                <div class="indicator-label">Capital lucru</div>
                <div
                  class="indicator-value"
                  :class="
                    getWorkingCapitalClass(performanceData.workingCapital)
                  "
                >
                  {{ formatCurrency(performanceData.workingCapital || 0) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from "vue";
import { Chart, registerables } from "chart.js";
import { useDashboardStore } from "@reports/stores/dashboard";

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

// Props
const props = defineProps({
  companyId: {
    type: [Number, String],
    required: true,
  },
});

// Emits
const emit = defineEmits(["periodChanged"]);

// State
const selectedPeriod = ref("7d");
const isLoading = ref(false);
const error = ref(null);
const performanceChart = ref(null);
let chartInstance = null;

// Store
const dashboardStore = useDashboardStore();

// Sample data (will be replaced with actual API data)
const performanceData = ref({
  rataIncasare: 85.2,
  cashConversion: 45,
  trend: "up",
  workingCapital: 125000,
});

const chartData = ref({
  labels: ["Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"],
  income: [12000, 15000, 8000, 22000, 18000, 14000, 16000],
  expenses: [8000, 12000, 15000, 16000, 14000, 11000, 13000],
});

// Computed
const totalIncome = computed(() => {
  return chartData.value.income?.reduce((sum, val) => sum + val, 0) || 0;
});

const totalExpenses = computed(() => {
  return chartData.value.expenses?.reduce((sum, val) => sum + val, 0) || 0;
});

const maxValue = computed(() => {
  const allValues = [
    ...(chartData.value.income || []),
    ...(chartData.value.expenses || []),
  ];
  return Math.max(...allValues, 0);
});

// Methods
const handlePeriodChange = () => {
  emit("periodChanged", selectedPeriod.value);
  loadPerformanceData();
};

const loadPerformanceData = async () => {
  if (!props.companyId) return;

  isLoading.value = true;
  error.value = null;

  try {
    // This will be replaced with actual API call
    // const result = await dashboardStore.loadPerformanceData(props.companyId, selectedPeriod.value)

    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // Mock data based on period
    const mockData = {
      "7d": {
        rataIncasare: 85.2,
        cashConversion: 45,
        trend: "up",
        workingCapital: 125000,
        chartData: {
          labels: ["Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"],
          income: [12000, 15000, 8000, 22000, 18000, 14000, 16000],
          expenses: [8000, 12000, 15000, 16000, 14000, 11000, 13000],
        },
      },
      "1m": {
        rataIncasare: 78.5,
        cashConversion: 52,
        trend: "stable",
        workingCapital: 89000,
        chartData: {
          labels: ["S1", "S2", "S3", "S4"],
          income: [45000, 52000, 38000, 48000],
          expenses: [42000, 47000, 51000, 45000],
        },
      },
      "3m": {
        rataIncasare: 82.1,
        cashConversion: 38,
        trend: "up",
        workingCapital: 156000,
        chartData: {
          labels: ["Ian", "Feb", "Mar"],
          income: [165000, 182000, 155000],
          expenses: [158000, 162000, 168000],
        },
      },
      "6m": {
        rataIncasare: 79.8,
        cashConversion: 41,
        trend: "down",
        workingCapital: 98000,
        chartData: {
          labels: ["Oct", "Noi", "Dec", "Ian", "Feb", "Mar"],
          income: [145000, 162000, 185000, 165000, 182000, 155000],
          expenses: [152000, 158000, 172000, 158000, 162000, 168000],
        },
      },
      ytd: {
        rataIncasare: 81.3,
        cashConversion: 43,
        trend: "stable",
        workingCapital: 142000,
        chartData: {
          labels: ["Q1", "Q2", "Q3"],
          income: [502000, 485000, 456000],
          expenses: [488000, 512000, 478000],
        },
      },
      "12m": {
        rataIncasare: 83.7,
        cashConversion: 39,
        trend: "up",
        workingCapital: 178000,
        chartData: {
          labels: ["T1", "T2", "T3", "T4"],
          income: [1456000, 1523000, 1387000, 1612000],
          expenses: [1423000, 1498000, 1456000, 1534000],
        },
      },
    };

    const data = mockData[selectedPeriod.value] || mockData["7d"];
    performanceData.value = data;
    chartData.value = data.chartData;

    // Initialize or update chart after data is loaded
    await nextTick();
    await updateChart();
  } catch (err) {
    console.error("Failed to load performance data:", err);
    error.value = "Nu s-au putut încărca datele de performanță";
  } finally {
    isLoading.value = false;
  }
};

const retryLoad = () => {
  loadPerformanceData();
};

const formatCurrency = (value) => {
  if (value === null || value === undefined) return "0 RON";
  return new Intl.NumberFormat("ro-RO", {
    style: "currency",
    currency: "RON",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
};

const initializeChart = async () => {
  if (!performanceChart.value || !chartData.value?.labels?.length) return;

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

  await nextTick();

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

  chartInstance = new Chart(ctx, {
    type: "line",
    data: {
      labels: chartData.value.labels,
      datasets: [
        {
          label: "Încasări",
          data: chartData.value.income,
          borderColor: "rgba(16, 185, 129, 1)", // var(--color-success)
          backgroundColor: "rgba(16, 185, 129, 0.1)",
          borderWidth: 2,
          fill: true,
          tension: 0.4,
          pointBackgroundColor: "rgba(16, 185, 129, 1)",
          pointBorderColor: "#ffffff",
          pointBorderWidth: 2,
          pointRadius: 4,
          pointHoverRadius: 6,
        },
        {
          label: "Plăți",
          data: chartData.value.expenses,
          borderColor: "rgba(239, 68, 68, 1)", // var(--color-error)
          backgroundColor: "rgba(239, 68, 68, 0.1)",
          borderWidth: 2,
          fill: true,
          tension: 0.4,
          pointBackgroundColor: "rgba(239, 68, 68, 1)",
          pointBorderColor: "#ffffff",
          pointBorderWidth: 2,
          pointRadius: 4,
          pointHoverRadius: 6,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        intersect: false,
        mode: "index",
      },
      plugins: {
        legend: {
          display: false, // We have our own custom legend
        },
        tooltip: {
          backgroundColor: "rgba(0, 0, 0, 0.8)",
          titleColor: "#ffffff",
          bodyColor: "#ffffff",
          borderColor: "rgba(255, 255, 255, 0.1)",
          borderWidth: 1,
          cornerRadius: 8,
          displayColors: true,
          callbacks: {
            label: function (context) {
              const value = context.parsed.y;
              const formattedValue = new Intl.NumberFormat("ro-RO", {
                style: "currency",
                currency: "RON",
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
              }).format(value);
              return `${context.dataset.label}: ${formattedValue}`;
            },
          },
        },
      },
      scales: {
        x: {
          grid: {
            display: false,
          },
          border: {
            display: false,
          },
          ticks: {
            color: "rgba(107, 114, 128, 0.8)",
            font: {
              size: 12,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
          },
        },
        y: {
          beginAtZero: true,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          border: {
            display: false,
          },
          ticks: {
            color: "rgba(107, 114, 128, 0.8)",
            font: {
              size: 12,
              family: "Inter, -apple-system, BlinkMacSystemFont, sans-serif",
            },
            callback: function (value) {
              return new Intl.NumberFormat("ro-RO", {
                style: "currency",
                currency: "RON",
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
                notation: "compact",
              }).format(value);
            },
          },
        },
      },
      elements: {
        line: {
          borderCapStyle: "round",
          borderJoinStyle: "round",
        },
      },
    },
  });
};

const updateChart = async () => {
  if (chartInstance && chartData.value?.labels?.length) {
    chartInstance.data.labels = chartData.value.labels;
    chartInstance.data.datasets[0].data = chartData.value.income;
    chartInstance.data.datasets[1].data = chartData.value.expenses;
    chartInstance.update("active");
  } else {
    await initializeChart();
  }
};

const getRateClass = (rate) => {
  if (rate >= 85) return "rate-excellent";
  if (rate >= 75) return "rate-good";
  if (rate >= 60) return "rate-average";
  return "rate-poor";
};

const getTrendClass = (trend) => {
  switch (trend) {
    case "up":
      return "trend-up";
    case "down":
      return "trend-down";
    default:
      return "trend-stable";
  }
};

const getTrendIcon = (trend) => {
  switch (trend) {
    case "up":
      return "pi pi-arrow-up";
    case "down":
      return "pi pi-arrow-down";
    default:
      return "pi pi-minus";
  }
};

const getTrendText = (trend) => {
  switch (trend) {
    case "up":
      return "Crescător";
    case "down":
      return "Descrescător";
    default:
      return "Stabil";
  }
};

const getWorkingCapitalClass = (value) => {
  if (value > 100000) return "capital-positive";
  if (value > 0) return "capital-neutral";
  return "capital-negative";
};

// Watchers
watch(
  () => props.companyId,
  (newId) => {
    if (newId) {
      loadPerformanceData();
    }
  },
  { immediate: true },
);

watch(
  chartData,
  async () => {
    if (chartData.value?.labels?.length) {
      await nextTick();
      await updateChart();
    }
  },
  { deep: true },
);

// Lifecycle
onMounted(async () => {
  if (props.companyId) {
    await loadPerformanceData();
  }
});

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

<style scoped>
/* Performance Card Styles */
.performance-card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--card-radius);
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-fast);
  overflow: hidden;
}

.performance-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

/* Header */
.card-header {
  padding: var(--space-lg);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-bg-secondary);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-md);
}

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

.card-icon {
  font-size: var(--text-lg);
}

.card-title {
  margin: 0;
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--color-text);
}

/* Period Selector */
.period-selector {
  position: relative;
}

.period-select {
  appearance: none;
  padding: var(--space-sm) var(--space-xl) var(--space-sm) var(--space-md);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  min-width: 100px;
}

.period-select:hover {
  border-color: var(--color-primary);
}

.period-select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px rgba(var(--color-primary-rgb), 0.1);
}

.period-select:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.select-icon {
  position: absolute;
  right: var(--space-sm);
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-secondary);
  font-size: var(--text-xs);
  pointer-events: none;
}

/* Body */
.card-body {
  padding: var(--space-lg);
}

/* Loading State */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-2xl);
  gap: var(--space-md);
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--color-border);
  border-top-color: var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

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

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* Error State */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-2xl);
  gap: var(--space-md);
  text-align: center;
}

.error-icon {
  color: var(--color-error);
  font-size: var(--text-2xl);
}

.error-text {
  color: var(--color-error);
  font-size: var(--text-sm);
  margin-bottom: var(--space-sm);
}

.retry-button {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  padding: var(--space-sm) var(--space-md);
  background: var(--color-primary);
  color: var(--color-text-inverse);
  border: none;
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: var(--text-sm);
  transition: background-color var(--transition-fast);
}

.retry-button:hover {
  background: var(--color-primary-dark);
}

/* Chart Container */
.chart-container {
  margin-bottom: var(--space-xl);
  min-height: 200px;
}

.chart-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  border: 2px dashed var(--color-border);
  border-radius: var(--radius-md);
  background: var(--color-bg-secondary);
}

.placeholder-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-sm);
  text-align: center;
}

.placeholder-icon {
  font-size: var(--text-3xl);
  color: var(--color-text-muted);
}

.placeholder-text {
  font-size: var(--text-base);
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
}

.placeholder-subtitle {
  font-size: var(--text-sm);
  color: var(--color-text-muted);
}

/* Chart Content */
.chart-content {
  background: var(--color-bg);
  border-radius: var(--radius-md);
  overflow: hidden;
}

.chart-legend {
  display: flex;
  justify-content: space-around;
  padding: var(--space-md);
  background: var(--color-bg-secondary);
  border-bottom: 1px solid var(--color-border);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  font-size: var(--text-sm);
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: var(--radius-sm);
}

.legend-color.income {
  background: var(--color-success);
}

.legend-color.expenses {
  background: var(--color-error);
}

.legend-label {
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
}

.legend-value {
  font-weight: var(--font-semibold);
  color: var(--color-text);
}

.chart-canvas-container {
  padding: var(--space-lg);
  height: 200px;
  position: relative;
}

.chart-canvas-container canvas {
  width: 100% !important;
  height: 100% !important;
}

/* Indicators */
.indicators-section {
  border-top: 1px solid var(--color-border);
  padding-top: var(--space-lg);
}

.indicators-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-md);
}

.indicator-card {
  display: flex;
  align-items: center;
  gap: var(--space-md);
  padding: var(--space-md);
  background: var(--color-bg-secondary);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.indicator-card:hover {
  background: var(--color-bg-muted);
}

.indicator-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  border-radius: var(--radius-lg);
  font-size: var(--text-lg);
  flex-shrink: 0;
}

.indicator-content {
  flex: 1;
  min-width: 0;
}

.indicator-label {
  font-size: var(--text-xs);
  color: var(--color-text-secondary);
  font-weight: var(--font-medium);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: var(--space-xs);
}

.indicator-value {
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
  color: var(--color-text);
  display: flex;
  align-items: center;
  gap: var(--space-xs);
}

/* Indicator Value Colors */
.rate-excellent {
  color: var(--color-success);
}
.rate-good {
  color: #10b981;
}
.rate-average {
  color: var(--color-warning);
}
.rate-poor {
  color: var(--color-error);
}

.trend-up {
  color: var(--color-success);
}
.trend-down {
  color: var(--color-error);
}
.trend-stable {
  color: var(--color-secondary);
}

.capital-positive {
  color: var(--color-success);
}
.capital-neutral {
  color: var(--color-warning);
}
.capital-negative {
  color: var(--color-error);
}

/* Mobile Responsive */
@media (max-width: 768px) {
  .card-header {
    padding: var(--space-md);
  }

  .card-body {
    padding: var(--space-md);
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--space-sm);
  }

  .indicators-grid {
    grid-template-columns: 1fr;
    gap: var(--space-sm);
  }

  .indicator-card {
    padding: var(--space-sm);
  }

  .indicator-icon {
    width: 32px;
    height: 32px;
    font-size: var(--text-base);
  }

  .chart-canvas-container {
    height: 160px;
    padding: var(--space-md);
  }

  .chart-legend {
    flex-direction: column;
    gap: var(--space-xs);
    padding: var(--space-sm);
  }
}

@media (max-width: 480px) {
  .card-header,
  .card-body {
    padding: var(--space-sm);
  }

  .card-title {
    font-size: var(--text-base);
  }

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

  .loading-state,
  .error-state {
    padding: var(--space-lg);
  }
}
</style>
