<template>
  <div class="p-6">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-[1.75rem] font-bold font-[family-name:var(--font-heading)] tracking-tight text-text-primary">Projects</h1>
      <button
        @click="openCreateDialog"
        class="px-3 py-1.5 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
      >
        + Add
      </button>
    </div>

    <!-- Projects Grid -->
    <div v-if="projectsStore.projects.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <div
        v-for="project in projectsStore.projects"
        :key="project.id"
        class="group bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] hover:bg-bg-elevated transition-all duration-150 cursor-pointer"
        @click="openEditDialog(project)"
      >
        <div class="flex border-l-[2px] hover:border-l-[3px] rounded-l-lg transition-all duration-150" :style="{ borderLeftColor: project.color }">
          <div class="flex-1 p-4">
            <div class="flex items-start justify-between">
              <div>
                <h3 class="text-[0.8125rem] font-semibold text-text-primary">{{ project.name }}</h3>
                <p class="text-xs text-text-secondary mt-0.5">{{ getClientName(project.client_id) }} · {{ formatCurrency(project.hourly_rate) }}/hr</p>
              </div>
              <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-100">
                <button
                  @click.stop="openEditDialog(project)"
                  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.stop="confirmDelete(project)"
                  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>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else class="flex flex-col items-center justify-center py-16">
      <FolderKanban class="w-12 h-12 text-text-tertiary" :stroke-width="1.5" />
      <p class="text-sm text-text-secondary mt-4">No projects yet</p>
      <p class="text-xs text-text-tertiary mt-2 max-w-xs text-center">Projects organize your time entries and set billing rates for clients.</p>
      <button
        @click="openCreateDialog"
        class="mt-4 px-4 py-2 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors"
      >
        Create Project
      </button>
    </div>

    <!-- Create/Edit Dialog -->
    <div
      v-if="showDialog"
      class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center p-4 z-50"
      @click.self="closeDialog"
    >
      <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 p-6 animate-modal-enter max-h-[calc(100vh-2rem)] overflow-y-auto">
        <h2 class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-4">
          {{ editingProject ? 'Edit Project' : 'Create Project' }}
        </h2>

        <form @submit.prevent="handleSubmit" class="space-y-4">
          <!-- Name -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Name *</label>
            <input
              v-model="formData.name"
              type="text"
              required
              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="Project name"
            />
          </div>

          <!-- Client -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Client</label>
            <AppSelect
              v-model="formData.client_id"
              :options="clientsStore.clients"
              label-key="name"
              value-key="id"
              placeholder="No client"
              :placeholder-value="undefined"
            />
          </div>

          <!-- Hourly Rate -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Hourly Rate ({{ getCurrencySymbol() }})</label>
            <AppNumberInput
              v-model="formData.hourly_rate"
              :min="0"
              :step="1"
              :precision="2"
              :prefix="getCurrencySymbol()"
            />
          </div>

          <!-- Color -->
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Color</label>
            <div class="flex gap-2 mb-2">
              <button
                v-for="c in colorPresets"
                :key="c"
                @click.prevent="formData.color = c"
                class="w-6 h-6 rounded-full border-2 transition-colors"
                :class="formData.color === c ? 'border-text-primary' : 'border-transparent'"
                :style="{ backgroundColor: c }"
              />
            </div>
            <div class="flex items-center gap-3">
              <input
                v-model="formData.color"
                type="color"
                class="w-8 h-8 rounded-lg cursor-pointer border border-border-subtle"
              />
              <input
                v-model="formData.color"
                type="text"
                class="flex-1 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="#D97706"
              />
            </div>
          </div>

          <!-- Buttons -->
          <div class="flex justify-end gap-3 pt-4">
            <button
              type="button"
              @click="closeDialog"
              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"
            >
              {{ editingProject ? 'Update' : 'Create' }}
            </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 p-4 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 p-6 animate-modal-enter">
        <h2 class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-2">Delete Project</h2>
        <p class="text-[0.75rem] text-text-secondary mb-6">
          Are you sure you want to delete "{{ projectToDelete?.name }}"? 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, onMounted } from 'vue'
import { FolderKanban } from 'lucide-vue-next'
import AppNumberInput from '../components/AppNumberInput.vue'
import AppSelect from '../components/AppSelect.vue'
import { useProjectsStore, type Project } from '../stores/projects'
import { useClientsStore } from '../stores/clients'
import { useSettingsStore } from '../stores/settings'
import { formatCurrency, getCurrencySymbol } from '../utils/locale'

const colorPresets = ['#D97706', '#3B82F6', '#8B5CF6', '#EC4899', '#10B981', '#EF4444', '#06B6D4', '#6B7280']

const projectsStore = useProjectsStore()
const clientsStore = useClientsStore()
const settingsStore = useSettingsStore()

// Dialog state
const showDialog = ref(false)
const showDeleteDialog = ref(false)
const editingProject = ref<Project | null>(null)
const projectToDelete = ref<Project | null>(null)

// Form data
const formData = reactive<Project>({
  name: '',
  client_id: undefined,
  hourly_rate: 0,
  color: '#D97706',
  archived: false
})

// Get client name by ID
function getClientName(clientId?: number): string {
  if (!clientId) return 'No client'
  const client = clientsStore.clients.find(c => c.id === clientId)
  return client?.name || 'Unknown client'
}

// Open create dialog
function openCreateDialog() {
  editingProject.value = null
  formData.name = ''
  formData.client_id = undefined
  formData.hourly_rate = parseFloat(settingsStore.settings.hourly_rate) || 0
  formData.color = '#F59E0B'
  formData.archived = false
  showDialog.value = true
}

// Open edit dialog
function openEditDialog(project: Project) {
  editingProject.value = project
  formData.id = project.id
  formData.name = project.name
  formData.client_id = project.client_id
  formData.hourly_rate = project.hourly_rate
  formData.color = project.color
  formData.archived = project.archived
  showDialog.value = true
}

// Close dialog
function closeDialog() {
  showDialog.value = false
  editingProject.value = null
}

// Handle form submit
async function handleSubmit() {
  if (editingProject.value) {
    // Update project
    await projectsStore.updateProject({ ...formData })
  } else {
    // Create project
    await projectsStore.createProject({ ...formData })
  }
  closeDialog()
}

// Confirm delete
function confirmDelete(project: Project) {
  projectToDelete.value = project
  showDeleteDialog.value = true
}

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

// Handle delete
async function handleDelete() {
  if (projectToDelete.value?.id) {
    await projectsStore.deleteProject(projectToDelete.value.id)
  }
  cancelDelete()
}

// Load data on mount
onMounted(async () => {
  await Promise.all([
    projectsStore.fetchProjects(),
    clientsStore.fetchClients(),
    settingsStore.fetchSettings()
  ])
})
</script>
