<script lang="ts">
  import { questions, nextStep } from '../stores/appStore'
  
  let searchTerm = ''
  let selectedPriority = 'all'
  let sortBy = 'order'
  
  $: filteredQuestions = $questions.filter(q => {
    const matchesSearch = q.text.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesPriority = selectedPriority === 'all' || q.priority === selectedPriority
    return matchesSearch && matchesPriority
  }).sort((a, b) => {
    if (sortBy === 'priority') {
      const priorityOrder = { high: 0, medium: 1, low: 2 }
      return priorityOrder[a.priority] - priorityOrder[b.priority]
    }
    return 0 // Keep original order
  })
  
  $: selectedCount = $questions.filter(q => q.selected).length
  
  function toggleQuestion(id: string) {
    questions.update(current => 
      current.map(q => 
        q.id === id ? { ...q, selected: !q.selected } : q
      )
    )
  }
  
  function updatePriority(id: string, priority: 'high' | 'medium' | 'low') {
    questions.update(current => 
      current.map(q => 
        q.id === id ? { ...q, priority } : q
      )
    )
  }
  
  function selectAll() {
    questions.update(current => 
      current.map(q => ({ ...q, selected: true }))
    )
  }
  
  function deselectAll() {
    questions.update(current => 
      current.map(q => ({ ...q, selected: false }))
    )
  }
  
  function proceedToNextStep() {
    if (selectedCount > 0) {
      nextStep()
    }
  }
  
  function getPriorityColor(priority: string) {
    switch (priority) {
      case 'high': return 'from-red-500 to-orange-500'
      case 'medium': return 'from-yellow-500 to-orange-500'
      case 'low': return 'from-green-500 to-blue-500'
      default: return 'from-gray-500 to-gray-600'
    }
  }
  
  function getPriorityBadgeColor(priority: string) {
    switch (priority) {
      case 'high': return 'bg-red-100 text-red-800 border-red-200'
      case 'medium': return 'bg-yellow-100 text-yellow-800 border-yellow-200'
      case 'low': return 'bg-green-100 text-green-800 border-green-200'
      default: return 'bg-gray-100 text-gray-800 border-gray-200'
    }
  }
</script>

<div class="space-y-8">
  <!-- Control Panel -->
  <div class="bg-gradient-to-r from-white/80 to-purple-50/80 backdrop-blur-sm rounded-3xl p-8 border border-purple-200/50 shadow-xl">
    <div class="flex items-center justify-between mb-6">
      <div class="flex items-center space-x-3">
        <div class="w-10 h-10 bg-gradient-to-r from-purple-500 to-pink-600 rounded-xl flex items-center justify-center text-white text-xl">
          🔍
        </div>
        <div>
          <h3 class="text-xl font-bold text-slate-800">Question Selection</h3>
          <p class="text-slate-600">Choose questions to process with AI</p>
        </div>
      </div>
      
      <div class="text-right">
        <div class="text-2xl font-bold text-purple-600">{selectedCount}</div>
        <div class="text-sm text-slate-600">Selected</div>
      </div>
    </div>
    
    <!-- Search and Filters -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <!-- Search -->
      <div class="col-span-2">
        <label class="block text-sm font-medium text-slate-700 mb-2">Search Questions</label>
        <div class="relative">
          <input
            type="text"
            bind:value={searchTerm}
            placeholder="Search by keyword..."
            class="w-full pl-10 pr-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 bg-white/70 backdrop-blur-sm"
          />
          <div class="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400">
            🔍
          </div>
        </div>
      </div>
      
      <!-- Priority Filter -->
      <div>
        <label class="block text-sm font-medium text-slate-700 mb-2">Filter by Priority</label>
        <select
          bind:value={selectedPriority}
          class="w-full py-3 px-4 border border-slate-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 bg-white/70 backdrop-blur-sm"
        >
          <option value="all">All Priorities</option>
          <option value="high">High Priority</option>
          <option value="medium">Medium Priority</option>
          <option value="low">Low Priority</option>
        </select>
      </div>
      
      <!-- Sort -->
      <div>
        <label class="block text-sm font-medium text-slate-700 mb-2">Sort By</label>
        <select
          bind:value={sortBy}
          class="w-full py-3 px-4 border border-slate-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 bg-white/70 backdrop-blur-sm"
        >
          <option value="order">Original Order</option>
          <option value="priority">Priority Level</option>
        </select>
      </div>
    </div>
    
    <!-- Bulk Actions -->
    <div class="flex space-x-4">
      <button
        on:click={selectAll}
        class="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 text-white py-3 px-6 rounded-xl font-semibold hover:from-green-600 hover:to-emerald-700 transition-all duration-300 shadow-lg hover:shadow-xl"
      >
        Select All
      </button>
      <button
        on:click={deselectAll}
        class="flex-1 bg-gradient-to-r from-gray-500 to-gray-600 text-white py-3 px-6 rounded-xl font-semibold hover:from-gray-600 hover:to-gray-700 transition-all duration-300 shadow-lg hover:shadow-xl"
      >
        Deselect All
      </button>
    </div>
  </div>
  
  <!-- Questions List -->
  <div class="space-y-4">
    {#each filteredQuestions as question, index}
      <div class="bg-white/70 backdrop-blur-sm rounded-2xl border border-slate-200/50 shadow-lg hover:shadow-xl transition-all duration-300 overflow-hidden {
        question.selected ? 'ring-2 ring-purple-400 ring-opacity-50' : ''
      }">
        <div class="p-6">
          <div class="flex items-start space-x-4">
            <!-- Selection Checkbox -->
            <div class="flex-shrink-0 pt-1">
              <button
                on:click={() => toggleQuestion(question.id)}
                class="w-6 h-6 rounded-md border-2 flex items-center justify-center transition-all duration-200 {
                  question.selected 
                    ? 'bg-purple-500 border-purple-500 text-white' 
                    : 'border-slate-300 hover:border-purple-400'
                }"
              >
                {#if question.selected}
                  ✓
                {/if}
              </button>
            </div>
            
            <!-- Question Content -->
            <div class="flex-1 min-w-0">
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center space-x-3">
                  <span class="inline-flex items-center justify-center w-8 h-8 bg-purple-100 text-purple-600 rounded-lg text-sm font-bold">
                    {index + 1}
                  </span>
                  <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium border {getPriorityBadgeColor(question.priority)}">
                    {question.priority.toUpperCase()} PRIORITY
                  </span>
                </div>
                
                <!-- Priority Selector -->
                <select
                  value={question.priority}
                  on:change={(e) => updatePriority(question.id, e.target.value)}
                  class="text-sm border border-slate-300 rounded-lg px-3 py-1 bg-white/80 focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
                >
                  <option value="high">High</option>
                  <option value="medium">Medium</option>
                  <option value="low">Low</option>
                </select>
              </div>
              
              <p class="text-slate-700 leading-relaxed text-lg">{question.text}</p>
              
              <!-- Question Stats -->
              <div class="mt-4 flex items-center space-x-6 text-sm text-slate-500">
                <div class="flex items-center space-x-1">
                  <span>📊</span>
                  <span>Estimated AI Processing: 30-45 seconds</span>
                </div>
                <div class="flex items-center space-x-1">
                  <span>🎯</span>
                  <span>Will generate 2-3 citations</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Selected Indicator -->
        {#if question.selected}
          <div class="bg-gradient-to-r {getPriorityColor(question.priority)} px-6 py-3">
            <div class="flex items-center justify-between text-white">
              <div class="flex items-center space-x-2">
                <span>✨</span>
                <span class="font-semibold">Selected for AI Processing</span>
              </div>
              <div class="text-sm opacity-80">
                {question.priority} priority
              </div>
            </div>
          </div>
        {/if}
      </div>
    {/each}
  </div>
  
  <!-- Continue Button -->
  {#if selectedCount > 0}
    <div class="bg-gradient-to-r from-white/80 to-green-50/80 backdrop-blur-sm rounded-3xl p-8 border border-green-200/50 shadow-xl">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="w-10 h-10 bg-gradient-to-r from-green-500 to-emerald-600 rounded-xl flex items-center justify-center text-white text-xl">
            ✅
          </div>
          <div>
            <h3 class="text-xl font-bold text-slate-800">Ready to Process</h3>
            <p class="text-slate-600">{selectedCount} questions selected for AI generation</p>
          </div>
        </div>
        
        <button
          on:click={proceedToNextStep}
          class="bg-gradient-to-r from-green-500 to-emerald-600 text-white px-8 py-4 rounded-2xl font-bold text-lg hover:from-green-600 hover:to-emerald-700 transition-all duration-300 shadow-lg hover:shadow-xl"
        >
          <div class="flex items-center space-x-2">
            <span>🚀</span>
            <span>Start AI Processing</span>
          </div>
        </button>
      </div>
      
      <!-- Processing Preview -->
      <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-white/60 rounded-xl p-4 text-center">
          <div class="text-2xl font-bold text-green-600">{selectedCount}</div>
          <div class="text-sm text-slate-600">Questions to Process</div>
        </div>
        <div class="bg-white/60 rounded-xl p-4 text-center">
          <div class="text-2xl font-bold text-blue-600">{Math.ceil(selectedCount * 0.75)}</div>
          <div class="text-sm text-slate-600">Estimated Minutes</div>
        </div>
        <div class="bg-white/60 rounded-xl p-4 text-center">
          <div class="text-2xl font-bold text-purple-600">{selectedCount * 3}</div>
          <div class="text-sm text-slate-600">Expected Citations</div>
        </div>
      </div>
    </div>
  {:else}
    <div class="bg-gradient-to-r from-white/80 to-orange-50/80 backdrop-blur-sm rounded-3xl p-8 border border-orange-200/50 shadow-xl text-center">
      <div class="w-16 h-16 bg-gradient-to-r from-orange-500 to-red-500 rounded-2xl flex items-center justify-center text-white text-3xl mx-auto mb-4">
        ⚠️
      </div>
      <h3 class="text-xl font-bold text-slate-800 mb-2">No Questions Selected</h3>
      <p class="text-slate-600">Please select at least one question to proceed with AI processing.</p>
    </div>
  {/if}
</div>
