<template>
  <div class="cashflow-card">
    <!-- Card Header -->
    <div class="card-header">
      <div class="header-content">
        <h3 class="card-title">📅 Cash Flow Previzionat</h3>
        <div class="period-selector">
          <select
            v-model="selectedPeriod"
            @change="handlePeriodChange"
            class="period-select"
          >
            <option value="7d">Următoarele 7 zile</option>
            <option value="1m">Următoarea lună</option>
            <option value="3m">Următoarele 3 luni</option>
            <option value="6m">Următoarele 6 luni</option>
          </select>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>Se încarcă previziunea cash flow...</p>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="error-state">
      <div class="error-icon">⚠️</div>
      <p>{{ error }}</p>
      <button @click="loadCashFlowData" class="retry-btn">
        Încearcă din nou
      </button>
    </div>

    <!-- Cash Flow Content -->
    <div v-else class="cashflow-content">
      <!-- Chart Container -->
      <div
        class="cashflow-bars"
        v-if="chartData && chartData.periods.length > 0"
      >
        <div class="chart-header">
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-color inflow"></span>
              <span class="legend-label">Încasări</span>
            </div>
            <div class="legend-item">
              <span class="legend-color outflow"></span>
              <span class="legend-label">Plăți</span>
            </div>
          </div>
        </div>

        <!-- Chart.js Canvas -->
        <div class="chart-canvas-container">
          <canvas
            ref="cashflowChart"
            v-if="chartData?.periods?.length"
            width="400"
            height="200"
          ></canvas>
        </div>
      </div>

      <!-- Empty State -->
      <div v-else class="empty-state">
        <div class="empty-icon">📊</div>
        <p>Nu există date de cash flow pentru perioada selectată</p>
      </div>

      <!-- Cash Flow Summary -->
      <div v-if="chartData" class="cashflow-summary">
        <div class="summary-row">
          <div
            class="summary-item net-flow"
            :class="getNetFlowClass(chartData.netTotal)"
          >
            <span class="summary-label">Net Total:</span>
            <span class="summary-value">{{
              formatCurrency(chartData.netTotal)
            }}</span>
          </div>
        </div>

        <!-- Critical Days Warnings -->
        <div
          v-if="chartData.criticalDays && chartData.criticalDays.length > 0"
          class="warnings"
        >
          <div class="warning-header">
            <span class="warning-icon">⚠️</span>
            <span class="warning-title">Zile Critice</span>
          </div>
          <div class="critical-days">
            <span
              v-for="day in chartData.criticalDays"
              :key="day"
              class="critical-day"
            >
              {{ day }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, 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,
    required: true,
  },
});

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

// Store
const dashboardStore = useDashboardStore();

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

// Computed
const maxValue = computed(() => {
  if (!chartData.value) return 1;

  const allValues = [
    ...chartData.value.inflows,
    ...chartData.value.outflows.map(Math.abs),
  ].filter((v) => v > 0);

  return Math.max(...allValues, 1);
});

// Methods
const formatCurrency = (amount) => {
  if (!amount && amount !== 0) return "0,00 RON";
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(numAmount)) return "0,00 RON";

  try {
    return new Intl.NumberFormat("ro-RO", {
      style: "currency",
      currency: "RON",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(numAmount);
  } catch (error) {
    return `${numAmount.toLocaleString("ro-RO", { minimumFractionDigits: 0, maximumFractionDigits: 0 })} RON`;
  }
};

const formatCurrencyShort = (amount) => {
  if (!amount && amount !== 0) return "0";
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(numAmount)) return "0";

  const absAmount = Math.abs(numAmount);

  if (absAmount >= 1000000) {
    return `${(numAmount / 1000000).toFixed(1)}M`;
  } else if (absAmount >= 1000) {
    return `${(numAmount / 1000).toFixed(0)}k`;
  }

  return numAmount.toLocaleString("ro-RO", {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  });
};

const initializeChart = async () => {
  if (!cashflowChart.value || !chartData.value) return;

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

  await nextTick();

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

  chartInstance.value = new Chart(ctx, {
    type: "line",
    data: {
      labels: chartData.value.periods,
      datasets: [
        {
          label: "Încasări",
          data: chartData.value.inflows,
          borderColor: "rgb(34, 197, 94)",
          backgroundColor: "rgba(34, 197, 94, 0.1)",
          borderWidth: 2,
          fill: false,
          tension: 0.4,
          pointBackgroundColor: "rgb(34, 197, 94)",
          pointBorderColor: "#ffffff",
          pointBorderWidth: 2,
          pointRadius: 5,
          pointHoverRadius: 7,
        },
        {
          label: "Plăți",
          data: chartData.value.outflows.map(Math.abs),
          borderColor: "rgb(239, 68, 68)",
          backgroundColor: "rgba(239, 68, 68, 0.1)",
          borderWidth: 2,
          fill: false,
          tension: 0.4,
          pointBackgroundColor: "rgb(239, 68, 68)",
          pointBorderColor: "#ffffff",
          pointBorderWidth: 2,
          pointRadius: 5,
          pointHoverRadius: 7,
        },
        {
          label: "Net Flow",
          data: chartData.value.netFlow,
          borderColor: "rgb(99, 102, 241)",
          backgroundColor: "rgba(99, 102, 241, 0.1)",
          borderWidth: 2,
          fill: false,
          tension: 0.4,
          pointBackgroundColor: "rgb(99, 102, 241)",
          pointBorderColor: "#ffffff",
          pointBorderWidth: 2,
          pointRadius: 5,
          pointHoverRadius: 7,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: "index",
        intersect: false,
      },
      plugins: {
        legend: {
          position: "top",
          labels: {
            usePointStyle: true,
            padding: 20,
            font: {
              size: 12,
              weight: "500",
            },
          },
        },
        tooltip: {
          backgroundColor: "rgba(0, 0, 0, 0.8)",
          titleColor: "#ffffff",
          bodyColor: "#ffffff",
          borderColor: "rgba(255, 255, 255, 0.2)",
          borderWidth: 1,
          cornerRadius: 8,
          displayColors: true,
          callbacks: {
            label: function (context) {
              const label = context.dataset.label;
              const value = context.parsed.y;
              return `${label}: ${formatCurrency(value)}`;
            },
          },
        },
      },
      scales: {
        x: {
          display: true,
          grid: {
            display: false,
          },
          ticks: {
            font: {
              size: 11,
            },
            color: "rgba(107, 114, 128, 0.8)",
          },
        },
        y: {
          display: true,
          grid: {
            color: "rgba(107, 114, 128, 0.1)",
            drawBorder: false,
          },
          ticks: {
            font: {
              size: 11,
            },
            color: "rgba(107, 114, 128, 0.8)",
            callback: function (value) {
              return formatCurrencyShort(value);
            },
          },
        },
      },
      elements: {
        line: {
          borderJoinStyle: "round",
        },
        point: {
          hoverBorderWidth: 3,
        },
      },
    },
  });
};

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

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

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

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

  try {
    const result = await dashboardStore.loadCashFlowData(
      props.companyId,
      selectedPeriod.value,
    );

    if (result.success) {
      chartData.value = result.data;
      await nextTick();
      initializeChart();
    } else {
      error.value = result.error || "Nu s-au putut încărca datele";
      // Fallback to mock data for development
      chartData.value = generateMockData();
      await nextTick();
      initializeChart();
    }
  } catch (err) {
    console.error("Error loading cash flow data:", err);
    error.value = "Eroare la încărcarea datelor";
    // Fallback to mock data for development
    chartData.value = generateMockData();
    await nextTick();
    initializeChart();
  } finally {
    isLoading.value = false;
  }
};

const generateMockData = () => {
  const periods = {
    "7d": ["Luni", "Marți", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"],
    "1m": ["S1", "S2", "S3", "S4"],
    "3m": ["Luna 1", "Luna 2", "Luna 3"],
    "6m": ["Trim 1", "Trim 2"],
  };

  const periodLabels = periods[selectedPeriod.value] || periods["7d"];
  const inflows = periodLabels.map(() => Math.random() * 500000 + 100000);
  const outflows = periodLabels.map(() => -(Math.random() * 400000 + 50000));
  const netFlow = inflows.map((inflow, i) => inflow + outflows[i]);
  const cumulative = netFlow.reduce((acc, val, i) => {
    acc.push((acc[i - 1] || 0) + val);
    return acc;
  }, []);

  const criticalDays = netFlow
    .map((net, i) => (net < -50000 ? periodLabels[i] : null))
    .filter(Boolean);

  return {
    periods: periodLabels,
    inflows,
    outflows,
    netFlow,
    cumulative,
    criticalDays,
    netTotal: netFlow.reduce((sum, val) => sum + val, 0),
  };
};

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

watch(
  chartData,
  (newData) => {
    if (newData) {
      nextTick(() => {
        initializeChart();
      });
    }
  },
  { deep: true },
);

// Lifecycle
onMounted(() => {
  if (props.companyId) {
    loadCashFlowData();
  }
});

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

<style scoped>
.cashflow-card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--card-radius);
  overflow: hidden;
  transition: all var(--transition-fast);
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

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

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

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

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

.period-selector {
  display: flex;
  align-items: center;
}

.period-select {
  padding: var(--space-xs) var(--space-sm);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  background: var(--color-bg);
  color: var(--color-text);
  cursor: pointer;
  transition: all var(--transition-fast);
}

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

/* Loading and Error States */
.loading-state,
.error-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl);
  color: var(--color-text-secondary);
  text-align: center;
  flex: 1;
}

.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;
  margin-bottom: var(--space-md);
}

.error-icon,
.empty-icon {
  font-size: 2rem;
  margin-bottom: var(--space-md);
}

.retry-btn {
  background: var(--color-primary);
  color: white;
  border: none;
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius-sm);
  cursor: pointer;
  font-size: var(--text-sm);
  transition: background-color var(--transition-fast);
  margin-top: var(--space-md);
}

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

/* Cash Flow Content */
.cashflow-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* Chart */
.cashflow-bars {
  padding: var(--space-lg) var(--space-xl);
  flex: 1;
}

.chart-header {
  display: flex;
  justify-content: center;
  margin-bottom: var(--space-lg);
}

.chart-legend {
  display: flex;
  gap: var(--space-lg);
}

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

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

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

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

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

/* Chart.js Container */
.chart-canvas-container {
  position: relative;
  height: 250px;
  padding: var(--space-md) 0;
}

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

/* Cash Flow Summary */
.cashflow-summary {
  padding: var(--space-lg) var(--space-xl);
  background: var(--color-bg-secondary);
  border-top: 1px solid var(--color-border);
}

.summary-row {
  display: flex;
  justify-content: center;
  margin-bottom: var(--space-md);
}

.summary-item {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius-md);
}

.summary-item.positive {
  background: var(--color-success-bg);
  color: var(--color-success);
}

.summary-item.negative {
  background: var(--color-error-bg);
  color: var(--color-error);
}

.summary-item.neutral {
  background: var(--color-bg-muted);
  color: var(--color-text);
}

.summary-label {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.summary-value {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  font-family: var(--font-mono);
}

/* Warnings */
.warnings {
  margin-top: var(--space-md);
}

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

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

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

.critical-days {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-xs);
}

.critical-day {
  background: var(--color-warning-bg);
  color: var(--color-warning);
  padding: var(--space-xs) var(--space-sm);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
}

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

/* Responsive Design */
@media (max-width: 1024px) {
  .header-content {
    flex-direction: column;
    align-items: stretch;
    gap: var(--space-sm);
  }

  .chart-legend {
    justify-content: center;
    flex-wrap: wrap;
  }

  .chart-canvas-container {
    height: 200px;
  }
}

@media (max-width: 768px) {
  .cashflow-card {
    min-height: 350px;
  }

  .card-header,
  .cashflow-bars,
  .cashflow-summary {
    padding: var(--space-md);
  }

  .chart-canvas-container {
    height: 180px;
  }

  .summary-item {
    flex-direction: column;
    text-align: center;
    gap: var(--space-xs);
  }

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

@media (max-width: 480px) {
  .chart-legend {
    flex-direction: column;
    align-items: center;
    gap: var(--space-sm);
  }

  .chart-canvas-container {
    height: 160px;
  }

  .critical-days {
    justify-content: center;
  }
}
</style>
