<template>
  <div class="card bg-base-100 shadow-xl">
    <div class="card-body">
      <h2 class="card-title text-xl mb-6">
        <i class="mdi mdi-check-circle text-2xl text-primary"></i>
        Submit Solution
      </h2>
      
       <form @submit.prevent="handleSubmit" class="space-y-6">
         <!-- Detected Puzzles Summary -->
         <div v-if="Object.keys(responsesByPuzzle).length > 0" class="alert alert-info">
           <i class="mdi mdi-information-outline text-xl"></i>
           <div class="flex-1">
             <h4 class="font-bold">Detected Puzzles ({{ Object.keys(responsesByPuzzle).length }})</h4>
             <div class="text-sm space-y-1 mt-1">
               <div v-for="(data, puzzleName) in responsesByPuzzle" :key="puzzleName" class="flex justify-between">
                 <span>{{ puzzleName }}</span>
                 <span class="badge badge-ghost badge-sm ml-2">{{ data.files.length }} file(s)</span>
               </div>
             </div>
           </div>
         </div>
         
         <!-- File Upload -->
         <FileUpload v-model="submissionFiles" :puzzles="puzzles" />
        
        <!-- Notes -->
        <div class="form-control">
          <div class="flex-1">
            <label class="flex label">
              <span class="label-text font-medium">Notes (Optional)</span>
              <span class="label-text-alt">{{ notesLength }}/500</span>
            </label>
            <textarea 
              v-model="notes"
              class="flex textarea textarea-bordered h-24 w-full resize-none"
              placeholder="Add any notes about your solution, approach, or interesting findings..."
              maxlength="500"
            ></textarea>
          </div>
        </div>
        
        <!-- Submit Button -->
        <div class="card-actions justify-end">
          <button 
            type="submit"
            class="btn btn-primary"
            :disabled="isSubmitting"
          >
            <span v-if="isSubmitting" class="loading loading-spinner loading-sm"></span>
            {{ isSubmitting ? 'Submitting...' : 'Submit Solution' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import FileUpload from './FileUpload.vue'
import type { SteamCollectionItem, SubmissionFile } from '@/types'

interface Props {
  puzzles: SteamCollectionItem[]
  findPuzzleByName: (name: string) => SteamCollectionItem | null
}

interface Emits {
  submit: [submissionData: { files: SubmissionFile[], notes?: string }]
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const submissionFiles = ref<SubmissionFile[]>([])
const notes = ref('')
const isSubmitting = ref(false)

const notesLength = computed(() => notes.value.length)

const canSubmit = computed(() => {
  return submissionFiles.value.length > 0 && 
         !isSubmitting.value
})

// Group files by detected puzzle
const responsesByPuzzle = computed(() => {
  const grouped: Record<string, { puzzle: SteamCollectionItem | null, files: SubmissionFile[] }> = {}
  
  submissionFiles.value.forEach(file => {
    if (file.ocrData?.puzzle) {
      const puzzleName = file.ocrData.puzzle
      if (!grouped[puzzleName]) {
        grouped[puzzleName] = {
          puzzle: props.findPuzzleByName(puzzleName),
          files: []
        }
      }
      grouped[puzzleName].files.push(file)
    }
  })
  
  return grouped
})

const handleSubmit = async () => {
  if (!canSubmit.value) return
  
  isSubmitting.value = true
  
  try {
    // Emit the files and notes for the parent to handle API submission
    emit('submit', {
      files: submissionFiles.value,
      notes: notes.value.trim() || undefined
    })
    
    // Reset form
    submissionFiles.value = []
    notes.value = ''
    
  } catch (error) {
    console.error('Submission error:', error)
  } finally {
    isSubmitting.value = false
  }
}
</script>
