<template>
  <main class="container page-padding">
    <div class="row q-mb-md items-center justify-between">
      <h1 class="mb-3">{{ $t('personalChoresPage.title') }}</h1>
      <button class="btn btn-primary" @click="openCreateChoreModal">
        <span class="material-icons">add</span>
        {{ $t('personalChoresPage.newChoreButton') }}
      </button>
    </div>

    <!-- Chores List -->
    <div class="neo-grid">
      <div v-for="chore in chores" :key="chore.id" class="neo-card">
        <div class="neo-card-header">
          <div class="row items-center justify-between">
            <h3>{{ chore.name }}</h3>
            <span class="neo-chore-frequency" :class="chore.frequency">
              {{ formatFrequency(chore.frequency) }}
            </span>
          </div>
        </div>
        <div class="neo-card-body">
          <div class="neo-chore-info">
            <div class="neo-chore-due">
              {{ $t('personalChoresPage.dates.duePrefix') }}: {{ formatDate(chore.next_due_date) }}
            </div>
            <div v-if="chore.description" class="neo-chore-description">
              {{ chore.description }}
            </div>
          </div>
          <div class="neo-card-actions">
            <button class="btn btn-primary btn-sm" @click="openEditChoreModal(chore)">
              <span class="material-icons">edit</span>
              {{ $t('personalChoresPage.editButton') }}
            </button>
            <button class="btn btn-danger btn-sm" @click="confirmDeleteChore(chore)">
              <span class="material-icons">delete</span>
              {{ $t('personalChoresPage.deleteButton') }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Create/Edit Chore Modal -->
    <div v-if="showChoreModal" class="neo-modal">
      <div class="neo-modal-content">
        <div class="neo-modal-header">
          <h3>{{ isEditing ? $t('personalChoresPage.modals.editChoreTitle') : $t('personalChoresPage.modals.newChoreTitle') }}</h3>
          <button class="btn btn-neutral btn-icon-only" @click="showChoreModal = false">
            <span class="material-icons">close</span>
          </button>
        </div>
        <div class="neo-modal-body">
          <form @submit.prevent="onSubmit" class="neo-form">
            <div class="neo-form-group">
              <label for="name">{{ $t('personalChoresPage.form.nameLabel') }}</label>
              <input
                id="name"
                v-model="choreForm.name"
                type="text"
                class="neo-input"
                required
              />
            </div>

            <div class="neo-form-group">
              <label for="description">{{ $t('personalChoresPage.form.descriptionLabel') }}</label>
              <textarea
                id="description"
                v-model="choreForm.description"
                class="neo-input"
                rows="3"
              ></textarea>
            </div>

            <div class="neo-form-group">
              <label for="frequency">{{ $t('personalChoresPage.form.frequencyLabel') }}</label>
              <select
                id="frequency"
                v-model="choreForm.frequency"
                class="neo-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="neo-form-group">
              <label for="interval">{{ $t('personalChoresPage.form.intervalLabel') }}</label>
              <input
                id="interval"
                v-model.number="choreForm.custom_interval_days"
                type="number"
                class="neo-input"
                min="1"
                required
              />
            </div>

            <div class="neo-form-group">
              <label for="dueDate">{{ $t('personalChoresPage.form.dueDateLabel') }}</label>
              <input
                id="dueDate"
                v-model="choreForm.next_due_date"
                type="date"
                class="neo-input"
                required
              />
            </div>
          </form>
        </div>
        <div class="neo-modal-footer">
          <button class="btn btn-neutral" @click="showChoreModal = false">{{ $t('personalChoresPage.cancelButton') }}</button>
          <button class="btn btn-primary" @click="onSubmit">{{ $t('personalChoresPage.saveButton') }}</button>
        </div>
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div v-if="showDeleteDialog" class="neo-modal">
      <div class="neo-modal-content">
        <div class="neo-modal-header">
          <h3>{{ $t('personalChoresPage.modals.deleteChoreTitle') }}</h3>
          <button class="btn btn-neutral btn-icon-only" @click="showDeleteDialog = false">
            <span class="material-icons">close</span>
          </button>
        </div>
        <div class="neo-modal-body">
          <p>{{ $t('personalChoresPage.deleteDialog.confirmationText') }}</p>
        </div>
        <div class="neo-modal-footer">
          <button class="btn btn-neutral" @click="showDeleteDialog = false">{{ $t('personalChoresPage.cancelButton') }}</button>
          <button class="btn btn-danger" @click="deleteChore">{{ $t('personalChoresPage.deleteButton') }}</button>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { format } from 'date-fns'
import { choreService } from '../services/choreService'
import { useNotificationStore } from '../stores/notifications'
import type { Chore, ChoreCreate, ChoreUpdate, ChoreFrequency } from '../types/chore'

const { t } = useI18n()
const notificationStore = useNotificationStore()

// State
const chores = ref<Chore[]>([])
const showChoreModal = ref(false)
const showDeleteDialog = ref(false)
const isEditing = ref(false)
const selectedChore = ref<Chore | null>(null)

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

const frequencyOptions = computed(() => [
  { label: t('personalChoresPage.frequencies.one_time'), value: 'one_time' as ChoreFrequency },
  { label: t('personalChoresPage.frequencies.daily'), value: 'daily' as ChoreFrequency },
  { label: t('personalChoresPage.frequencies.weekly'), value: 'weekly' as ChoreFrequency },
  { label: t('personalChoresPage.frequencies.monthly'), value: 'monthly' as ChoreFrequency },
  { label: t('personalChoresPage.frequencies.custom'), value: 'custom' as ChoreFrequency }
])

// Methods
const loadChores = async () => {
  try {
    chores.value = await choreService.getPersonalChores()
  } catch (error) {
    console.error('Failed to load personal chores:', error)
    notificationStore.addNotification({
      message: t('personalChoresPage.notifications.loadFailed'),
      type: 'error'
    })
  }
}

const openCreateChoreModal = () => {
  isEditing.value = false
  choreForm.value = {
    name: '',
    description: '',
    frequency: 'daily',
    custom_interval_days: undefined,
    next_due_date: format(new Date(), 'yyyy-MM-dd'),
    type: 'personal'
  }
  showChoreModal.value = true
}

const openEditChoreModal = (chore: Chore) => {
  isEditing.value = true
  selectedChore.value = chore
  choreForm.value = { ...chore, type: 'personal' } // Ensure type is personal
  showChoreModal.value = true
}

const onSubmit = async () => {
  try {
    const payload: ChoreCreate | ChoreUpdate = {
      ...choreForm.value,
      type: 'personal' // Always personal for this page
    };

    if (isEditing.value && selectedChore.value) {
      await choreService.updatePersonalChore(selectedChore.value.id, payload as ChoreUpdate)
      notificationStore.addNotification({
        message: t('personalChoresPage.notifications.updateSuccess'),
        type: 'success'
      })
    } else {
      await choreService.createPersonalChore(payload as ChoreCreate)
      notificationStore.addNotification({
        message: t('personalChoresPage.notifications.createSuccess'),
        type: 'success'
      })
    }
    showChoreModal.value = false
    loadChores()
  } catch (error) {
    console.error('Failed to save personal chore:', error)
    notificationStore.addNotification({
      message: t('personalChoresPage.notifications.saveFailed'), // Generic message
      type: 'error'
    })
  }
}

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

const deleteChore = async () => {
  if (!selectedChore.value) return

  try {
    await choreService.deletePersonalChore(selectedChore.value.id)
    showDeleteDialog.value = false
    notificationStore.addNotification({
      message: t('personalChoresPage.notifications.deleteSuccess'),
      type: 'success'
    })
    loadChores()
  } catch (error) {
    console.error('Failed to delete personal chore:', error)
    notificationStore.addNotification({
      message: t('personalChoresPage.notifications.deleteFailed'),
      type: 'error'
    })
  }
}

const formatDate = (date: string | undefined) => {
    if (!date) return ''; // Or perhaps a specific 'Unknown Date' string if desired: t('personalChoresPage.dates.unknownDate')
    try {
        // Handles both 'YYYY-MM-DD' and full ISO with 'T'
        const parsedDate = new Date(date);
        if (isNaN(parsedDate.getTime())) {
             // Explicitly handle 'YYYY-MM-DD' if new Date() struggles with it directly as local time
            if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
                 const [year, month, day] = date.split('-').map(Number);
                 return format(new Date(year, month - 1, day), 'MMM d, yyyy');
            }
            return t('personalChoresPage.dates.invalidDate');
        }
        return format(parsedDate, 'MMM d, yyyy');
    } catch (e) {
        return t('personalChoresPage.dates.invalidDate');
    }
}

const formatFrequency = (frequency: ChoreFrequency | undefined) => {
  if (!frequency) return t('personalChoresPage.frequencies.unknown');
  // Use the value from frequencyOptions which is now translated
  const option = frequencyOptions.value.find(opt => opt.value === frequency);
  return option ? option.label : t(`personalChoresPage.frequencies.${frequency}`); // Fallback if somehow not in options
}

// Lifecycle
onMounted(() => {
  loadChores()
})
</script>

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

.mb-3 {
  margin-bottom: 1.5rem;
}

/* Neo Grid Layout */
.neo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

/* Neo Card Styles */
.neo-card {
  border-radius: 18px;
  box-shadow: 6px 6px 0 #111;
  background: var(--light);
  border: 3px solid #111;
  overflow: hidden;
}

.neo-card-header {
  padding: 1.5rem;
  border-bottom: 3px solid #111;
  background: #fafafa;
}

.neo-card-header h3 {
  font-weight: 900;
  font-size: 1.25rem;
  margin: 0;
  letter-spacing: 0.5px;
}

.neo-card-body {
  padding: 1.5rem;
}

.neo-card-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

/* Chore Info Styles */
.neo-chore-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.neo-chore-due {
  font-size: 0.875rem;
  color: #666;
}

.neo-chore-description {
  margin-top: 0.5rem;
  color: #444;
}

.neo-chore-frequency {
  font-size: 0.875rem;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-weight: 600;
}

.neo-chore-frequency.one_time { background: #e0e0e0; }
.neo-chore-frequency.daily { background: #bbdefb; color: #1565c0; }
.neo-chore-frequency.weekly { background: #c8e6c9; color: #2e7d32; }
.neo-chore-frequency.monthly { background: #e1bee7; color: #7b1fa2; }
.neo-chore-frequency.custom { background: #ffe0b2; color: #ef6c00; }

/* Modal Styles */
.neo-modal {
  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;
}

.neo-modal-content {
  background: white;
  border-radius: 18px;
  box-shadow: 6px 6px 0 #111;
  border: 3px solid #111;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

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

.neo-modal-body {
  padding: 1.5rem;
}

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

/* Form Styles */
.neo-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.neo-form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.neo-form-group label {
  font-weight: 600;
}

.neo-input {
  padding: 0.75rem;
  border: 2px solid #111;
  border-radius: 8px;
  font-size: 1rem;
  background: white;
}

.neo-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* Button Styles */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: 2px solid #111;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.1s ease-in-out;
}

.btn:hover {
  transform: translateY(-2px);
}

.btn-primary {
  background: var(--primary-color);
  color: white;
}

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

.btn-neutral {
  background: #f8f9fa;
  color: #111;
}

.btn-sm {
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
}

.btn-icon-only {
  padding: 0.5rem;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
  .neo-grid {
    grid-template-columns: 1fr;
  }

  .neo-modal-content {
    width: 95%;
  }
}
</style>
