<!--
/**
 * Schedule View - Platform Neutral Scheduling Interface
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */
-->

<template>
  <div class="schedule-view">
    <div class="view-header">
      <div class="header-title-row">
        <button class="back-button" @click="goBack" aria-label="Go back to home">
          ←
        </button>
        <h1 class="page-title">📅 Schedule Notification</h1>
      </div>
      <p class="page-subtitle">Schedule a new daily notification</p>
    </div>
    
    <div class="schedule-form">
      <div class="form-group">
        <label class="form-label">Notification Time</label>
        <input type="time" class="form-input" v-model="scheduleTime" />
      </div>
      
      <div class="form-group">
        <label class="form-label">Title</label>
        <input type="text" class="form-input" v-model="notificationTitle" placeholder="Daily Update" />
      </div>
      
      <div class="form-group">
        <label class="form-label">Message</label>
        <textarea class="form-textarea" v-model="notificationMessage" placeholder="Your daily notification message"></textarea>
      </div>
      
      <div class="form-actions">
        <button class="action-button primary" @click="scheduleNotification" :disabled="isScheduling">
          {{ isScheduling ? 'Scheduling...' : 'Schedule Notification' }}
        </button>
        <button class="action-button secondary" @click="testNotification" :disabled="isTesting">
          {{ isTesting ? 'Testing...' : '🧪 Test Notification (5 seconds)' }}
        </button>
      </div>
      
      <div v-if="scheduleFeedback" class="feedback-message" :class="scheduleFeedback.type">
        {{ scheduleFeedback.message }}
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, toNative } from 'vue-facing-decorator'
import router from '../router'

@Component
class ScheduleView extends Vue {
  scheduleTime = this.getDefaultScheduleTime()
  notificationTitle = 'Daily Update'
  notificationMessage = 'Your daily notification is ready!'
  isScheduling = false
  isTesting = false
  scheduleFeedback: { type: 'success' | 'error' | 'info', message: string } | null = null

  /**
   * Calculate default schedule time as current time + 3 minutes (rounded up)
   * @returns Time string in HH:MM format
   */
  getDefaultScheduleTime(): string {
    const now = new Date()
    // Round up to next minute if there are any seconds
    if (now.getSeconds() > 0 || now.getMilliseconds() > 0) {
      now.setMinutes(now.getMinutes() + 1)
      now.setSeconds(0)
      now.setMilliseconds(0)
    }
    // Add 3 minutes
    now.setMinutes(now.getMinutes() + 3)
    // Format as HH:MM
    const hours = now.getHours().toString().padStart(2, '0')
    const minutes = now.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  }

  goBack() {
    router.push('/')
  }

  async scheduleNotification() {
    this.isScheduling = true
    this.scheduleFeedback = null
    
    try {
      console.log('🔄 Starting notification scheduling...')
      
      // Import and use the real plugin
      const { DailyNotification } = await import('@timesafari/daily-notification-plugin')
      const plugin = DailyNotification
      
      console.log('✅ Plugin loaded:', plugin)
      
      // Calculate when the notification will fire
      const [hours, minutes] = this.scheduleTime.split(':').map(Number)
      const now = new Date()
      const scheduledTime = new Date()
      scheduledTime.setHours(hours, minutes, 0, 0)
      
      // If the time has passed today, schedule for tomorrow
      if (scheduledTime <= now) {
        scheduledTime.setDate(scheduledTime.getDate() + 1)
      }
      
      const options = {
        time: this.scheduleTime,
        title: this.notificationTitle,
        body: this.notificationMessage,
        sound: true,
        priority: 'high' as const
      }
      
      console.log('📅 Scheduling notification with options:', options)
      
      await plugin.scheduleDailyNotification(options)
      
      console.log('✅ Notification scheduled successfully!')
      
      // Show success feedback with timing info
      const timeUntil = scheduledTime.getTime() - now.getTime()
      const hoursUntil = Math.floor(timeUntil / (1000 * 60 * 60))
      const minutesUntil = Math.floor((timeUntil % (1000 * 60 * 60)) / (1000 * 60))
      
      let timeMessage = ''
      if (hoursUntil > 0) {
        timeMessage = `Notification will appear in ${hoursUntil} hour${hoursUntil > 1 ? 's' : ''} and ${minutesUntil} minute${minutesUntil !== 1 ? 's' : ''} (at ${scheduledTime.toLocaleTimeString()})`
      } else {
        timeMessage = `Notification will appear in ${minutesUntil} minute${minutesUntil !== 1 ? 's' : ''} (at ${scheduledTime.toLocaleTimeString()})`
      }
      
      this.scheduleFeedback = {
        type: 'success',
        message: `✅ Notification scheduled successfully! ${timeMessage}. Use "Test Notification" to see one immediately.`
      }
      
    } catch (error) {
      console.error('❌ Failed to schedule notification:', error)
      console.error('❌ Error details:', {
        name: error.name,
        message: error.message,
        stack: error.stack
      })
      
      this.scheduleFeedback = {
        type: 'error',
        message: `❌ Failed to schedule notification: ${error.message}`
      }
    } finally {
      this.isScheduling = false
    }
  }

  async testNotification() {
    this.isTesting = true
    this.scheduleFeedback = null
    
    try {
      console.log('🧪 Testing notification (will fire in 5 seconds)...')
      
      // Import and use the real plugin
      const { DailyNotification } = await import('@timesafari/daily-notification-plugin')
      const plugin = DailyNotification
      
      console.log('✅ Plugin loaded:', plugin)
      
      // Use testAlarm to schedule a notification that fires in 5 seconds
      const result = await plugin.testAlarm({ secondsFromNow: 5 })
      
      console.log('✅ Test notification scheduled:', result)
      
      this.scheduleFeedback = {
        type: 'success',
        message: '✅ Test notification scheduled! It will appear in 5 seconds. Look for it at the top of your screen.'
      }
      
      // Clear feedback after 10 seconds
      setTimeout(() => {
        this.scheduleFeedback = null
      }, 10000)
      
    } catch (error) {
      console.error('❌ Failed to schedule test notification:', error)
      console.error('❌ Error details:', {
        name: error.name,
        message: error.message,
        stack: error.stack
      })
      
      this.scheduleFeedback = {
        type: 'error',
        message: `❌ Failed to schedule test notification: ${error.message}`
      }
    } finally {
      this.isTesting = false
    }
  }
}
export default toNative(ScheduleView)
</script>

<style scoped>
.schedule-view {
  max-width: 600px;
  margin: 0 auto;
}

.view-header {
  text-align: center;
  margin-bottom: 30px;
}

.header-title-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.back-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  height: 40px;
}

.back-button:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateX(-2px);
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: white;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
}

.schedule-form {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 24px;
  backdrop-filter: blur(10px);
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: white;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.4);
}

.form-textarea {
  min-height: 80px;
  resize: vertical;
}

.form-actions {
  margin-top: 24px;
}

.action-button {
  width: 100%;
  padding: 14px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-button.primary {
  background: #1976d2;
  color: white;
}

.action-button.primary:hover:not(:disabled) {
  background: #1565c0;
}

.action-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-button.secondary {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  margin-top: 12px;
}

.action-button.secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
}

.feedback-message {
  margin-top: 16px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
}

.feedback-message.success {
  background: rgba(76, 175, 80, 0.2);
  border: 1px solid rgba(76, 175, 80, 0.4);
  color: #81c784;
}

.feedback-message.error {
  background: rgba(244, 67, 54, 0.2);
  border: 1px solid rgba(244, 67, 54, 0.4);
  color: #e57373;
}

.feedback-message.info {
  background: rgba(33, 150, 243, 0.2);
  border: 1px solid rgba(33, 150, 243, 0.4);
  color: #64b5f6;
}

/* Mobile responsiveness */
@media (max-width: 768px) {
  .schedule-view {
    padding: 16px 0;
  }
  
  .schedule-form {
    padding: 20px;
  }
  
  .header-title-row {
    gap: 8px;
  }
  
  .back-button {
    min-width: 36px;
    height: 36px;
    font-size: 16px;
  }
}
</style>
