<template>
  <div class="timer-management">
    <!-- Timer Management Button -->
    <button @click="showManagementModal" class="btn btn-info btn-sm" title="Hallinnoi ajastimia">
      <i class="fas fa-history"></i>
      <span class="timer-text">Historia</span>
    </button>
    
    <!-- Timer Management Modal -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content large">
        <div class="modal-header">
          <h3>Ajastimien Hallinta</h3>
          <button @click="closeModal" class="close-btn">&times;</button>
        </div>
        
        <div class="modal-body">
          <!-- Tabs -->
          <div class="tabs">
            <button 
              :class="['tab-btn', { active: activeTab === 'active' }]" 
              @click="activeTab = 'active'"
            >
              Aktiiviset ({{ activeTimers.length }})
            </button>
            <button 
              :class="['tab-btn', { active: activeTab === 'history' }]" 
              @click="activeTab = 'history'"
            >
              Historia ({{ timerHistory.length }})
            </button>
            <button 
              :class="['tab-btn', { active: activeTab === 'workhours' }]" 
              @click="activeTab = 'workhours'"
            >
              Työtunnit ({{ workHours.length }})
            </button>
          </div>
          
          <!-- Active Timers Tab -->
          <div v-if="activeTab === 'active'" class="tab-content">
            <div v-if="loading" class="loading">Ladataan ajastimia...</div>
            
            <div v-else-if="activeTimers.length === 0" class="no-data">
              <p>Ei aktiivisia ajastimia</p>
            </div>
            
            <div v-else class="timer-list">
              <div v-for="timer in activeTimers" :key="timer.id" class="timer-item active">
                <div class="timer-info">
                  <div class="timer-header">
                    <h4>{{ timer.task_title || 'Tehtävä tuntematon' }}</h4>
                    <span class="timer-status running">
                      <i class="fas fa-circle"></i>
                      Ajastin käynnissä
                    </span>
                  </div>
                  <div class="timer-details">
                    <p class="timer-description">{{ timer.description || '-' }}</p>
                    <div class="timer-meta">
                      <span><i class="fas fa-user"></i> {{ timer.first_name }} {{ timer.last_name }}</span>
                      <span><i class="fas fa-clock"></i> {{ formatDateTime(timer.start_time) }}</span>
                      <span class="timer-duration">{{ formatTimerDuration(timer) }}</span>
                    </div>
                  </div>
                </div>
                <div class="timer-actions">
                  <button @click="stopTimer(timer.id)" class="btn btn-danger btn-sm">
                    <i class="fas fa-stop"></i>
                    Pysäytä
                  </button>
                  <button @click="editTimer(timer)" class="btn btn-warning btn-sm">
                    <i class="fas fa-edit"></i>
                    Muokkaa
                  </button>
                  <button @click="deleteTimer(timer.id)" class="btn btn-danger btn-sm">
                    <i class="fas fa-trash"></i>
                    Poista
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Timer History Tab -->
          <div v-if="activeTab === 'history'" class="tab-content">
            <div class="filter-controls">
              <input 
                type="date" 
                v-model="historyFilter.date" 
                @change="loadTimerHistory"
                class="form-control"
                placeholder="Päivämäärä"
              >
              <select v-model="historyFilter.task_id" @change="loadTimerHistory" class="form-control">
                <option value="">Kaikki tehtävät</option>
                <option v-for="task in tasks" :key="task.id" :value="task.id">
                  {{ task.title }}
                </option>
              </select>
              <button @click="clearHistoryFilters" class="btn btn-secondary btn-sm">
                <i class="fas fa-times"></i>
                Tyhjennä suodattimet
              </button>
            </div>
            
            <div v-if="loading" class="loading">Ladataan historiaa...</div>
            
            <div v-else-if="timerHistory.length === 0" class="no-data">
              <p>Ei ajastinhistoriaa</p>
            </div>
            
            <div v-else class="timer-list">
              <div v-for="timer in timerHistory" :key="timer.id" class="timer-item">
                <div class="timer-info">
                  <div class="timer-header">
                    <h4>{{ timer.task_title || 'Tehtävä tuntematon' }}</h4>
                    <span class="timer-status stopped">
                      <i class="fas fa-circle"></i>
                      Pysäytetty
                    </span>
                  </div>
                  <div class="timer-details">
                    <p class="timer-description">{{ timer.description || '-' }}</p>
                    <div class="timer-meta">
                      <span><i class="fas fa-user"></i> {{ timer.first_name }} {{ timer.last_name }}</span>
                      <span><i class="fas fa-clock"></i> {{ formatDateTime(timer.start_time) }} - {{ formatDateTime(timer.end_time) }}</span>
                      <span class="timer-duration">{{ timer.duration || '00:00:00' }}</span>
                    </div>
                  </div>
                </div>
                <div class="timer-actions">
                  <button @click="viewTimerDetails(timer)" class="btn btn-info btn-sm">
                    <i class="fas fa-eye"></i>
                    Tiedot
                  </button>
                  <button @click="editTimer(timer)" class="btn btn-warning btn-sm">
                    <i class="fas fa-edit"></i>
                    Muokkaa
                  </button>
                  <button @click="deleteTimer(timer.id)" class="btn btn-danger btn-sm">
                    <i class="fas fa-trash"></i>
                    Poista
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Work Hours Tab -->
          <div v-if="activeTab === 'workhours'" class="tab-content">
            <div class="filter-controls">
              <input 
                type="date" 
                v-model="workHoursFilter.date" 
                @change="loadWorkHours"
                class="form-control"
                placeholder="Päivämäärä"
              >
              <select v-model="workHoursFilter.task_id" @change="loadWorkHours" class="form-control">
                <option value="">Kaikki tehtävät</option>
                <option v-for="task in tasks" :key="task.id" :value="task.id">
                  {{ task.title }}
                </option>
              </select>
              <button @click="clearWorkHoursFilters" class="btn btn-secondary btn-sm">
                <i class="fas fa-times"></i>
                Tyhjennä suodattimet
              </button>
            </div>
            
            <div v-if="loading" class="loading">Ladataan tunteja...</div>
            
            <div v-else-if="workHours.length === 0" class="no-data">
              <p>Ei työtunteja</p>
            </div>
            
            <div v-else class="timer-list">
              <div v-for="workHour in workHours" :key="workHour.id" class="timer-item work-hour">
                <div class="timer-info">
                  <div class="timer-header">
                    <h4>{{ workHour.task_title || 'Tehtävä tuntematon' }}</h4>
                    <span class="timer-status work-hour">
                      <i class="fas fa-check-circle"></i>
                      Työtunti
                    </span>
                  </div>
                  <div class="timer-details">
                    <p class="timer-description">{{ workHour.description || '-' }}</p>
                    <div class="timer-meta">
                      <span><i class="fas fa-calendar"></i> {{ formatDate(workHour.date) }}</span>
                      <span><i class="fas fa-clock"></i> {{ formatTime(workHour.start_time) }} - {{ formatTime(workHour.end_time) }}</span>
                      <span class="timer-duration">{{ workHour.hours }}h</span>
                      <span v-if="workHour.rate" class="timer-rate">€{{ workHour.rate }}/h</span>
                    </div>
                  </div>
                </div>
                <div class="timer-actions">
                  <button @click="editWorkHour(workHour)" class="btn btn-warning btn-sm">
                    <i class="fas fa-edit"></i>
                    Muokkaa
                  </button>
                  <button @click="deleteWorkHour(workHour.id)" class="btn btn-danger btn-sm">
                    <i class="fas fa-trash"></i>
                    Poista
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeModal" class="btn btn-secondary">Sulje</button>
        </div>
      </div>
    </div>
    
    <!-- Timer Edit Modal -->
    <div v-if="showEditModal" class="modal" @click.self="closeEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>Muokkaa Ajastinta</h3>
          <button @click="closeEditModal" class="close-btn">&times;</button>
        </div>
        
        <div class="modal-body">
          <form @submit.prevent="saveTimer">
            <div class="form-group">
              <label for="editDescription">Kuvaus</label>
              <textarea 
                id="editDescription" 
                v-model="editForm.description" 
                rows="3"
                class="form-control"
                placeholder="Kuvaile ajastimen tarkoitusta"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="editTask">Tehtävä</label>
              <select id="editTask" v-model="editForm.task_id" class="form-control">
                <option value="">Valitse tehtävä...</option>
                <option v-for="task in tasks" :key="task.id" :value="task.id">
                  {{ task.title }}
                </option>
              </select>
            </div>
            
            <div class="form-group">
              <label for="editDuration">Kesto</label>
              <div class="duration-display">
                <span class="duration-value">{{ editForm.duration || 'Lasketaan...' }}</span>
                <span class="duration-info">(ajastin kestänyt)</span>
              </div>
            </div>
            
            <div class="form-group">
              <label for="editHours">Tunnit</label>
              <input 
                type="number" 
                id="editHours" 
                v-model="editForm.hours" 
                step="0.5"
                min="0"
                class="form-control"
                placeholder="Tunnit (esim. 1.5)"
              >
              <small class="form-text text-muted">Kokonaislaskettu tunneiksi (pyöristetty lähimpään tuntiin)</small>
            </div>
            
                        
            <div class="form-actions">
              <button type="button" @click="closeEditModal" class="btn btn-secondary">Peruuta</button>
              <button type="submit" class="btn btn-primary">Tallenna</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'TimerManagement',
  data() {
    return {
      showModal: false,
      showEditModal: false,
      activeTab: 'active',
      loading: false,
      activeTimers: [],
      timerHistory: [],
      workHours: [],
      tasks: [],
      historyFilter: {
        date: '',
        task_id: ''
      },
      workHoursFilter: {
        date: '',
        task_id: ''
      },
      editForm: {
        id: null,
        description: '',
        task_id: ''
      }
    }
  },
  mounted() {
    this.loadTasks()
  },
  methods: {
    showManagementModal() {
      this.showModal = true
      this.loadAllData()
    },
    
    closeModal() {
      this.showModal = false
    },
    
    closeEditModal() {
      this.showEditModal = false
      this.editForm = {
        id: null,
        description: '',
        task_id: '',
        duration: '',
        hours: 0
      }
    },
    
    async loadAllData() {
      await Promise.all([
        this.loadActiveTimers(),
        this.loadTimerHistory(),
        this.loadWorkHours()
      ])
    },
    
    async loadActiveTimers() {
      try {
        this.loading = true
        const response = await api.get('/timers.php?action=active')
        if (response.data.success) {
          this.activeTimers = response.data.data || []
        }
      } catch (error) {
        console.error('Error loading active timers:', error)
      } finally {
        this.loading = false
      }
    },
    
    async loadTimerHistory() {
      try {
        this.loading = true
        const params = new URLSearchParams()
        
        if (this.historyFilter.date) {
          params.append('date', this.historyFilter.date)
        }
        if (this.historyFilter.task_id) {
          params.append('task_id', this.historyFilter.task_id)
        }
        
        const response = await api.get(`/timer_history.php?${params}`)
        if (response.data.success) {
          this.timerHistory = response.data.data || []
        }
      } catch (error) {
        console.error('Error loading timer history:', error)
      } finally {
        this.loading = false
      }
    },
    
    async loadWorkHours() {
      try {
        this.loading = true
        const params = new URLSearchParams()
        
        if (this.workHoursFilter.date) {
          params.append('date', this.workHoursFilter.date)
        }
        if (this.workHoursFilter.task_id) {
          params.append('task_id', this.workHoursFilter.task_id)
        }
        
        const response = await api.get(`/work_hours.php?${params}`)
        if (response.data.success) {
          this.workHours = response.data.data || []
        }
      } catch (error) {
        console.error('Error loading work hours:', error)
      } finally {
        this.loading = false
      }
    },
    
    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)
      }
    },
    
    async stopTimer(timerId) {
      try {
        const response = await api.post('/timer_stop.php', {
          action: 'stop',
          id: timerId
        })
        
        if (response.data.success) {
          this.loadAllData()
        } else {
          console.error('Error stopping timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error stopping timer:', error)
      }
    },
    
    editTimer(timer) {
      const duration = timer.duration || this.calculateDuration(timer.start_time, timer.end_time)
      const hours = this.durationToHours(duration)
      
      this.editForm = {
        id: timer.id,
        description: timer.description || '',
        task_id: timer.task_id,
        duration: duration,
        hours: hours
      }
      this.showEditModal = true
    },
    
    async saveTimer() {
      try {
        const response = await api.post('/timer_update.php', {
          action: 'update',
          id: this.editForm.id,
          description: this.editForm.description,
          task_id: this.editForm.task_id,
          hours: this.editForm.hours
        })
        
        if (response.data.success) {
          this.closeEditModal()
          this.loadAllData()
        } else {
          console.error('Error updating timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error updating timer:', error)
      }
    },
    
    async deleteTimer(timerId) {
      if (!confirm('Oletko varma että haluat poistaa tämän ajastimen?')) return
      
      try {
        const response = await api.post('/timers.php', {
          action: 'delete',
          id: timerId
        })
        
        if (response.data.success) {
          this.loadAllData()
        } else {
          console.error('Error deleting timer:', response.data.message)
        }
      } catch (error) {
        console.error('Error deleting timer:', error)
      }
    },
    
    viewTimerDetails(timer) {
      // Could implement a detailed view modal
      alert(`Ajastimen tiedot:\n\nTehtävä: ${timer.task_title}\nKuvaus: ${timer.description || '-'}\nAloitusaika: ${this.formatDateTime(timer.start_time)}\nLopetusaika: ${this.formatDateTime(timer.end_time)}\nKesto: ${timer.duration}`)
    },
    
    async deleteWorkHour(workHourId) {
      if (!confirm('Oletko varma että haluat poistaa tämän työtunnin?')) return
      
      try {
        const response = await api.delete(`/work_hours.php?id=${workHourId}`)
        
        if (response.data.success) {
          this.loadWorkHours()
        } else {
          console.error('Error deleting work hour:', response.data.message)
        }
      } catch (error) {
        console.error('Error deleting work hour:', error)
      }
    },
    
    editWorkHour(workHour) {
      // Could implement work hour editing
      console.log('Edit work hour:', workHour)
    },
    
    clearHistoryFilters() {
      this.historyFilter = {
        date: '',
        task_id: ''
      }
      this.loadTimerHistory()
    },
    
    clearWorkHoursFilters() {
      this.workHoursFilter = {
        date: '',
        task_id: ''
      }
      this.loadWorkHours()
    },
    
    calculateDuration(startTime, endTime) {
      if (!startTime) return '00:00:00'
      
      const start = new Date(startTime + 'Z')
      const end = endTime ? new Date(endTime + 'Z') : new Date()
      const diff = end - 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')}`
    },
    
    durationToHours(duration) {
      if (!duration) return 0
      
      const parts = duration.split(':')
      const hours = parseFloat(parts[0]) || 0
      const minutes = parseFloat(parts[1]) || 0
      const seconds = parseFloat(parts[2]) || 0
      
      // Convert to decimal hours and round to nearest hour
      const decimalHours = hours + (minutes / 60) + (seconds / 3600)
      return Math.round(decimalHours * 2) / 2 // Round to nearest 0.5 hour
    },
    
        
    formatTimerDuration(timer) {
      if (!timer.start_time) return '00:00:00'
      
      // Convert UTC timestamp to local time
      const start = new Date(timer.start_time + 'Z')
      const now = timer.end_time ? new Date(timer.end_time + 'Z') : 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')}`
    },
    
    formatDateTime(dateString) {
      if (!dateString) return '-'
      return new Date(dateString + 'Z').toLocaleString('fi-FI')
    },
    
    formatDate(dateString) {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleDateString('fi-FI')
    },
    
    formatTime(timeString) {
      if (!timeString) return '-'
      return new Date(`1970-01-01T${timeString}Z`).toLocaleTimeString('fi-FI', { 
        hour: '2-digit', 
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.timer-management {
  display: inline-block;
}

.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: 900px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-content.large {
  max-width: 1200px;
}

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

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

/* Tabs */
.tabs {
  display: flex;
  border-bottom: 1px solid #dee2e6;
  margin-bottom: 20px;
}

.tab-btn {
  background: none;
  border: none;
  padding: 12px 24px;
  cursor: pointer;
  color: #6c757d;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tab-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
}

.tab-content {
  min-height: 400px;
}

/* Filter Controls */
.filter-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

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

/* Timer List */
.timer-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.timer-item {
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 15px;
}

.timer-item.active {
  border-left: 4px solid #28a745;
  background: #f8fff9;
}

.timer-item.work-hour {
  border-left: 4px solid #17a2b8;
  background: #f8f9ff;
}

.timer-info {
  flex: 1;
}

.timer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.timer-header h4 {
  margin: 0;
  color: #495057;
}

.timer-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
}

.timer-status.running {
  background: #d4edda;
  color: #155724;
}

.timer-status.stopped {
  background: #f8d7da;
  color: #721c24;
}

.timer-status.work-hour {
  background: #d1ecf1;
  color: #0c5460;
}

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

.timer-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.timer-description {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.timer-meta {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  font-size: 12px;
  color: #6c757d;
}

.timer-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.timer-duration {
  font-weight: bold;
  color: #495057 !important;
}

.timer-rate {
  color: #28a745 !important;
  font-weight: bold;
}

.timer-actions {
  display: flex;
  gap: 5px;
  flex-shrink: 0;
}

.loading, .no-data {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

/* Form Styles */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #495057;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

/* Buttons */
.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;
  transition: opacity 0.2s ease;
}

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

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

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

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

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.modal-content {
  max-width: 960px;
  width: 95%;
}

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

/* Make entire application 20% wider */
.container, .main-content, .dashboard, .app {
  max-width: 120% !important;
  width: 120% !important;
}

.modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-height: 90vh;
  overflow-y: auto;
  padding: 24px;
  margin: auto;
}

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

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

.btn:hover {
  opacity: 0.9;
}

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

.duration-value {
  font-weight: 600;
  color: #495057;
  font-family: 'Courier New', monospace;
}

.duration-info {
  font-size: 0.875rem;
  color: #6c757d;
}
</style>
