<template>
  <div class="dashboard">
    <h2 class="page-title">Dashboard</h2>
    
    <!-- Aktiver Timer -->
    <div class="card timer-card">
      <div class="timer-header">
        <h3>Zeiterfassung</h3>
        <div class="timer-display">{{ formattedTime }}</div>
      </div>

      <form v-if="!isRunning" @submit.prevent="startTimer" class="timer-form">
        <div class="form-group">
          <label for="project">Projekt</label>
          <input
            v-model="newEntry.project"
            type="text"
            id="project"
            class="input"
            placeholder="z.B. Projektname"
          />
        </div>
        <div class="form-group">
          <label for="description">Beschreibung</label>
          <input
            v-model="newEntry.description"
            type="text"
            id="description"
            class="input"
            placeholder="Was arbeitest du gerade?"
          />
        </div>
        <button type="submit" class="btn btn-success btn-large">
          ▶️ Starten
        </button>
      </form>

      <div v-else class="running-timer">
        <div class="running-info">
          <div class="info-item">
            <strong>Projekt:</strong> {{ currentEntry.project }}
          </div>
          <div class="info-item" v-if="currentEntry.description">
            <strong>Beschreibung:</strong> {{ currentEntry.description }}
          </div>
          <div class="info-item">
            <strong>Gestartet:</strong> {{ formatDateTime(currentEntry.startTime) }}
          </div>
        </div>
        <button @click="stopTimer" class="btn btn-danger btn-large">
          ⏹️ Stoppen
        </button>
      </div>
    </div>

    <!-- Letzte Einträge -->
    <div class="recent-entries">
      <h3>Letzte Einträge</h3>
      <div v-if="recentEntries.length === 0" class="empty-state">
        <p>Noch keine Einträge vorhanden. Starte deinen ersten Timer!</p>
      </div>
      <div v-else class="entries-list">
        <div v-for="entry in recentEntries" :key="entry.id" class="entry-card card">
          <div class="entry-header">
            <span class="entry-project">{{ entry.project }}</span>
            <span class="entry-duration">{{ formatDuration(entry.duration) }}</span>
          </div>
          <div class="entry-description">{{ entry.description || 'Keine Beschreibung' }}</div>
          <div class="entry-time">
            {{ formatDateTime(entry.startTime) }} - {{ formatDateTime(entry.endTime) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useTimeStore } from '../stores/timeStore'

const timeStore = useTimeStore()

const newEntry = ref({
  project: '',
  description: ''
})

const isRunning = computed(() => timeStore.currentEntry !== null)
const currentEntry = computed(() => timeStore.currentEntry)
const recentEntries = computed(() => timeStore.entries.slice(0, 5))

const currentTime = ref(0)
let intervalId = null

const formattedTime = computed(() => {
  if (!isRunning.value) return '00:00:00'
  return formatDuration(currentTime.value)
})

const startTimer = async () => {
  await timeStore.startTimer(newEntry.value)
  newEntry.value = { project: '', description: '' }
}

const stopTimer = async () => {
  await timeStore.stopTimer()
}

const formatDuration = (seconds) => {
  if (!seconds) return '00:00:00'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const updateCurrentTime = () => {
  if (isRunning.value && currentEntry.value) {
    const start = new Date(currentEntry.value.startTime)
    const now = new Date()
    currentTime.value = Math.floor((now - start) / 1000)
  }
}

onMounted(async () => {
  await timeStore.fetchEntries()
  intervalId = setInterval(updateCurrentTime, 1000)
})

onUnmounted(() => {
  if (intervalId) clearInterval(intervalId)
})
</script>

<style scoped>
.page-title {
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: #333;
  font-weight: normal;
}

.timer-card {
  margin-bottom: 2rem;
}

.timer-header {
  text-align: center;
  margin-bottom: 1.5rem;
}

.timer-header h3 {
  font-size: 1.3rem;
  margin-bottom: 1rem;
  color: #333;
  font-weight: normal;
}

.timer-display {
  font-size: 2.5rem;
  font-weight: bold;
  font-family: 'Courier New', monospace;
  color: #000;
  margin-bottom: 1rem;
}

.timer-form {
  max-width: 500px;
  margin: 0 auto;
}

.btn-large {
  width: 100%;
  padding: 1rem;
  font-size: 1.2rem;
}

.running-timer {
  max-width: 500px;
  margin: 0 auto;
}

.running-info {
  background-color: #f9f9f9;
  border: 1px solid #d4d4d4;
  padding: 1rem;
  margin-bottom: 1rem;
}

.info-item {
  padding: 0.5rem 0;
  border-bottom: 1px solid #e0e0e0;
}

.info-item:last-child {
  border-bottom: none;
}

.recent-entries h3 {
  font-size: 1.3rem;
  margin-bottom: 1rem;
  color: #333;
  font-weight: normal;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.entries-list {
  display: grid;
  gap: 1rem;
}

.entry-card {
  padding: 1.5rem;
}

.entry-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.entry-project {
  font-weight: bold;
  color: #000;
  font-size: 1rem;
}

.entry-duration {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: #5cb85c;
  font-size: 1rem;
}

.entry-description {
  color: #666;
  margin-bottom: 0.5rem;
  font-size: 0.95rem;
}

.entry-time {
  font-size: 0.85rem;
  color: #999;
}
</style>

