<template>
  <main class="neo-container page-padding">
    <div class="neo-list-header">
      <div class="header-left">
        <h1 class="neo-title">Chores</h1>
        <div class="view-tabs">
          <button class="neo-tab-btn" :class="{ active: activeView === 'overdue' }" @click="activeView = 'overdue'"
            :disabled="isLoading">
            <span class="material-icons">warning</span>
            Overdue
            <span v-if="counts.overdue > 0" class="neo-tab-count">{{ counts.overdue }}</span>
          </button>
          <button class="neo-tab-btn" :class="{ active: activeView === 'today' }" @click="activeView = 'today'"
            :disabled="isLoading">
            <span class="material-icons">today</span>
            Today
            <span v-if="counts.today > 0" class="neo-tab-count">{{ counts.today }}</span>
          </button>
          <button class="neo-tab-btn" :class="{ active: activeView === 'upcoming' }" @click="activeView = 'upcoming'"
            :disabled="isLoading">
            <span class="material-icons">upcoming</span>
            Upcoming
          </button>
          <button class="neo-tab-btn" :class="{ active: activeView === 'all' }" @click="activeView = 'all'"
            :disabled="isLoading">
            <span class="material-icons">list</span>
            All Pending
          </button>
          <button class="neo-tab-btn" :class="{ active: activeView === 'completed' }" @click="activeView = 'completed'"
            :disabled="isLoading">
            <span class="material-icons">check_circle</span>
            Completed
          </button>
        </div>
      </div>
      <div class="header-right">
        <div class="neo-view-toggle">
          <button class="neo-toggle-btn" :class="{ active: viewMode === 'calendar' }" @click="viewMode = 'calendar'"
            :disabled="isLoading">
            <span class="material-icons">calendar_month</span>
            Calendar
          </button>
          <button class="neo-toggle-btn" :class="{ active: viewMode === 'list' }" @click="viewMode = 'list'"
            :disabled="isLoading">
            <span class="material-icons">view_list</span>
            List
          </button>
        </div>
        <button class="neo-action-button" @click="openCreateChoreModal(null)" :disabled="isLoading">
          <span class="material-icons">add</span>
          New Chore
        </button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="neo-loading-state">
      <div class="loading-spinner"></div>
      <p>Loading chores...</p>
    </div>

    <!-- Calendar View -->
    <div v-else-if="viewMode === 'calendar'" class="calendar-view">
      <div class="calendar-header">
        <button class="btn btn-icon" @click="previousMonth">
          <span class="material-icons">chevron_left</span>
        </button>
        <h2>{{ currentMonthYear }}</h2>
        <button class="btn btn-icon" @click="nextMonth">
          <span class="material-icons">chevron_right</span>
        </button>
      </div>
      <div class="calendar-grid">
        <div class="calendar-weekdays">
          <div v-for="day in weekDays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="calendar-days">
          <div v-for="(day, index) in calendarDays" :key="index" class="calendar-day" :class="{
            'other-month': !day.isCurrentMonth,
            'today': day.isToday,
            'has-chores': day.chores.length > 0
          }">
            <div class="day-header">
              <span class="day-number">{{ day.date.getDate() }}</span>
              <div v-if="!day.isOtherMonth" class="add-chore-indicator"
                @click.stop="openCreateChoreModal(null, day.date)">+</div>
            </div>
            <div class="day-chores">
              <div v-for="chore in day.chores" :key="chore.id" class="calendar-chore-item"
                :class="{ 'is-completed': chore.is_completed }" @click="openEditChoreModal(chore)">
                <div class="chore-status" :class="getStatusClass(chore)"></div>
                <span class="chore-name">{{ chore.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- List View -->
    <div v-else class="chores-grid">
      <transition-group name="chore-list" tag="div" class="chores-grid">
        <div v-for="chore in filteredChores" :key="chore.id" class="chore-card"
          :class="{ 'is-overdue': !chore.is_completed && isOverdue(chore), 'is-completed': chore.is_completed }">
          <div class="chore-status" :class="getStatusClass(chore)"></div>
          <div class="chore-content">
            <div class="chore-main-info">
              <div class="chore-header">
                <h3>{{ chore.name }}</h3>
                <div class="chore-tags">
                  <span class="chore-type-tag" :class="chore.type">
                    {{ chore.type === 'personal' ? 'Personal' : getGroupName(chore.group_id) || 'Group' }}
                  </span>
                  <span v-if="!chore.is_completed" class="chore-frequency-tag" :class="chore.frequency">
                    {{ formatFrequency(chore.frequency) }}
                  </span>
                </div>
              </div>
              <div class="chore-meta">
                <div v-if="!chore.is_completed" class="chore-due-date" :class="getDueDateClass(chore)">
                  <span class="material-icons">schedule</span>
                  {{ formatDueDate(chore.next_due_date) }}
                </div>
                <div v-else class="chore-completed-date">
                  <span class="material-icons">check_circle_outline</span>
                  Completed: {{ formatDate(chore.completed_at || chore.next_due_date) }}
                </div>
                <div v-if="chore.description" class="chore-description">
                  {{ chore.description }}
                </div>
              </div>
            </div>
            <div class="chore-card-actions">
              <button v-if="!chore.is_completed" class="btn btn-success btn-sm btn-complete"
                @click="toggleChoreCompletion(chore)" title="Mark as Done">
                <span class="material-icons">check_circle</span> Done
              </button>
              <button v-else class="btn btn-warning btn-sm btn-undo" @click="toggleChoreCompletion(chore)"
                title="Mark as Not Done">
                <span class="material-icons">undo</span> Undo
              </button>
              <button class="btn btn-icon" @click="openEditChoreModal(chore)" title="Edit">
                <span class="material-icons">edit</span>
              </button>
              <button class="btn btn-icon btn-danger-icon" @click="confirmDeleteChore(chore)" title="Delete">
                <span class="material-icons">delete</span>
              </button>
            </div>
          </div>
        </div>
      </transition-group>
    </div>

    <!-- Create/Edit Chore Modal -->
    <div v-if="showChoreModal" class="modal-backdrop open" @click.self="showChoreModal = false">
      <div class="modal-container">
        <div class="modal-header">
          <h3>{{ isEditing ? 'Edit Chore' : 'New Chore' }}</h3>
          <button class="btn btn-icon" @click="showChoreModal = false">
            <span class="material-icons">close</span>
          </button>
        </div>
        <form @submit.prevent="onSubmit" class="modal-form">
          <div class="form-group">
            <label for="name">Name</label>
            <input id="name" v-model="choreForm.name" type="text" class="form-input" placeholder="Enter chore name"
              required />
          </div>

          <div class="form-group">
            <label>Type</label>
            <div class="type-selector">
              <button type="button" class="type-btn" :class="{ active: choreForm.type === 'personal' }"
                @click="choreForm.type = 'personal'; choreForm.group_id = undefined">
                <span class="material-icons">person</span>
                Personal
              </button>
              <button type="button" class="type-btn" :class="{ active: choreForm.type === 'group' }"
                @click="choreForm.type = 'group'">
                <span class="material-icons">group</span>
                Group
              </button>
            </div>
          </div>

          <div v-if="choreForm.type === 'group'" class="form-group">
            <label for="group">Group</label>
            <select id="group" v-model="choreForm.group_id" class="form-input" required>
              <option :value="undefined" disabled>Select a group</option>
              <option v-for="group in groups" :key="group.id" :value="group.id">
                {{ group.name }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" v-model="choreForm.description" class="form-input" rows="3"
              placeholder="Add a description (optional)"></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="frequency">Frequency</label>
              <select id="frequency" v-model="choreForm.frequency" class="form-input" required>
                <option v-for="option in frequencyOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>

            <div v-if="choreForm.frequency === 'custom'" class="form-group">
              <label for="interval">Interval (days)</label>
              <input id="interval" v-model.number="choreForm.custom_interval_days" type="number" class="form-input"
                min="1" required />
            </div>
          </div>

          <div class="form-group">
            <label for="dueDate">Due Date</label>
            <div class="quick-due-dates">
              <button type="button" class="btn btn-sm btn-outline" @click="setQuickDueDate('today')">Today</button>
              <button type="button" class="btn btn-sm btn-outline"
                @click="setQuickDueDate('tomorrow')">Tomorrow</button>
              <button type="button" class="btn btn-sm btn-outline" @click="setQuickDueDate('next_week')">Next
                Week</button>
            </div>
            <input id="dueDate" v-model="choreForm.next_due_date" type="date" class="form-input" required />
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-neutral" @click="showChoreModal = false">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div v-if="showDeleteDialog" class="modal-backdrop open" @click.self="showDeleteDialog = false">
      <div class="modal-container delete-confirm">
        <div class="modal-header">
          <h3>Delete Chore</h3>
          <button class="btn btn-icon" @click="showDeleteDialog = false">
            <span class="material-icons">close</span>
          </button>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete this chore? This action cannot be undone.</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-neutral" @click="showDeleteDialog = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteChore">Delete</button>
        </div>
      </div>
    </div>

    <!-- Keyboard Shortcuts Modal -->
    <div v-if="showShortcutsModal" class="modal-backdrop open" @click.self="showShortcutsModal = false">
      <div class="modal-container shortcuts-modal">
        <div class="modal-header">
          <h3>Keyboard Shortcuts</h3>
          <button class="btn btn-icon" @click="showShortcutsModal = false">
            <span class="material-icons">close</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="shortcuts-list">
            <div class="shortcut-item">
              <div class="shortcut-keys">
                <kbd>Ctrl/Cmd</kbd> + <kbd>N</kbd>
              </div>
              <div class="shortcut-description">New Chore</div>
            </div>
            <div class="shortcut-item">
              <div class="shortcut-keys">
                <kbd>Ctrl/Cmd</kbd> + <kbd>/</kbd>
              </div>
              <div class="shortcut-description">Toggle View</div>
            </div>
            <div class="shortcut-item">
              <div class="shortcut-keys">
                <kbd>Ctrl/Cmd</kbd> + <kbd>?</kbd>
              </div>
              <div class="shortcut-description">Show/Hide Shortcuts</div>
            </div>
            <div class="shortcut-item">
              <div class="shortcut-keys">
                <kbd>Esc</kbd>
              </div>
              <div class="shortcut-description">Close Modal</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, watch, onBeforeUnmount } from 'vue'
import { format, startOfDay, addDays, addWeeks, isBefore, isEqual, startOfMonth, endOfMonth, eachDayOfInterval, isSameMonth, isToday as isTodayDate } from 'date-fns'
import { choreService } from '../services/choreService' // Assuming choreService exists
import { useNotificationStore } from '../stores/notifications'
import type { Chore as OriginalChore, ChoreCreate as OriginalChoreCreate, ChoreUpdate, ChoreFrequency } from '../types/chore' // Assuming these types exist
import { useRoute } from 'vue-router'
import { groupService } from '../services/groupService' // Assuming groupService exists
import { useStorage } from '@vueuse/core'

// Extend Chore type to include completion status
interface Chore extends OriginalChore {
  is_completed: boolean;
  completed_at: string | null; // ISO string date when completed
}
interface ChoreCreate extends OriginalChoreCreate {
  is_completed: boolean;
  completed_at: string | null;
}


const notificationStore = useNotificationStore()
const route = useRoute()

// State
const chores = ref<Chore[]>([])
const groups = ref<{ id: number, name: string }[]>([])
const showChoreModal = ref(false)
const showDeleteDialog = ref(false)
const isEditing = ref(false)
const selectedChore = ref<Chore | null>(null)
const showShortcutsModal = ref(false)

const cachedChores = useStorage<Chore[]>('cached-chores-v2', []) // Changed key to avoid conflicts with old cache
const cachedTimestamp = useStorage<number>('cached-chores-timestamp-v2', 0)
const CACHE_DURATION = 5 * 60 * 1000;

const loadCachedData = () => {
  const now = Date.now();
  if (cachedChores.value.length > 0 && (now - cachedTimestamp.value) < CACHE_DURATION) {
    chores.value = cachedChores.value.map(c => ({ // Ensure cached items have new properties
      ...c,
      is_completed: c.is_completed || false,
      completed_at: c.completed_at || null
    }));
  }
};

const choreForm = ref<ChoreCreate>({
  name: '',
  description: '',
  frequency: 'daily',
  custom_interval_days: undefined,
  next_due_date: format(new Date(), 'yyyy-MM-dd'),
  type: 'personal',
  group_id: undefined,
  is_completed: false,
  completed_at: null,
})

const getGroupName = (groupId?: number | null): string | undefined => {
  if (!groupId) return undefined;
  return groups.value.find(g => g.id === groupId)?.name;
};

const frequencyOptions = [
  { label: 'One Time', value: 'one_time' as ChoreFrequency },
  { label: 'Daily', value: 'daily' as ChoreFrequency },
  { label: 'Weekly', value: 'weekly' as ChoreFrequency },
  { label: 'Monthly', value: 'monthly' as ChoreFrequency },
  { label: 'Custom', value: 'custom' as ChoreFrequency }
]

// Add loading state
const isLoading = ref(true)

const loadChores = async () => {
  isLoading.value = true
  try {
    const fetchedChores = await choreService.getAllChores() as OriginalChore[]
    chores.value = fetchedChores.map(c => ({
      ...c,
      is_completed: (c as Chore).is_completed || false,
      completed_at: (c as Chore).completed_at || null,
    }))
    cachedChores.value = chores.value
    cachedTimestamp.value = Date.now()
  } catch (error) {
    console.error('Failed to load all chores:', error)
    notificationStore.addNotification({ message: 'Failed to load chores', type: 'error' })
    if (cachedChores.value.length === 0) chores.value = []
  } finally {
    isLoading.value = false
  }
}

// Calendar state
const viewMode = ref<'calendar' | 'list'>('calendar')
const currentDate = ref(new Date())

const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

const currentMonthYear = computed(() => {
  return format(currentDate.value, 'MMMM yyyy')
})

const calendarDays = computed(() => {
  const start = startOfMonth(currentDate.value)
  const end = endOfMonth(currentDate.value)

  // Get the first day of the month and adjust to start from Sunday
  const firstDay = start.getDay()
  const startDate = addDays(start, -firstDay)

  // Get the last day of the month and adjust to end on Saturday
  const lastDay = end.getDay()
  const endDate = addDays(end, 6 - lastDay)

  const days = eachDayOfInterval({ start: startDate, end: endDate })

  return days.map(date => {
    const dayChores = chores.value.filter(chore => {
      if (chore.is_completed) return false
      const choreDate = startOfDay(new Date(chore.next_due_date))
      return isEqual(choreDate, startOfDay(date))
    })

    return {
      date,
      isCurrentMonth: isSameMonth(date, currentDate.value),
      isToday: isTodayDate(date),
      isOtherMonth: !isSameMonth(date, currentDate.value),
      chores: dayChores
    }
  })
})

const previousMonth = () => {
  currentDate.value = addDays(startOfMonth(currentDate.value), -1)
}

const nextMonth = () => {
  currentDate.value = addDays(endOfMonth(currentDate.value), 1)
}

const openCreateChoreModal = (groupId: number | null, date?: Date) => {
  console.log('Opening create modal', { groupId, date }) // Debug log
  isEditing.value = false
  choreForm.value = {
    name: '',
    description: '',
    frequency: 'daily',
    custom_interval_days: undefined,
    next_due_date: date ? format(date, 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
    type: groupId ? 'group' : 'personal',
    group_id: groupId ?? undefined,
    is_completed: false,
    completed_at: null,
  }
  showChoreModal.value = true
}

const openEditChoreModal = (chore: Chore) => {
  console.log('Opening edit modal', chore) // Debug log
  isEditing.value = true
  selectedChore.value = chore
  choreForm.value = {
    name: chore.name,
    description: chore.description,
    frequency: chore.frequency,
    custom_interval_days: chore.custom_interval_days,
    next_due_date: chore.next_due_date ? format(new Date(chore.next_due_date), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
    type: chore.type,
    group_id: chore.group_id,
    is_completed: chore.is_completed,
    completed_at: chore.completed_at,
  }
  showChoreModal.value = true
}

const onSubmit = async () => {
  if (!validateForm()) return

  try {
    const choreData: ChoreCreate | ChoreUpdate = { ...choreForm.value }

    if (choreData.frequency !== 'custom') {
      choreData.custom_interval_days = undefined
    }

    let notificationMessage = ''

    if (isEditing.value && selectedChore.value) {
      await choreService.updateChore(selectedChore.value.id, choreData as ChoreUpdate)
      notificationMessage = `Chore updated successfully`
    } else {
      await choreService.createChore(choreData as ChoreCreate)
      notificationMessage = `Chore created successfully`
    }

    notificationStore.addNotification({ message: notificationMessage, type: 'success' })
    showChoreModal.value = false
    loadChores()
  } catch (error) {
    console.error('Failed to save chore:', error)
    notificationStore.addNotification({ message: `Failed to ${isEditing.value ? 'update' : 'create'} chore`, type: 'error' })
  }
}

const confirmDeleteChore = (chore: Chore) => {
  selectedChore.value = chore
  showDeleteDialog.value = true
}

const deleteChore = async () => {
  if (!selectedChore.value) return;
  try {
    await choreService.deleteChore(selectedChore.value.id, selectedChore.value.type, selectedChore.value.group_id);
    showDeleteDialog.value = false;
    notificationStore.addNotification({ message: `Chore deleted successfully`, type: 'success' })
    loadChores()
  } catch (error) {
    console.error('Failed to delete chore:', error);
    notificationStore.addNotification({ message: 'Failed to delete chore', type: 'error' })
  }
}

const formatDate = (dateString: string | null): string => {
  if (!dateString) return 'N/A';
  try {
    // Handle 'yyyy-MM-dd' or full ISO string
    return format(new Date(dateString.replace(/-/g, '/')), 'MMM d, yyyy'); // Replace for cross-browser date parsing
  } catch (e) {
    return 'Invalid Date';
  }
}

const formatFrequency = (frequency: ChoreFrequency) => {
  const option = frequencyOptions.find(opt => opt.value === frequency)
  return option ? option.label : frequency
}

const loadGroups = async () => {
  try {
    groups.value = await groupService.getUserGroups();
  } catch (error) {
    console.error('Failed to load groups:', error);
    notificationStore.addNotification({ message: 'Failed to load groups', type: 'error' });
  }
};

const activeView = ref('today') // Default to 'today' or 'overdue' might be better

const today = computed(() => startOfDay(new Date()));

const isOverdue = (chore: Chore) => {
  if (chore.is_completed) return false;
  const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
  return isBefore(dueDate, today.value);
};

const filteredChores = computed(() => {
  let result: Chore[];
  const pendingChores = chores.value.filter(c => !c.is_completed)
    .sort((a, b) => new Date(a.next_due_date).getTime() - new Date(b.next_due_date).getTime());
  const completedChoresList = chores.value.filter(c => c.is_completed)
    .sort((a, b) => new Date(b.completed_at || 0).getTime() - new Date(a.completed_at || 0).getTime());

  switch (activeView.value) {
    case 'overdue':
      result = pendingChores.filter(chore => isOverdue(chore));
      break;
    case 'today':
      result = pendingChores.filter(chore => {
        const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
        return isEqual(dueDate, today.value);
      });
      break;
    case 'upcoming':
      result = pendingChores.filter(chore => {
        const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
        return isBefore(today.value, dueDate);
      });
      break;
    case 'completed':
      result = completedChoresList;
      break;
    default: // 'all' (all pending)
      result = pendingChores;
  }
  return result;
});

const counts = computed(() => {
  const pending = chores.value.filter(c => !c.is_completed);
  return {
    overdue: pending.filter(chore => isOverdue(chore)).length,
    today: pending.filter(chore => {
      const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
      return isEqual(dueDate, today.value);
    }).length,
  };
});

const getStatusClass = (chore: Chore) => {
  if (chore.is_completed) return 'completed';
  if (isOverdue(chore)) return 'overdue';
  const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
  if (isEqual(dueDate, today.value)) return 'today';
  return 'upcoming';
}

const getDueDateClass = (chore: Chore) => {
  if (chore.is_completed) return '';
  if (isOverdue(chore)) return 'overdue';
  const dueDate = startOfDay(new Date(chore.next_due_date.replace(/-/g, '/')));
  if (isEqual(dueDate, today.value)) return 'today';
  return 'upcoming';
}

const formatDueDate = (dateString: string) => {
  const dueDate = startOfDay(new Date(dateString.replace(/-/g, '/')));
  if (isEqual(dueDate, today.value)) return 'Due Today';

  const tomorrow = addDays(today.value, 1);
  if (isEqual(dueDate, tomorrow)) return 'Due Tomorrow';

  if (isBefore(dueDate, today.value)) return `Overdue: ${formatDate(dateString)}`;

  return `Due ${formatDate(dateString)}`;
}

const toggleChoreCompletion = async (choreToToggle: Chore) => {
  choreToToggle.is_completed = !choreToToggle.is_completed;
  if (choreToToggle.is_completed) {
    choreToToggle.completed_at = new Date().toISOString();
    // For recurring chores, choreService.completeChore would ideally update next_due_date.
    // For this example, we'll just toggle the status.
    // await choreService.completeChore(choreToToggle.id, choreToToggle.type, choreToToggle.group_id); // Placeholder
    notificationStore.addNotification({ message: `${choreToToggle.name} marked as done.`, type: 'success' });

  } else {
    choreToToggle.completed_at = null;
    // If un-completing, you might need a service call to revert next_due_date if it was advanced.
    // await choreService.undoCompleteChore(choreToToggle.id, choreToToggle.type, choreToToggle.group_id); // Placeholder
    notificationStore.addNotification({ message: `${choreToToggle.name} marked as not done.`, type: 'info' });
  }
  // Optimistically update local state, then persist
  const index = chores.value.findIndex(c => c.id === choreToToggle.id);
  if (index !== -1) {
    chores.value[index] = { ...choreToToggle }; // Ensure reactivity
  }
  // Persist the change (if your service expects the whole object)
  try {
    await choreService.updateChore(choreToToggle.id, choreToToggle as ChoreUpdate); // This service might need adjustment
    // No need to call loadChores() if updateChore returns the updated chore or if optimistic update is enough
  } catch (error) {
    console.error("Failed to update chore completion status:", error);
    // Revert optimistic update on error
    choreToToggle.is_completed = !choreToToggle.is_completed;
    choreToToggle.completed_at = choreToToggle.is_completed ? new Date().toISOString() : null;
    if (index !== -1) chores.value[index] = { ...choreToToggle };
    notificationStore.addNotification({ message: 'Failed to update chore status.', type: 'error' });
  }
  cachedChores.value = [...chores.value]; // Update cache after toggle
};


const setQuickDueDate = (when: 'today' | 'tomorrow' | 'next_week') => {
  let date = startOfDay(new Date());
  if (when === 'tomorrow') date = addDays(date, 1);
  if (when === 'next_week') date = addWeeks(date, 1);
  choreForm.value.next_due_date = format(date, 'yyyy-MM-dd');
};

// Modify handleKeyPress to include shortcuts modal toggle
const handleKeyPress = (event: KeyboardEvent) => {
  // Only handle shortcuts when not in an input field
  if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
    return
  }

  // Ctrl/Cmd + N for new chore
  if ((event.ctrlKey || event.metaKey) && event.key === 'n') {
    event.preventDefault()
    openCreateChoreModal(null)
  }

  // Ctrl/Cmd + / to toggle view mode
  if ((event.ctrlKey || event.metaKey) && event.key === '/') {
    event.preventDefault()
    viewMode.value = viewMode.value === 'calendar' ? 'list' : 'calendar'
  }

  // Ctrl/Cmd + ? to toggle shortcuts modal
  if ((event.ctrlKey || event.metaKey) && event.key === '?') {
    event.preventDefault()
    showShortcutsModal.value = !showShortcutsModal.value
  }

  // Escape to close modals
  if (event.key === 'Escape') {
    if (showChoreModal.value) {
      showChoreModal.value = false
    }
    if (showDeleteDialog.value) {
      showDeleteDialog.value = false
    }
    if (showShortcutsModal.value) {
      showShortcutsModal.value = false
    }
  }
}

// Add keyboard event listeners
onMounted(() => {
  window.addEventListener('keydown', handleKeyPress)
  loadCachedData()
  loadChores()
  loadGroups()
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyPress)
})

// Improve form validation
const validateForm = () => {
  if (!choreForm.value.name.trim()) {
    notificationStore.addNotification({ message: 'Please enter a chore name', type: 'error' })
    return false
  }

  if (choreForm.value.type === 'group' && !choreForm.value.group_id) {
    notificationStore.addNotification({ message: 'Please select a group', type: 'error' })
    return false
  }

  if (choreForm.value.frequency === 'custom' && (!choreForm.value.custom_interval_days || choreForm.value.custom_interval_days < 1)) {
    notificationStore.addNotification({ message: 'Please enter a valid interval', type: 'error' })
    return false
  }

  return true
}

// Add auto-save functionality for form
let autoSaveTimeout: number | null = null

const autoSaveForm = () => {
  if (autoSaveTimeout) {
    clearTimeout(autoSaveTimeout)
  }
  autoSaveTimeout = window.setTimeout(() => {
    if (isEditing.value && selectedChore.value) {
      onSubmit()
    }
  }, 2000) // Auto-save after 2 seconds of inactivity
}

// Modify choreForm to trigger auto-save
watch(choreForm, () => {
  if (isEditing.value) {
    autoSaveForm()
  }
}, { deep: true })

// Add confirmation before leaving with unsaved changes
const hasUnsavedChanges = ref(false)

watch(choreForm, () => {
  hasUnsavedChanges.value = true
}, { deep: true })

onBeforeUnmount(() => {
  if (hasUnsavedChanges.value) {
    const confirm = window.confirm('You have unsaved changes. Are you sure you want to leave?')
    if (!confirm) {
      // Prevent navigation
      return false
    }
  }
})

// Watch for modal state changes
watch(showChoreModal, (newVal) => {
  console.log('Chore modal visibility changed:', newVal)
})

watch(showDeleteDialog, (newVal) => {
  console.log('Delete dialog visibility changed:', newVal)
})

watch(showShortcutsModal, (newVal) => {
  console.log('Shortcuts modal visibility changed:', newVal)
})
</script>

<style>
/* Modal styles - not scoped to allow for fixed positioning */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 12px;
  border: 3px solid #111;
  box-shadow: 6px 6px 0 #111;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

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

.modal-header h3 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 2px solid #111;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

/* Form styles */
.modal-form {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: #333;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #111;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.2s ease;
  background: white;
}

.form-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.form-input::placeholder {
  color: #999;
}

/* Type selector styles */
.type-selector {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.type-btn {
  flex: 1;
  padding: 0.75rem;
  border: 2px solid #111;
  border-radius: 8px;
  background: white;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.2s ease;
}

.type-btn:hover {
  background: #f8f9fa;
}

.type-btn.active {
  background: #111;
  color: white;
}

/* Quick due dates styles */
.quick-due-dates {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.btn-outline {
  padding: 0.5rem 1rem;
  border: 2px solid #111;
  border-radius: 6px;
  background: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-outline:hover {
  background: #f8f9fa;
}

/* Button styles */
.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-primary {
  background: #111;
  color: white;
  border: 2px solid #111;
}

.btn-primary:hover {
  background: #333;
}

.btn-neutral {
  background: white;
  color: #333;
  border: 2px solid #111;
}

.btn-neutral:hover {
  background: #f8f9fa;
}

.btn-icon {
  padding: 0.5rem;
  border: none;
  background: transparent;
  color: #666;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-icon:hover {
  color: #333;
}

/* Dark mode support for modals and forms */
@media (prefers-color-scheme: dark) {
  .modal-container {
    background: #1a1a1a;
    border-color: #fff;
    box-shadow: 6px 6px 0 #fff;
  }

  .modal-header,
  .modal-footer {
    border-color: #fff;
  }

  .form-group label {
    color: #fff;
  }

  .form-input {
    background: #2a2a2a;
    border-color: #fff;
    color: #fff;
  }

  .form-input::placeholder {
    color: #666;
  }

  .type-btn {
    background: #2a2a2a;
    border-color: #fff;
    color: #fff;
  }

  .type-btn:hover {
    background: #333;
  }

  .type-btn.active {
    background: #fff;
    color: #111;
  }

  .btn-outline {
    background: #2a2a2a;
    border-color: #fff;
    color: #fff;
  }

  .btn-outline:hover {
    background: #333;
  }

  .btn-neutral {
    background: #2a2a2a;
    color: #fff;
    border-color: #fff;
  }

  .btn-neutral:hover {
    background: #333;
  }

  .btn-icon {
    color: #999;
  }

  .btn-icon:hover {
    color: #fff;
  }
}
</style>

<style scoped>
/* Base container styles */
.neo-container {
  padding: 1rem;
  max-width: 1200px;
  margin: 0 auto;
}

.page-padding {
  padding: 1rem;
  max-width: 1200px;
  margin: 0 auto;
}

/* Header styles */
.neo-list-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 2rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: white;
  border-radius: 18px;
  border: 3px solid #111;
  box-shadow: 6px 6px 0 #111;
}

.header-left {
  flex: 1;
  min-width: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-shrink: 0;
}

.neo-title {
  font-size: 2.5rem;
  font-weight: 900;
  margin: 0 0 1rem 0;
  line-height: 1.2;
  color: #111;
}

/* Tab styles */
.view-tabs {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-bottom: 0.5rem;
}

.neo-tab-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.6rem 1rem;
  border: 2px solid #111;
  background: #f5f5f5;
  color: #333;
  font-weight: 600;
  font-size: 0.9rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 2px 2px 0 #111;
}

.neo-tab-btn .material-icons {
  font-size: 1.1rem;
}

.neo-tab-btn:hover {
  transform: translateY(-1px);
  box-shadow: 3px 3px 0 #111;
}

.neo-tab-btn.active {
  background: #111;
  color: white;
  box-shadow: 3px 3px 0 #111;
}

.neo-tab-count {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 0.1em 0.5em;
  border-radius: 1rem;
  font-size: 0.8rem;
  font-weight: 600;
  min-width: 1.5rem;
  text-align: center;
}

.neo-tab-btn:not(.active) .neo-tab-count {
  background: #e0e0e0;
  color: #333;
}

/* View toggle styles */
.neo-view-toggle {
  display: flex;
  gap: 0.5rem;
  background: #f5f5f5;
  padding: 0.25rem;
  border-radius: 8px;
  border: 2px solid #111;
}

.neo-toggle-btn {
  border: none;
  background: transparent;
  color: #333;
  padding: 0.5rem 1rem;
  font-weight: 600;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.neo-toggle-btn:hover {
  background: #e9ecef;
}

.neo-toggle-btn.active {
  background: #111;
  color: white;
}

/* Action button styles */
.neo-action-button {
  background: #fff;
  border: 3px solid #111;
  border-radius: 8px;
  padding: 0.6rem 1rem;
  font-weight: 700;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: 3px 3px 0 #111;
  transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
}

.neo-action-button:hover {
  transform: translateY(-2px);
  box-shadow: 3px 5px 0 #111;
}

.neo-action-button:active {
  transform: translateY(0);
  box-shadow: 2px 2px 0 #111;
}

.neo-action-button .material-icons {
  font-size: 1.2rem;
}

/* Loading state styles */
.neo-loading-state {
  text-align: center;
  padding: 3rem 1rem;
  margin: 2rem 0;
  border: 3px solid #111;
  border-radius: 18px;
  background: #fff;
  box-shadow: 6px 6px 0 #111;
}

/* Responsive styles */
@media (max-width: 768px) {
  .neo-list-header {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
  }

  .header-right {
    width: 100%;
    justify-content: space-between;
  }

  .neo-title {
    font-size: 1.8rem;
  }

  .view-tabs {
    overflow-x: auto;
    padding-bottom: 0.5rem;
    margin: 0 -0.5rem;
    padding: 0 0.5rem;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }

  .view-tabs::-webkit-scrollbar {
    display: none;
  }

  .neo-tab-btn {
    white-space: nowrap;
  }

  .neo-view-toggle {
    flex: 1;
    justify-content: center;
  }

  .neo-action-button {
    flex: 1;
    justify-content: center;
  }
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  .neo-list-header {
    background: #1a1a1a;
    border-color: #fff;
    box-shadow: 6px 6px 0 #fff;
  }

  .neo-title {
    color: #fff;
  }

  .neo-tab-btn {
    background: #2a2a2a;
    border-color: #fff;
    color: #fff;
    box-shadow: 2px 2px 0 #fff;
  }

  .neo-tab-btn:hover {
    box-shadow: 3px 3px 0 #fff;
  }

  .neo-tab-btn.active {
    background: #fff;
    color: #111;
  }

  .neo-tab-btn:not(.active) .neo-tab-count {
    background: #333;
    color: #fff;
  }

  .neo-view-toggle {
    background: #2a2a2a;
    border-color: #fff;
  }

  .neo-toggle-btn {
    color: #fff;
  }

  .neo-toggle-btn:hover {
    background: #333;
  }

  .neo-toggle-btn.active {
    background: #fff;
    color: #111;
  }

  .neo-action-button {
    background: #2a2a2a;
    border-color: #fff;
    color: #fff;
    box-shadow: 3px 3px 0 #fff;
  }

  .neo-action-button:hover {
    box-shadow: 3px 5px 0 #fff;
  }
}

/* Calendar View Styles */
.calendar-view {
  background: white;
  border-radius: 18px;
  border: 3px solid #111;
  box-shadow: 6px 6px 0 #111;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

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

.calendar-header h2 {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0;
}

.calendar-grid {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.weekday {
  text-align: center;
  font-weight: 600;
  color: #666;
  padding: 0.5rem;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0.5rem;
}

.calendar-day {
  aspect-ratio: 1;
  border: 2px solid #111;
  border-radius: 12px;
  padding: 0.5rem;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  transition: all 0.2s ease;
}

.calendar-day:hover {
  transform: translateY(-2px);
  box-shadow: 3px 3px 0 #111;
}

.calendar-day.other-month {
  opacity: 0.5;
  background: #eee;
}

.calendar-day.today {
  background: #fff;
  border-color: #007bff;
}

.calendar-day.has-chores {
  background: #fff;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.day-number {
  font-weight: 600;
  font-size: 1.1rem;
}

.add-chore-indicator {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary);
  font-size: 1.2rem;
  font-weight: 300;
  opacity: 0;
  transition: all 0.2s ease;
  cursor: pointer;
}

.calendar-day:hover .add-chore-indicator {
  opacity: 0.7;
}

.add-chore-indicator:hover {
  color: #f57c00;
  opacity: 1;
  transform: translateY(-50%) scale(1.1);
}

.btn-sm {
  padding: 0.2rem;
  min-width: 28px;
  height: 28px;
  background: transparent;
  border: 1px solid #ddd;
  color: #666;
  transition: all 0.2s ease;
}

.btn-sm:hover {
  background: #f8f9fa;
  border-color: #ccc;
  color: #333;
}

.btn-sm .material-icons {
  font-size: 1.1rem;
}

.calendar-day:hover .btn-sm {
  border-color: #ccc;
}

.day-chores {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.calendar-chore-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.25rem 0.5rem;
  background: white;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.calendar-chore-item:hover {
  background: #f8f9fa;
  transform: translateX(2px);
}

.calendar-chore-item.is-completed {
  opacity: 0.6;
  text-decoration: line-through;
}

.chore-status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.chore-status.overdue {
  background: #dc3545;
}

.chore-status.today {
  background: #007bff;
}

.chore-status.upcoming {
  background: #28a745;
}

.chore-status.completed {
  background: #6c757d;
}

/* List View Styles */
.chores-grid {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 2rem;
  width: 100%;
}

.chore-card {
  background: white;
  border-radius: 12px;
  border: 2px solid #111;
  box-shadow: 3px 3px 0 #111;
  padding: 1rem 1.5rem;
  display: flex;
  gap: 1rem;
  transition: all 0.2s ease;
  align-items: center;
}

.chore-card:hover {
  transform: translateY(-1px);
  box-shadow: 4px 4px 0 #111;
}

.chore-card.is-overdue {
  border-color: #dc3545;
}

.chore-card.is-completed {
  opacity: 0.7;
}

.chore-content {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.chore-main-info {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.chore-header {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.chore-header h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chore-tags {
  display: flex;
  gap: 0.5rem;
  flex-wrap: nowrap;
}

.chore-type-tag,
.chore-frequency-tag {
  padding: 0.2rem 0.6rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  font-weight: 600;
  white-space: nowrap;
}

.chore-type-tag.personal {
  background: #e3f2fd;
  color: #1976d2;
}

.chore-type-tag.group {
  background: #f3e5f5;
  color: #7b1fa2;
}

.chore-frequency-tag {
  background: #e8f5e9;
  color: #2e7d32;
}

.chore-meta {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  min-width: max-content;
}

.chore-due-date,
.chore-completed-date {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.85rem;
  white-space: nowrap;
}

.chore-due-date.overdue {
  color: #dc3545;
}

.chore-due-date.today {
  color: #007bff;
}

.chore-description {
  font-size: 0.85rem;
  color: #666;
  margin-left: 1rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.chore-card-actions {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
  flex-shrink: 0;
}

/* Dark Mode Support for List View */
@media (prefers-color-scheme: dark) {
  .chore-card {
    background: #1a1a1a;
    border-color: #fff;
    box-shadow: 3px 3px 0 #fff;
  }

  .chore-card:hover {
    box-shadow: 4px 4px 0 #fff;
  }

  .chore-description {
    color: #999;
  }
}

/* Responsive Styles for List View */
@media (max-width: 768px) {
  .chores-grid {
    padding: 0;
  }

  .chore-card {
    padding: 0.75rem 1rem;
  }

  .chore-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.75rem;
  }

  .chore-main-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.75rem;
    width: 100%;
  }

  .chore-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    width: 100%;
  }

  .chore-meta {
    width: 100%;
    justify-content: space-between;
  }

  .chore-description {
    max-width: none;
    margin-left: 0;
  }

  .chore-card-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* Transition Animations */
.chore-list-enter-active,
.chore-list-leave-active {
  transition: all 0.3s ease;
}

.chore-list-enter-from,
.chore-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.chore-list-move {
  transition: transform 0.3s ease;
}

/* Keyboard Shortcuts Modal Styles */
.shortcuts-modal {
  max-width: 500px;
}

.shortcuts-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.shortcut-item {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  padding: 0.75rem;
  background: #f5f5f5;
  border-radius: 8px;
  border: 2px solid #111;
}

.shortcut-keys {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  min-width: 120px;
}

.shortcut-description {
  font-weight: 500;
  color: #333;
}

kbd {
  background: white;
  border: 2px solid #111;
  border-radius: 4px;
  padding: 0.2rem 0.5rem;
  font-family: monospace;
  font-size: 0.9rem;
  box-shadow: 2px 2px 0 #111;
}

/* Dark Mode Support for Shortcuts Modal */
@media (prefers-color-scheme: dark) {
  .shortcut-item {
    background: #2a2a2a;
    border-color: #fff;
  }

  .shortcut-description {
    color: #fff;
  }

  kbd {
    background: #1a1a1a;
    border-color: #fff;
    box-shadow: 2px 2px 0 #fff;
  }
}

/* Remove old keyboard shortcuts help styles */
.keyboard-shortcuts-help,
.shortcuts-tooltip {
  display: none;
}
</style>