<script setup>
import { ref, computed, onMounted } from 'vue'
import { useCollaborationStore } from '../stores/collaboration'

const emit = defineEmits(['session-created'])

const collaborationStore = useCollaborationStore()

const prompt = ref('')
const contextFile = ref(null)
const agentCount = ref(7)
const isCreating = ref(false)
const previousSessions = ref([])
const loadingPreviousSessions = ref(false)

onMounted(async () => {
  loadingPreviousSessions.value = true
  try {
    const response = await fetch('/api/collaborate')
    const data = await response.json()
    previousSessions.value = data.sessions || []
  } catch (error) {
    console.error('Error loading previous sessions:', error)
  } finally {
    loadingPreviousSessions.value = false
  }
})

const handleOpenSession = (sessionId) => {
  emit('session-created', { sessionId })
}

const agentOptions = computed(() => {
  return Array.from({ length: 48 }, (_, i) => ({
    value: i + 3,
    label: `${i + 3} agents`
  }))
})

const handleFileSelect = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    const validTypes = ['text/markdown', 'text/plain', 'application/octet-stream']
    const validExtensions = ['.md', '.txt']
    const hasValidType = validTypes.includes(file.type)
    const hasValidExtension = validExtensions.some(ext => file.name.endsWith(ext))

    if (!hasValidType && !hasValidExtension) {
      alert('Please upload a Markdown (.md) or Text (.txt) file')
      return
    }

    contextFile.value = file
  }
}

const handleCreateSession = async () => {
  if (!prompt.value.trim()) {
    alert('Please enter a project description')
    return
  }

  isCreating.value = true
  try {
    let finalPrompt = prompt.value

    // If a context file was uploaded, prepend it to the prompt
    if (contextFile.value) {
      const fileContent = await contextFile.value.text()
      finalPrompt = `Context file content:\n\`\`\`\n${fileContent}\n\`\`\`\n\nProject description:\n${prompt.value}`
    }

    // Always use 'md' format for output
    const session = await collaborationStore.createSession(
      finalPrompt,
      'md',
      agentCount.value
    )

    emit('session-created', session)

    // Reset form
    prompt.value = ''
    contextFile.value = null
    agentCount.value = 7
  } catch (error) {
    alert(`Error creating session: ${collaborationStore.error}`)
  } finally {
    isCreating.value = false
  }
}

const handleKeydown = (e) => {
  if (e.key === 'Enter' && e.ctrlKey) {
    handleCreateSession()
  }
}

const removeFile = () => {
  contextFile.value = null
}
</script>

<template>
  <div class="collaborative-input">
    <div class="container">
      <header class="header">
        <h1>AI Architecture Design</h1>
        <p class="subtitle">
          Describe your software project. AI specialists collaboratively design
          the architecture through iterative refinement.
        </p>
      </header>

      <form @submit.prevent="handleCreateSession" class="form">
        <!-- Project Description -->
        <div class="form-section">
          <label for="prompt" class="label">Project Description</label>
          <p class="label-hint">
            Describe your software project in detail. What is it? What problems does it solve? What are the key requirements?
          </p>
          <textarea
            id="prompt"
            v-model="prompt"
            @keydown="handleKeydown"
            placeholder="Example: Real-time collaborative document editing platform with multiple users, version history, and commenting..."
            class="textarea"
            rows="8"
          ></textarea>
          <p class="hint">The more detailed your description, the better the AI collaboration.</p>
        </div>

        <!-- Optional Context File -->
        <div class="form-section">
          <label class="label">Context File (Optional)</label>
          <p class="label-hint">
            Upload an existing Markdown or text file to use as context for the AI specialists.
          </p>

          <div class="file-input-wrapper">
            <input
              type="file"
              id="contextFile"
              accept=".md,.txt"
              @change="handleFileSelect"
              class="file-input"
            />
            <label for="contextFile" class="file-label">
              Choose a file (.md or .txt)
            </label>
          </div>

          <div v-if="contextFile" class="file-selected">
            <span class="file-name">{{ contextFile.name }}</span>
            <button
              type="button"
              @click="removeFile"
              class="remove-btn"
            >
              Remove
            </button>
          </div>

          <p class="hint">Optional: Provide existing documentation or requirements to guide the design.</p>
        </div>

        <!-- Agent Count Selection -->
        <div class="form-grid">
          <div class="form-group">
            <label for="agents" class="label">Number of AI Specialists</label>
            <select v-model.number="agentCount" id="agents" class="select">
              <option v-for="opt in agentOptions" :key="opt.value" :value="opt.value">
                {{ opt.label }}
              </option>
            </select>
            <p class="hint">More agents = more diverse perspectives.</p>
          </div>
        </div>

        <!-- Info Box -->
        <div class="info-box">
          <p><strong>Process:</strong></p>
          <ul>
            <li>Lead Architect creates initial design</li>
            <li>{{ agentCount }} specialists review iteratively</li>
            <li>Each proposes improvements based on expertise</li>
            <li>Document evolves through refinement</li>
            <li>Converges when consensus reached</li>
            <li>Output: Markdown architectural specification</li>
          </ul>
        </div>

        <!-- Submit Button -->
        <button
          @click="handleCreateSession"
          :disabled="!prompt.trim() || isCreating"
          type="button"
          class="submit-btn"
        >
          {{ isCreating ? 'Starting...' : 'Start Design Session' }}
        </button>
      </form>

      <!-- Previous Sessions -->
      <div v-if="previousSessions.length > 0" class="previous-sessions-section">
        <h2>Recent Sessions</h2>
        <div class="sessions-grid">
          <div
            v-for="session in previousSessions.slice(0, 6)"
            :key="session.sessionId"
            @click="handleOpenSession(session.sessionId)"
            class="session-card"
            :class="{ 'status-completed': session.status === 'completed' }"
          >
            <div class="session-header">
              <span class="session-id">#{{ session.sessionId }}</span>
              <span class="session-status">{{ session.status }}</span>
            </div>
            <p class="session-prompt">{{ session.prompt.substring(0, 100) }}...</p>
            <p class="session-date">{{ new Date(session.createdAt).toLocaleDateString() }}</p>
          </div>
        </div>
      </div>

      <footer class="footer">
        <p>Typical session: 2-5 rounds for complete consensus. Output format: Markdown</p>
      </footer>
    </div>
  </div>
</template>

<style scoped>
.collaborative-input {
  min-height: 100vh;
  padding: 2rem;
  background: linear-gradient(
    -45deg,
    #0f0c29 0%,
    #302b63 25%,
    #24243e 50%,
    #302b63 75%,
    #0f0c29 100%
  );
  background-size: 400% 400%;
  animation: gradient-shift 15s ease infinite;
  position: relative;
  overflow: hidden;
}

.collaborative-input::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.1) 0%, transparent 50%),
              radial-gradient(circle at 80% 80%, rgba(118, 75, 162, 0.08) 0%, transparent 50%);
  animation: float1 20s ease-in-out infinite;
  pointer-events: none;
  z-index: 0;
}

@keyframes gradient-shift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes float1 {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
    opacity: 0.03;
  }
  25% {
    transform: translate(100px, -100px) rotate(90deg);
    opacity: 0.05;
  }
  50% {
    transform: translate(-50px, 150px) rotate(180deg);
    opacity: 0.03;
  }
  75% {
    transform: translate(-100px, -50px) rotate(270deg);
    opacity: 0.04;
  }
}

.container {
  max-width: 900px;
  margin: 0 auto;
  position: relative;
  z-index: 2;
}

.header {
  text-align: center;
  color: white;
  margin-bottom: 3rem;
}

.header h1 {
  font-size: 2.5rem;
  margin: 0;
  margin-bottom: 0.5rem;
  font-weight: 700;
  letter-spacing: -0.5px;
}

.subtitle {
  font-size: 1.1rem;
  opacity: 0.85;
  margin: 0;
  line-height: 1.6;
}

.form {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 20px;
  padding: 2.5rem;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2);
  margin-bottom: 2rem;
}

.form-section {
  margin-bottom: 2rem;
}

.label {
  display: block;
  font-weight: 600;
  color: white;
  margin-bottom: 0.5rem;
  font-size: 1rem;
}

.label-hint {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.95rem;
  margin: 0 0 0.75rem 0;
}

.textarea {
  width: 100%;
  padding: 1rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-family: inherit;
  font-size: 1rem;
  resize: vertical;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.05);
  color: white;
  backdrop-filter: blur(5px);
}

.textarea::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.textarea:focus {
  outline: none;
  border-color: rgba(102, 126, 234, 0.6);
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1), inset 0 0 20px rgba(102, 126, 234, 0.05);
}

.hint {
  font-size: 0.85rem;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 0.5rem;
  margin-bottom: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.select {
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 1rem;
  background: rgba(255, 255, 255, 0.05);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  backdrop-filter: blur(5px);
}

.select option {
  background: #302b63;
  color: white;
}

.select:focus {
  outline: none;
  border-color: rgba(102, 126, 234, 0.6);
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.info-box {
  background: rgba(102, 126, 234, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.3);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
}

.info-box p {
  margin: 0 0 0.75rem 0;
  color: white;
  font-weight: 600;
}

.info-box ul {
  margin: 0;
  padding-left: 1.5rem;
  color: rgba(255, 255, 255, 0.8);
}

.info-box li {
  margin-bottom: 0.5rem;
}

.submit-btn {
  width: 100%;
  padding: 1.25rem;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.8) 0%, rgba(118, 75, 162, 0.8) 100%);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2);
  backdrop-filter: blur(10px);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.95) 0%, rgba(118, 75, 162, 0.95) 100%);
  box-shadow: 0 12px 40px rgba(102, 126, 234, 0.4);
  border-color: rgba(255, 255, 255, 0.3);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.file-input-wrapper {
  position: relative;
  margin-bottom: 1rem;
}

.file-input {
  display: none;
}

.file-label {
  display: block;
  padding: 1rem;
  border: 2px dashed rgba(102, 126, 234, 0.5);
  border-radius: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(102, 126, 234, 0.05);
  color: rgba(255, 255, 255, 0.8);
  font-weight: 600;
  backdrop-filter: blur(5px);
}

.file-label:hover {
  background: rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.8);
  color: white;
}

.file-input:focus + .file-label {
  border-color: rgba(102, 126, 234, 0.8);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15), inset 0 0 20px rgba(102, 126, 234, 0.05);
}

.file-selected {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  background: rgba(76, 175, 80, 0.15);
  border: 1px solid rgba(76, 175, 80, 0.4);
  border-radius: 8px;
  margin-top: 0.75rem;
  backdrop-filter: blur(5px);
}

.file-name {
  color: rgba(76, 175, 80, 0.9);
  font-weight: 600;
  font-size: 0.95rem;
}

.remove-btn {
  background: none;
  border: none;
  color: rgba(244, 67, 54, 0.7);
  font-size: 0.85rem;
  cursor: pointer;
  padding: 0 0.75rem;
  transition: color 0.3s;
  font-weight: 600;
}

.remove-btn:hover {
  color: rgba(244, 67, 54, 1);
}

.footer {
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.95rem;
}

.previous-sessions-section {
  margin-top: 3rem;
  padding-top: 2rem;
  border-top: 1px solid rgba(102, 126, 234, 0.2);
}

.previous-sessions-section h2 {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: rgba(102, 126, 234, 0.9);
}

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

.session-card {
  padding: 1.25rem;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(102, 126, 234, 0.3);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.session-card:hover {
  background: rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.2);
}

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

.session-id {
  font-weight: 700;
  color: rgba(102, 126, 234, 0.9);
  font-size: 1.1rem;
}

.session-status {
  padding: 0.25rem 0.75rem;
  background: rgba(76, 175, 80, 0.25);
  color: rgba(76, 175, 80, 0.9);
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: capitalize;
}

.session-card.status-completed .session-status {
  background: rgba(76, 175, 80, 0.3);
  color: rgba(76, 175, 80, 0.95);
}

.session-prompt {
  margin: 0.75rem 0;
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  line-height: 1.4;
}

.session-date {
  margin: 0;
  color: rgba(255, 255, 255, 0.5);
  font-size: 0.85rem;
}

@media (max-width: 768px) {
  .collaborative-input {
    padding: 1rem;
  }

  .header h1 {
    font-size: 2rem;
  }

  .form {
    padding: 1.5rem;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>
