<template>
  <div class="header-timer">
    <!-- Timer Running State -->
    <div v-if="hasActiveTimer" class="timer-display">
      <div class="timer-info">
        <div class="timer-status running">
          <i class="fas fa-circle"></i>
          Ajastin käynnissä
        </div>
        <div class="timer-duration-large">
          {{ formatTimerDuration(activeTimers[0]) }}
        </div>
      </div>
      <div class="timer-controls">
        <button 
          @click="stopTimer(activeTimers[0]?.id)" 
          class="btn btn-sm btn-danger"
          title="Pysäytä ajastin"
        >
          <i class="fas fa-stop"></i>
          Pysäytä
        </button>
        <TimerManagement />
      </div>
    </div>
    
    <!-- No Active Timer -->
    <div v-else class="no-timer">
      <button @click="startTimerDirect" class="btn btn-sm btn-success" title="Käynnistä ajastin">
        <i class="fas fa-stopwatch"></i>
        <span class="timer-text">Käynnistä ajastin</span>
      </button>
      <TimerManagement />
    </div>
    
    <!-- Timer Modal -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>Ajastin</h3>
          <button @click="closeModal" class="close-btn">&times;</button>
        </div>
        
        <div class="modal-body">
          <div v-if="selectedTask" class="selected-task">
            <h4>Tehtävä: {{ selectedTask.title }}</h4>
          </div>
          
          <!-- Task Selection -->
          <div v-if="!selectedTask && tasks.length > 0" class="task-selection">
            <label>Valitse tehtävä (valinnainen):</label>
            <select v-model="selectedTaskId" @change="selectTask" class="form-control">
              <option value="">Ajasta ilman tehtävää</option>
              <option v-for="task in tasks" :key="task.id" :value="task.id">
                {{ task.title }}
              </option>
            </select>
          </div>
          
          <!-- Timer Display -->
          <div v-if="activeTimers.length > 0" class="timer-display-large">
            <div class="timer-info">
              <div class="timer-status" :class="{ 'timer-running': isTimerRunning }">
                <i class="fas fa-circle"></i>
                {{ isTimerRunning ? 'Ajastin käynnissä' : 'Ajastin pysäytetty' }}
              </div>
              <div class="timer-duration">
                {{ formatTimerDuration(activeTimers[0]) }}
              </div>
            </div>
          </div>
          
          <!-- Timer Controls -->
          <div class="timer-controls-large">
            <button 
              v-if="!hasActiveTimer" 
              @click="startTimer" 
              class="btn btn-success"
            >
              <i class="fas fa-play"></i>
              Aloita ajastin
            </button>
            <button 
              v-if="isTimerRunning" 
              @click="stopTimer(activeTimers[0]?.id)" 
              class="btn btn-danger"
            >
              <i class="fas fa-stop"></i>
              Pysäytä ajastin
            </button>
          </div>
          
          <!-- No tasks message -->
          <div v-if="tasks.length === 0" class="no-tasks-message">
            <p>Ei tehtäviä löytynyt. Luo ensin tehtävä ennen ajastimen käyttöä.</p>
            <button @click="$emit('navigate-to-tasks')" class="btn btn-primary">
              Siirry tehtäviin
            </button>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeModal" class="btn btn-secondary">Sulje</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../api/axios'
import TimerManagement from './TimerManagement.vue'

export default {
  name: 'HeaderTimer',
  components: {
    TimerManagement
  },
  data() {
    return {
      showModal: false,
      activeTimers: [],
      tasks: [],
      selectedTask: null,
      selectedTaskId: '',
      loading: false,
      currentTime: Date.now()
    }
  },
  computed: {
    isTimerRunning() {
      return this.activeTimers.length > 0 && this.activeTimers[0]?.end_time === null
    },
    hasActiveTimer() {
      return this.activeTimers.some(timer => !timer.end_time)
    },
  },
  mounted() {
    this.loadActiveTimers()
    this.loadTasks()
    // Update timer every second
    this.timerInterval = setInterval(() => {
      if (this.hasActiveTimer) {
        // Update current time to trigger timer duration recalculation
        this.currentTime = Date.now()
      }
    }, 1000)
  },
  beforeUnmount() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval)
    }
  },
  methods: {
    async loadActiveTimers() {
      try {
        const response = await api.get('/timers.php?action=active')
        if (response.data.success) {
          this.activeTimers = response.data.data || []
        } else {
          this.activeTimers = []
        }
      } catch (error) {
        console.error('Error loading active timers:', error)
        this.activeTimers = []
      }
    },
    
    async loadTasks() {
      try {
        const response = await api.get('/tasks.php')
        if (response.data.success) {
          this.tasks = response.data.data || []
        }
      } catch (error) {
        console.error('Error loading tasks:', error)
        this.tasks = []
      }
    },
    
    showTimerModal() {
      this.showModal = true
      this.loadActiveTimers()
      this.loadTasks()
    },
    
    closeModal() {
      this.showModal = false
      this.selectedTask = null
      this.selectedTaskId = ''
    },
    
    selectTask() {
      if (this.selectedTaskId) {
        this.selectedTask = this.tasks.find(task => task.id === parseInt(this.selectedTaskId))
      } else {
        this.selectedTask = null
      }
    },
    
    async startTimerDirect() {
      try {
        const response = await api.post('/timers.php', {
          action: 'start',
          task_id: null,
          user_id: 1,
          description: 'Timer started without task'
        })
        
        if (response.data.success) {
          this.loadActiveTimers()
        } else {
          console.error('Error starting timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error starting timer:', error)
      }
    },

    async startTimer() {
      try {
        const taskDescription = this.selectedTask ? `Timer started for ${this.selectedTask.title}` : 'Timer started without task'
        
        const response = await api.post('/timers.php', {
          action: 'start',
          task_id: this.selectedTask ? this.selectedTask.id : null,
          user_id: 1, // Default to current user
          description: taskDescription
        })
        
        if (response.data.success) {
          this.loadActiveTimers()
          this.closeModal()
        } else {
          console.error('Error starting timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error starting timer:', error)
      }
    },
    
    async stopTimer(timerId) {
      try {
        const response = await api.post('/timer_stop.php', {
          action: 'stop',
          id: timerId
        })
        
        if (response.data.success) {
          this.loadActiveTimers()
          this.loadTasks() // Refresh tasks to update total hours
        } else {
          console.error('Error stopping timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error stopping timer:', error)
      }
    },
    
    formatTimerDuration(timer) {
      if (!timer || !timer.start_time) {
        return '00:00:00'
      }
      
      // Convert UTC timestamp to local time
      const start = new Date(timer.start_time + 'Z')
      const now = new Date()
      const diff = now - start
      
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / 60000)
      const seconds = Math.floor((diff % 60000) / 1000)
      
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.header-timer {
  display: flex;
  align-items: center;
}

.timer-display {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #dee2e6;
}

.timer-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.timer-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6c757d;
}

.timer-status.running {
  color: #28a745;
}

.timer-status i {
  font-size: 8px;
}

.timer-duration {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  font-size: 14px;
  color: #495057;
}

.timer-duration-large {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  font-size: 18px;
  color: #007bff;
  margin: 4px 0;
}

.timer-task {
  font-size: 11px;
  color: #6c757d;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.timer-controls {
  display: flex;
  gap: 5px;
}

.no-timer {
  display: flex;
  align-items: center;
}

.timer-text {
  margin-left: 5px;
}

/* Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  padding: 0;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #dee2e6;
}

.modal-header h3 {
  margin: 0;
  color: #495057;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 20px;
}

.selected-task {
  margin-bottom: 20px;
}

.selected-task h4 {
  margin: 0;
  color: #495057;
}

.task-selection {
  margin-bottom: 20px;
}

.task-selection label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.timer-display-large {
  text-align: center;
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.timer-display-large .timer-status {
  font-size: 16px;
  margin-bottom: 10px;
}

.timer-display-large .timer-duration {
  font-size: 24px;
  color: #495057;
}

.timer-controls-large {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin: 20px 0;
}

.no-tasks-message {
  text-align: center;
  padding: 20px;
  color: #6c757d;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #dee2e6;
  display: flex;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}
</style>
