<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useProjectsStore } from '@/stores/projects'
import Button from '@/components/common/Button.vue'
import Modal from '@/components/common/Modal.vue'

const router = useRouter()
const projectsStore = useProjectsStore()

const showNewProjectModal = ref(false)
const newProjectName = ref('')
const newProjectDescription = ref('')
const creating = ref(false)

onMounted(async () => {
  await projectsStore.fetchProjects()
})

function openProject(projectId: string) {
  router.push(`/projects/${projectId}`)
}

async function createProject() {
  if (!newProjectName.value.trim()) return

  creating.value = true
  try {
    const project = await projectsStore.createProject(
      newProjectName.value.trim(),
      newProjectDescription.value.trim()
    )
    showNewProjectModal.value = false
    newProjectName.value = ''
    newProjectDescription.value = ''
    openProject(project.id)
  } catch (e) {
    console.error('Failed to create project:', e)
  } finally {
    creating.value = false
  }
}

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

<template>
  <div class="dashboard">
    <div class="dashboard__header">
      <div>
        <h1 class="dashboard__title">Your Projects</h1>
        <p class="dashboard__subtitle">
          {{ projectsStore.projects.length }} project{{ projectsStore.projects.length !== 1 ? 's' : '' }}
        </p>
      </div>
      <Button variant="primary" @click="showNewProjectModal = true">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="12" y1="5" x2="12" y2="19"/>
          <line x1="5" y1="12" x2="19" y2="12"/>
        </svg>
        New Project
      </Button>
    </div>

    <div v-if="projectsStore.loading" class="dashboard__loading">
      <div class="dashboard__spinner"></div>
      <p>Loading projects...</p>
    </div>

    <div v-else-if="projectsStore.projects.length === 0" class="dashboard__empty">
      <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
        <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
      </svg>
      <h2>No projects yet</h2>
      <p>Create your first project to start organizing your documents</p>
      <Button variant="primary" @click="showNewProjectModal = true">
        Create First Project
      </Button>
    </div>

    <div v-else class="dashboard__grid">
      <article
        v-for="project in projectsStore.projects"
        :key="project.id"
        class="project-card"
        @click="openProject(project.id)"
      >
        <div class="project-card__icon">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
          </svg>
        </div>
        <div class="project-card__content">
          <h3 class="project-card__name">{{ project.name }}</h3>
          <p v-if="project.description" class="project-card__desc">
            {{ project.description }}
          </p>
          <p class="project-card__date">
            Updated {{ formatDate(project.updated_at) }}
          </p>
        </div>
        <svg class="project-card__arrow" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="m9 18 6-6-6-6"/>
        </svg>
      </article>
    </div>

    <Modal :show="showNewProjectModal" title="Create New Project" @close="showNewProjectModal = false">
      <form @submit.prevent="createProject">
        <div class="form__field">
          <label for="project-name" class="form__label">Project Name</label>
          <input
            id="project-name"
            v-model="newProjectName"
            type="text"
            class="form__input"
            placeholder="My Research Project"
            autofocus
          />
        </div>
        <div class="form__field">
          <label for="project-desc" class="form__label">Description (optional)</label>
          <textarea
            id="project-desc"
            v-model="newProjectDescription"
            class="form__textarea"
            placeholder="Brief description of your project..."
            rows="3"
          ></textarea>
        </div>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showNewProjectModal = false">Cancel</Button>
        <Button variant="primary" :loading="creating" @click="createProject">Create Project</Button>
      </template>
    </Modal>
  </div>
</template>

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

.dashboard__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
}

.dashboard__title {
  margin: 0;
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
}

.dashboard__subtitle {
  margin: 0.25rem 0 0;
  font-size: 0.9375rem;
  color: var(--text-secondary);
}

.dashboard__loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem;
  color: var(--text-secondary);
}

.dashboard__spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.dashboard__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem 2rem;
  text-align: center;
  color: var(--text-secondary);
}

.dashboard__empty h2 {
  margin: 0;
  font-size: 1.25rem;
  color: var(--text-primary);
}

.dashboard__empty p {
  margin: 0;
  max-width: 320px;
}

.dashboard__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 1.25rem;
}

.project-card {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1.25rem;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.15s;
}

.project-card:hover {
  border-color: var(--accent);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.project-card__icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary);
  border-radius: 10px;
  color: var(--accent);
}

.project-card__content {
  flex: 1;
  min-width: 0;
}

.project-card__name {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.project-card__desc {
  margin: 0.375rem 0 0;
  font-size: 0.875rem;
  color: var(--text-secondary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-card__date {
  margin: 0.5rem 0 0;
  font-size: 0.8125rem;
  color: var(--text-secondary);
}

.project-card__arrow {
  flex-shrink: 0;
  color: var(--text-secondary);
  opacity: 0;
  transition: opacity 0.15s;
}

.project-card:hover .project-card__arrow {
  opacity: 1;
}

/* Form styles (used in modal) */
.form__field {
  margin-bottom: 1.25rem;
}

.form__field:last-child {
  margin-bottom: 0;
}

.form__label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
}

.form__input,
.form__textarea {
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.9375rem;
  font-family: inherit;
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.15s, box-shadow 0.15s;
  box-sizing: border-box;
}

.form__input::placeholder,
.form__textarea::placeholder {
  color: var(--text-secondary);
}

.form__input:focus,
.form__textarea:focus {
  border-color: var(--accent);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form__textarea {
  resize: vertical;
  min-height: 80px;
}
</style>
