<template>
  <div class="container mx-auto px-4 py-6">
    <h1 class="text-2xl font-bold text-neutral-dark mb-6">{{ $t('earnings.title') }}</h1>
    
    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
      <div class="bg-white rounded-lg shadow p-6 border border-neutral-light hover:border-primary transition-colors duration-200">
        <h2 class="text-lg font-medium text-neutral-dark mb-2">{{ $t('earnings.totalEarnings') }}</h2>
        <p class="text-3xl font-bold text-primary">{{ formatCurrency(totalEarnings) }}</p>
        <p class="text-sm text-neutral mt-2 flex items-center">
          <span :class="earningsChange >= 0 ? 'text-green-500' : 'text-red-500'" class="flex items-center">
            <svg v-if="earningsChange >= 0" class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
            </svg>
            <svg v-else class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
            </svg>
            {{ earningsChange >= 0 ? '+' : '' }}{{ earningsChange }}%
          </span> 
          <span class="ml-1">{{ $t('earnings.comparedToLastMonth') }}</span>
        </p>
      </div>
      
      <div class="bg-white rounded-lg shadow p-6 border border-neutral-light hover:border-secondary-lavender transition-colors duration-200">
        <h2 class="text-lg font-medium text-neutral-dark mb-2">{{ $t('earnings.thisMonth') }}</h2>
        <p class="text-3xl font-bold text-secondary-lavender">{{ formatCurrency(currentMonthEarnings) }}</p>
        <p class="text-sm text-neutral mt-2 flex items-center">
          <svg class="w-4 h-4 mr-1 text-neutral" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
          </svg>
          {{ daysLeftInMonth }} {{ $t('earnings.daysLeft') }}
        </p>
      </div>
      
      <div class="bg-white rounded-lg shadow p-6 border border-neutral-light hover:border-accent-yellow transition-colors duration-200">
        <h2 class="text-lg font-medium text-neutral-dark mb-2">{{ $t('earnings.bestPlatform') }}</h2>
        <p class="text-3xl font-bold text-accent-yellow">{{ bestPlatform.name }}</p>
        <p class="text-sm text-neutral mt-2 flex items-center">
          <svg class="w-4 h-4 mr-1 text-neutral" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
          </svg>
          {{ formatCurrency(bestPlatform.amount) }} ({{ bestPlatform.percentage }}%)
        </p>
      </div>
    </div>
    
    <!-- Main Chart -->
    <div class="bg-white rounded-lg shadow p-6 mb-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-lg font-medium text-neutral-dark">{{ $t('earnings.monthlyEarnings') }}</h2>
        <div class="flex space-x-2">
          <button 
            v-for="period in timePeriods" 
            :key="period.value"
            @click="selectedPeriod = period.value"
            class="px-3 py-1 text-sm rounded-md"
            :class="selectedPeriod === period.value ? 'bg-primary text-white' : 'bg-neutral-light text-neutral-dark'"
          >
            {{ period.label }}
          </button>
        </div>
      </div>
      
      <div class="chart-container">
        <LineChart :chart-data="chartData" :options="chartOptions" :styles="chartStyles" />
      </div>
    </div>
    
    <!-- Platform Breakdown -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
      <!-- Platform Distribution -->
      <div class="bg-white rounded-lg shadow p-6">
        <h2 class="text-lg font-medium text-neutral-dark mb-4">{{ $t('earnings.platformDistribution') }}</h2>
        <div class="chart-container-small">
          <DoughnutChart :chart-data="doughnutData" :options="doughnutOptions" :styles="doughnutStyles" />
        </div>
      </div>
      
      <!-- Platform Comparison -->
      <div class="bg-white rounded-lg shadow p-6">
        <h2 class="text-lg font-medium text-neutral-dark mb-4">{{ $t('earnings.platformComparison') }}</h2>
        <div class="chart-container-small">
          <BarChart :chart-data="barData" :options="barOptions" :styles="barStyles" />
        </div>
      </div>
    </div>
    
    <!-- Earnings History Table -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4">
        <h2 class="text-lg font-medium text-neutral-dark mb-2 sm:mb-0">{{ $t('earnings.earningsHistory') }}</h2>
        <div class="flex items-center space-x-2">
          <label for="platform-filter" class="text-sm text-neutral-dark">{{ $t('earnings.filterByPlatform') }}:</label>
          <select 
            id="platform-filter" 
            v-model="platformFilter"
            class="border border-neutral-light rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
          >
            <option value="all">{{ $t('earnings.allPlatforms') }}</option>
            <option value="TikTok">TikTok</option>
            <option value="YouTube">YouTube</option>
            <option value="Instagram">Instagram</option>
          </select>
        </div>
      </div>
      
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-neutral-light">
          <thead>
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-neutral-dark uppercase tracking-wider">{{ $t('earnings.date') }}</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-neutral-dark uppercase tracking-wider">{{ $t('earnings.platform') }}</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-neutral-dark uppercase tracking-wider">{{ $t('earnings.amount') }}</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-neutral-dark uppercase tracking-wider">{{ $t('earnings.change') }}</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-neutral-light">
            <tr v-for="(entry, index) in paginatedEarningsHistory" :key="index" class="hover:bg-neutral-50">
              <td class="px-4 py-3 whitespace-nowrap text-sm text-neutral-dark">{{ formatDate(entry.date) }}</td>
              <td class="px-4 py-3 whitespace-nowrap text-sm text-neutral-dark">
                <span 
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  :class="getPlatformClass(entry.platform)"
                >
                  {{ entry.platform }}
                </span>
              </td>
              <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-neutral-dark">{{ formatCurrency(entry.amount) }}</td>
              <td class="px-4 py-3 whitespace-nowrap text-sm">
                <span :class="entry.change >= 0 ? 'text-green-500' : 'text-red-500'" class="font-medium">
                  {{ entry.change >= 0 ? '+' : '' }}{{ entry.change }}%
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- Pagination -->
      <div class="flex flex-col sm:flex-row justify-between items-center mt-4 pt-4 border-t border-neutral-light">
        <p class="text-sm text-neutral mb-2 sm:mb-0">
          {{ $t('earnings.showing') }} {{ (currentPage - 1) * itemsPerPage + 1 }} {{ $t('earnings.to') }} 
          {{ Math.min(currentPage * itemsPerPage, filteredEarningsHistory.length) }} {{ $t('earnings.of') }} 
          {{ filteredEarningsHistory.length }} {{ $t('earnings.results') }}
        </p>
        <div class="flex space-x-2">
          <button 
            @click="currentPage--" 
            :disabled="currentPage === 1"
            class="px-3 py-1 text-sm rounded-md bg-neutral-light text-neutral-dark hover:bg-neutral-200 disabled:opacity-50 disabled:hover:bg-neutral-light"
          >
            {{ $t('earnings.previous') }}
          </button>
          <button 
            @click="currentPage++" 
            :disabled="currentPage >= Math.ceil(filteredEarningsHistory.length / itemsPerPage)"
            class="px-3 py-1 text-sm rounded-md bg-neutral-light text-neutral-dark hover:bg-neutral-200 disabled:opacity-50 disabled:hover:bg-neutral-light"
          >
            {{ $t('earnings.next') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Line, Doughnut, Bar } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, ArcElement, BarElement } from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, ArcElement, BarElement);

// Globale Chart.js-Einstellungen
ChartJS.defaults.font.size = 10;
ChartJS.defaults.plugins.legend.labels.boxWidth = 10;
ChartJS.defaults.plugins.legend.labels.padding = 6;

export default {
  components: {
    LineChart: Line,
    DoughnutChart: Doughnut,
    BarChart: Bar
  },
  setup() {
    const { t, locale } = useI18n();
    
    // State
    const loading = ref(true);
    const totalEarnings = ref(3245.67);
    const earningsChange = ref(12.5);
    const currentMonthEarnings = ref(427.89);
    const selectedPeriod = ref('6m');
    const platformFilter = ref('all');
    const currentPage = ref(1);
    const itemsPerPage = ref(10);
    
    // Chart styles
    const chartStyles = {
      height: '250px',
      position: 'relative'
    };
    
    const doughnutStyles = {
      height: '200px',
      position: 'relative'
    };
    
    const barStyles = {
      height: '200px',
      position: 'relative'
    };
    
    // Mock data
    const mockEarningsData = reactive({
      monthly: [
        { month: 'Jan', TikTok: 120.45, YouTube: 230.67, Instagram: 45.32 },
        { month: 'Feb', TikTok: 145.78, YouTube: 245.90, Instagram: 52.45 },
        { month: 'Mar', TikTok: 165.23, YouTube: 267.45, Instagram: 58.90 },
        { month: 'Apr', TikTok: 189.56, YouTube: 289.34, Instagram: 67.23 },
        { month: 'Mai', TikTok: 210.34, YouTube: 312.56, Instagram: 78.45 },
        { month: 'Jun', TikTok: 245.67, YouTube: 345.78, Instagram: 89.67 },
        { month: 'Jul', TikTok: 267.89, YouTube: 378.45, Instagram: 98.34 },
        { month: 'Aug', TikTok: 289.45, YouTube: 412.67, Instagram: 110.23 },
        { month: 'Sep', TikTok: 312.56, YouTube: 445.89, Instagram: 125.67 },
        { month: 'Okt', TikTok: 345.78, YouTube: 478.90, Instagram: 142.34 },
        { month: 'Nov', TikTok: 378.90, YouTube: 512.45, Instagram: 156.78 },
        { month: 'Dez', TikTok: 412.45, YouTube: 545.67, Instagram: 172.45 }
      ],
      history: []
    });
    
    // Generate mock history data
    const generateMockHistory = () => {
      const platforms = ['TikTok', 'YouTube', 'Instagram'];
      const history = [];
      
      // Generate data for the last 2 years (24 months)
      const currentDate = new Date();
      for (let i = 0; i < 24; i++) {
        const date = new Date(currentDate);
        date.setMonth(date.getMonth() - i);
        
        for (const platform of platforms) {
          const baseAmount = Math.random() * 200 + 50; // Random amount between 50 and 250
          const previousAmount = i > 0 ? history.find(h => h.platform === platform && h.month === date.getMonth() + 1 && h.year === date.getFullYear() - 1)?.amount || baseAmount : baseAmount;
          const change = Math.random() * 30 - 10; // Random change between -10% and +20%
          
          history.push({
            date: new Date(date),
            platform,
            amount: previousAmount * (1 + change / 100),
            change: parseFloat(change.toFixed(2)),
            month: date.getMonth() + 1,
            year: date.getFullYear()
          });
        }
      }
      
      return history.sort((a, b) => b.date - a.date);
    };
    
    mockEarningsData.history = generateMockHistory();
    
    // Computed properties
    const daysLeftInMonth = computed(() => {
      const now = new Date();
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      return lastDay.getDate() - now.getDate();
    });
    
    const bestPlatform = computed(() => {
      const platforms = {
        TikTok: 0,
        YouTube: 0,
        Instagram: 0
      };
      
      // Sum up earnings for each platform
      mockEarningsData.history.forEach(entry => {
        if (entry.date.getMonth() === new Date().getMonth() && 
            entry.date.getFullYear() === new Date().getFullYear()) {
          platforms[entry.platform] += entry.amount;
        }
      });
      
      // Find the platform with the highest earnings
      let bestPlatform = 'YouTube';
      let highestAmount = 0;
      
      for (const [platform, amount] of Object.entries(platforms)) {
        if (amount > highestAmount) {
          bestPlatform = platform;
          highestAmount = amount;
        }
      }
      
      // Calculate percentage
      const total = Object.values(platforms).reduce((sum, amount) => sum + amount, 0);
      const percentage = total > 0 ? Math.round((highestAmount / total) * 100) : 0;
      
      return {
        name: bestPlatform,
        amount: highestAmount,
        percentage
      };
    });
    
    const timePeriods = [
      { label: '3M', value: '3m' },
      { label: '6M', value: '6m' },
      { label: '1J', value: '1y' },
      { label: 'All', value: 'all' }
    ];
    
    const chartData = computed(() => {
      let months;
      const now = new Date();
      
      switch (selectedPeriod.value) {
        case '3m':
          months = mockEarningsData.monthly.slice(-3);
          break;
        case '6m':
          months = mockEarningsData.monthly.slice(-6);
          break;
        case '1y':
          months = mockEarningsData.monthly;
          break;
        case 'all':
          // For 'all', we'll use the last 2 years of data
          const uniqueMonthYears = [...new Set(mockEarningsData.history.map(h => `${h.year}-${h.month}`))];
          const sortedMonthYears = uniqueMonthYears.sort();
          
          months = sortedMonthYears.map(my => {
            const [year, month] = my.split('-');
            const monthData = { month: new Date(parseInt(year), parseInt(month) - 1).toLocaleString(locale.value, { month: 'short' }) };
            
            ['TikTok', 'YouTube', 'Instagram'].forEach(platform => {
              const entries = mockEarningsData.history.filter(h => h.year === parseInt(year) && h.month === parseInt(month) && h.platform === platform);
              monthData[platform] = entries.reduce((sum, entry) => sum + entry.amount, 0);
            });
            
            return monthData;
          });
          break;
        default:
          months = mockEarningsData.monthly.slice(-6);
      }
      
      return {
        labels: months.map(m => m.month),
        datasets: [
          {
            label: 'TikTok',
            backgroundColor: 'rgba(90, 143, 221, 0.2)',
            borderColor: '#5A8FDD',
            data: months.map(m => m.TikTok),
            tension: 0.4
          },
          {
            label: 'YouTube',
            backgroundColor: 'rgba(191, 162, 219, 0.2)',
            borderColor: '#BFA2DB',
            data: months.map(m => m.YouTube),
            tension: 0.4
          },
          {
            label: 'Instagram',
            backgroundColor: 'rgba(247, 183, 163, 0.2)',
            borderColor: '#F7B7A3',
            data: months.map(m => m.Instagram),
            tension: 0.4
          }
        ]
      };
    });
    
    const chartOptions = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        tooltip: {
          callbacks: {
            label: function(context) {
              return context.dataset.label + ': ' + 
                context.raw.toLocaleString(locale.value, { style: 'currency', currency: 'EUR' });
            }
          }
        },
        legend: {
          position: 'top',
          labels: {
            boxWidth: 12,
            padding: 10,
            font: {
              size: 11
            }
          }
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value) {
              return value.toLocaleString(locale.value, { style: 'currency', currency: 'EUR', minimumFractionDigits: 0 });
            },
            font: {
              size: 10
            }
          }
        },
        x: {
          ticks: {
            font: {
              size: 10
            }
          }
        }
      }
    };
    
    const doughnutData = computed(() => {
      // Calculate total earnings per platform for the current month
      const platforms = {
        TikTok: 0,
        YouTube: 0,
        Instagram: 0
      };
      
      const now = new Date();
      mockEarningsData.history.forEach(entry => {
        if (entry.date.getMonth() === now.getMonth() && 
            entry.date.getFullYear() === now.getFullYear()) {
          platforms[entry.platform] += entry.amount;
        }
      });
      
      return {
        labels: Object.keys(platforms),
        datasets: [
          {
            data: Object.values(platforms),
            backgroundColor: ['#5A8FDD', '#BFA2DB', '#F7B7A3'],
            hoverBackgroundColor: ['#3A77D4', '#A67FC9', '#F39377']
          }
        ]
      };
    });
    
    const doughnutOptions = {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '60%',
      plugins: {
        tooltip: {
          callbacks: {
            label: function(context) {
              const total = context.dataset.data.reduce((sum, value) => sum + value, 0);
              const percentage = total > 0 ? Math.round((context.raw / total) * 100) : 0;
              return context.label + ': ' + 
                context.raw.toLocaleString(locale.value, { style: 'currency', currency: 'EUR' }) +
                ' (' + percentage + '%)';
            }
          }
        },
        legend: {
          position: 'right',
          labels: {
            boxWidth: 12,
            padding: 10,
            font: {
              size: 11
            }
          }
        }
      }
    };
    
    const barData = computed(() => {
      // Compare current month with previous month
      const now = new Date();
      const currentMonth = now.getMonth();
      const previousMonth = currentMonth === 0 ? 11 : currentMonth - 1;
      const currentYear = now.getFullYear();
      const previousYear = currentMonth === 0 ? currentYear - 1 : currentYear;
      
      const currentMonthData = mockEarningsData.history.filter(
        entry => entry.date.getMonth() === currentMonth && entry.date.getFullYear() === currentYear
      );
      
      const previousMonthData = mockEarningsData.history.filter(
        entry => entry.date.getMonth() === previousMonth && entry.date.getFullYear() === previousYear
      );
      
      const platforms = ['TikTok', 'YouTube', 'Instagram'];
      const currentMonthTotals = {};
      const previousMonthTotals = {};
      
      platforms.forEach(platform => {
        currentMonthTotals[platform] = currentMonthData
          .filter(entry => entry.platform === platform)
          .reduce((sum, entry) => sum + entry.amount, 0);
          
        previousMonthTotals[platform] = previousMonthData
          .filter(entry => entry.platform === platform)
          .reduce((sum, entry) => sum + entry.amount, 0);
      });
      
      return {
        labels: platforms,
        datasets: [
          {
            label: new Date(currentYear, currentMonth).toLocaleString(locale.value, { month: 'long' }),
            backgroundColor: '#5A8FDD',
            data: platforms.map(platform => currentMonthTotals[platform])
          },
          {
            label: new Date(previousYear, previousMonth).toLocaleString(locale.value, { month: 'long' }),
            backgroundColor: '#BFA2DB',
            data: platforms.map(platform => previousMonthTotals[platform])
          }
        ]
      };
    });
    
    const barOptions = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        tooltip: {
          callbacks: {
            label: function(context) {
              return context.dataset.label + ': ' + 
                context.raw.toLocaleString(locale.value, { style: 'currency', currency: 'EUR' });
            }
          }
        },
        legend: {
          position: 'top',
          labels: {
            boxWidth: 12,
            padding: 8,
            font: {
              size: 11
            }
          }
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value) {
              return value.toLocaleString(locale.value, { style: 'currency', currency: 'EUR', minimumFractionDigits: 0 });
            },
            font: {
              size: 10
            }
          }
        },
        x: {
          ticks: {
            font: {
              size: 10
            }
          }
        }
      }
    };
    
    const filteredEarningsHistory = computed(() => {
      let filtered = [...mockEarningsData.history];
      
      if (platformFilter.value !== 'all') {
        filtered = filtered.filter(entry => entry.platform === platformFilter.value);
      }
      
      return filtered;
    });
    
    const paginatedEarningsHistory = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage.value;
      const end = start + itemsPerPage.value;
      return filteredEarningsHistory.value.slice(start, end);
    });
    
    // Helper functions
    const formatCurrency = (value) => {
      return value.toLocaleString(locale.value, { style: 'currency', currency: 'EUR' });
    };
    
    const formatDate = (date) => {
      return date.toLocaleDateString(locale.value, { year: 'numeric', month: 'short', day: 'numeric' });
    };
    
    const getPlatformClass = (platform) => {
      switch (platform) {
        case 'TikTok':
          return 'bg-primary-100 text-primary border border-primary-200';
        case 'YouTube':
          return 'bg-secondary-lavender-light text-secondary-lavender-dark border border-secondary-lavender';
        case 'Instagram':
          return 'bg-accent-coral-light text-accent-coral-dark border border-accent-coral';
        default:
          return 'bg-neutral-light text-neutral-dark border border-neutral';
      }
    };
    
    onMounted(() => {
      // Simulate loading data
      setTimeout(() => {
        loading.value = false;
      }, 500);
    });
    
    return {
      loading,
      totalEarnings,
      earningsChange,
      currentMonthEarnings,
      daysLeftInMonth,
      bestPlatform,
      selectedPeriod,
      timePeriods,
      chartData,
      chartOptions,
      doughnutData,
      doughnutOptions,
      barData,
      barOptions,
      platformFilter,
      filteredEarningsHistory,
      paginatedEarningsHistory,
      currentPage,
      itemsPerPage,
      formatCurrency,
      formatDate,
      getPlatformClass,
      chartStyles,
      doughnutStyles,
      barStyles
    };
  }
};
</script>

<style scoped>
/* Kontrolliere die Canvas-Größe */
.chart-container {
  position: relative;
  height: 250px;
  width: 250px;
  margin: 0 auto;
}

.chart-container-small {
  position: relative;
  height: 200px;
  width: 200px;
  margin: 0 auto;
}

canvas {
  max-width: 200px;
}
</style> 