<template>
  <div class="p-6">
    <h1 class="text-[1.75rem] font-bold font-[family-name:var(--font-heading)] tracking-tight text-text-primary mb-6">Entries</h1>

    <!-- Filters -->
    <div class="bg-bg-surface rounded-lg p-4 mb-6 flex flex-wrap items-end gap-4">
      <div>
        <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Start Date</label>
        <AppDatePicker
          v-model="startDate"
          placeholder="Start date"
        />
      </div>
      <div>
        <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">End Date</label>
        <AppDatePicker
          v-model="endDate"
          placeholder="End date"
        />
      </div>
      <div>
        <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Project</label>
        <AppSelect
          v-model="filterProject"
          :options="projectsStore.projects"
          label-key="name"
          value-key="id"
          placeholder="All Projects"
          :placeholder-value="null"
        />
      </div>
      <button
        @click="applyFilters"
        class="px-4 py-2 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
      >
        Apply
      </button>
      <button
        @click="clearFilters"
        class="text-text-secondary text-xs hover:text-text-primary transition-colors"
      >
        Clear
      </button>
    </div>

    <!-- Entries Table -->
    <div v-if="filteredEntries.length > 0" class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b border-border-subtle bg-bg-surface">
            <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Date</th>
            <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Project</th>
            <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Task</th>
            <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Description</th>
            <th class="px-4 py-3 text-right text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Duration</th>
            <th class="px-4 py-3 w-20"></th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="entry in filteredEntries"
            :key="entry.id"
            class="group border-b border-border-subtle hover:bg-bg-elevated transition-colors duration-150"
          >
            <td class="px-4 py-3 text-[0.75rem] text-text-primary">
              {{ formatDate(entry.start_time) }}
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <div
                  class="w-2 h-2 rounded-full shrink-0"
                  :style="{ backgroundColor: getProjectColor(entry.project_id) }"
                />
                <span class="text-[0.75rem] text-text-primary">{{ getProjectName(entry.project_id) }}</span>
              </div>
            </td>
            <td class="px-4 py-3 text-[0.75rem] text-text-secondary">
              {{ getTaskName(entry.task_id) || '-' }}
            </td>
            <td class="px-4 py-3 text-[0.75rem] text-text-secondary">
              {{ entry.description || '-' }}
            </td>
            <td class="px-4 py-3 text-right text-[0.75rem] font-mono text-accent-text">
              {{ formatDuration(entry.duration) }}
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-100">
                <button
                  @click="openEditDialog(entry)"
                  class="p-1.5 text-text-tertiary hover:text-text-secondary transition-colors duration-150"
                  title="Edit"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </button>
                <button
                  @click="confirmDelete(entry)"
                  class="p-1.5 text-text-tertiary hover:text-status-error transition-colors duration-150"
                  title="Delete"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div v-else class="flex flex-col items-center justify-center py-16">
      <ListIcon class="w-12 h-12 text-text-tertiary" :stroke-width="1.5" />
      <p class="text-sm text-text-secondary mt-4">No entries found</p>
      <p class="text-xs text-text-tertiary mt-2 max-w-xs text-center">Time entries will appear here as you track your work. Try adjusting the date range if you have existing entries.</p>
      <router-link to="/timer" class="mt-4 px-4 py-2 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors">
        Go to Timer
      </router-link>
    </div>

    <!-- Edit Dialog -->
    <div
      v-if="showEditDialog"
      class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center z-50"
      @click.self="closeEditDialog"
    >
      <div class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-md mx-4 p-6 animate-modal-enter">
        <h2 class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-4">Edit Entry</h2>

        <form @submit.prevent="handleEdit" class="space-y-4">
          <!-- Project -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Project *</label>
            <AppSelect
              v-model="editForm.project_id"
              :options="projectsStore.projects"
              label-key="name"
              value-key="id"
              placeholder="Select project"
            />
          </div>

          <!-- Description -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Description</label>
            <input
              v-model="editForm.description"
              type="text"
              class="w-full px-3 py-2 bg-bg-inset border border-border-subtle rounded-lg text-[0.8125rem] text-text-primary focus:outline-none focus:border-border-visible"
              placeholder="What did you work on?"
            />
          </div>

          <!-- Duration -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Duration (minutes)</label>
            <AppNumberInput
              v-model="durationMinutes"
              :min="1"
              :step="1"
              suffix="min"
            />
          </div>

          <!-- Start Time -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Start Time</label>
            <input
              v-model="editForm.start_time"
              type="datetime-local"
              class="w-full px-3 py-2 bg-bg-inset border border-border-subtle rounded-lg text-[0.8125rem] text-text-primary focus:outline-none focus:border-border-visible"
            />
          </div>

          <!-- Buttons -->
          <div class="flex justify-end gap-3 pt-4">
            <button
              type="button"
              @click="closeEditDialog"
              class="px-4 py-2 border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors duration-150"
            >
              Cancel
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-accent text-bg-base font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
            >
              Save
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div
      v-if="showDeleteDialog"
      class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center z-50"
      @click.self="cancelDelete"
    >
      <div class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-sm mx-4 p-6 animate-modal-enter">
        <h2 class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-2">Delete Entry</h2>
        <p class="text-[0.75rem] text-text-secondary mb-6">
          Are you sure you want to delete this time entry? This action cannot be undone.
        </p>
        <div class="flex justify-end gap-3">
          <button
            @click="cancelDelete"
            class="px-4 py-2 border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors duration-150"
          >
            Cancel
          </button>
          <button
            @click="handleDelete"
            class="px-4 py-2 border border-status-error text-status-error font-medium rounded-lg hover:bg-status-error/10 transition-colors duration-150"
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { List as ListIcon } from 'lucide-vue-next'
import AppNumberInput from '../components/AppNumberInput.vue'
import AppSelect from '../components/AppSelect.vue'
import AppDatePicker from '../components/AppDatePicker.vue'
import { useEntriesStore, type TimeEntry } from '../stores/entries'
import { useProjectsStore } from '../stores/projects'

const entriesStore = useEntriesStore()
const projectsStore = useProjectsStore()

// Filter state
const startDate = ref('')
const endDate = ref('')
const filterProject = ref<number | null>(null)

// Dialog state
const showEditDialog = ref(false)
const showDeleteDialog = ref(false)
const editingEntry = ref<TimeEntry | null>(null)
const entryToDelete = ref<TimeEntry | null>(null)

// Edit form
const editForm = reactive<TimeEntry>({
  id: 0,
  project_id: 0,
  description: '',
  start_time: '',
  duration: 0
})

// Duration in minutes (computed for editing)
const durationMinutes = computed({
  get: () => Math.round(editForm.duration / 60),
  set: (val: number) => { editForm.duration = val * 60 }
})

// Filtered entries based on date range and project
const filteredEntries = computed(() => {
  let result = [...entriesStore.entries]

  // Filter by project
  if (filterProject.value !== null) {
    result = result.filter(e => e.project_id === filterProject.value)
  }

  // Filter by date range
  if (startDate.value) {
    const start = new Date(startDate.value)
    result = result.filter(e => new Date(e.start_time) >= start)
  }

  if (endDate.value) {
    const end = new Date(endDate.value)
    end.setHours(23, 59, 59)
    result = result.filter(e => new Date(e.start_time) <= end)
  }

  // Sort by date descending
  result.sort((a, b) => new Date(b.start_time).getTime() - new Date(a.start_time).getTime())

  return result
})

// Get project name by ID
function getProjectName(projectId: number): string {
  const project = projectsStore.projects.find(p => p.id === projectId)
  return project?.name || 'Unknown Project'
}

// Get project color by ID
function getProjectColor(projectId: number): string {
  const project = projectsStore.projects.find(p => p.id === projectId)
  return project?.color || '#6B7280'
}

// Get task name by ID
function getTaskName(taskId?: number): string {
  if (!taskId) return ''
  return ''
}

// Format duration from seconds to readable format
function formatDuration(seconds: number): string {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return `${hours}h ${minutes}m`
  }
  return `${minutes}m`
}

// Format date
function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })
}

// Apply filters
function applyFilters() {
  entriesStore.fetchEntries(startDate.value || undefined, endDate.value || undefined)
}

// Clear filters
function clearFilters() {
  startDate.value = ''
  endDate.value = ''
  filterProject.value = null
  entriesStore.fetchEntries()
}

// Open edit dialog
function openEditDialog(entry: TimeEntry) {
  editingEntry.value = entry
  editForm.id = entry.id || 0
  editForm.project_id = entry.project_id
  editForm.description = entry.description || ''
  editForm.start_time = entry.start_time.slice(0, 16) // Format for datetime-local
  editForm.duration = entry.duration
  showEditDialog.value = true
}

// Close edit dialog
function closeEditDialog() {
  showEditDialog.value = false
  editingEntry.value = null
}

// Handle edit submit
async function handleEdit() {
  if (editingEntry.value) {
    // Recalculate end_time based on duration
    const start = new Date(editForm.start_time)
    const end = new Date(start.getTime() + editForm.duration * 1000)

    const updatedEntry: TimeEntry = {
      id: editForm.id,
      project_id: editForm.project_id,
      description: editForm.description || undefined,
      start_time: start.toISOString(),
      end_time: end.toISOString(),
      duration: editForm.duration
    }

    await entriesStore.updateEntry(updatedEntry)
    closeEditDialog()
  }
}

// Confirm delete
function confirmDelete(entry: TimeEntry) {
  entryToDelete.value = entry
  showDeleteDialog.value = true
}

// Cancel delete
function cancelDelete() {
  showDeleteDialog.value = false
  entryToDelete.value = null
}

// Handle delete
async function handleDelete() {
  if (entryToDelete.value?.id) {
    await entriesStore.deleteEntry(entryToDelete.value.id)
  }
  cancelDelete()
}

// Load data on mount
onMounted(async () => {
  await Promise.all([
    entriesStore.fetchEntries(),
    projectsStore.fetchProjects()
  ])

  // Set default date range to this week
  const now = new Date()
  const weekStart = new Date(now)
  weekStart.setDate(now.getDate() - now.getDay() + 1)
  startDate.value = weekStart.toISOString().split('T')[0]
  endDate.value = now.toISOString().split('T')[0]
})
</script>
