<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 />

        <!-- Manual Selection Warning -->
        <div
          v-if="submissionFilesNeedingManualSelection.length > 0"
          class="alert alert-warning"
        >
          <i class="mdi mdi-alert-circle text-xl"></i>
          <div class="flex-1">
            <div class="font-bold">Manual Puzzle Selection Required</div>
            <div class="text-sm">
              {{ submissionFilesNeedingManualSelection.length }} file(s) have
              low OCR confidence for puzzle names. Please select the correct
              puzzle for each file before submitting.
            </div>

            <button
              class="btn mt-3 w-full"
              @click="processLowConfidenceOCRFiles"
            >
              <span class="mdi mdi-reload text-2xl"></span>
              Retry OCR on low confidence puzzle
            </button>
          </div>
        </div>

        <!-- 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>

        <!-- Manual Validation Request -->
        <div class="form-control">
          <label class="label cursor-pointer justify-start gap-3">
            <input
              type="checkbox"
              v-model="manualValidationRequested"
              class="checkbox checkbox-primary"
              :disabled="hasLowConfidence"
            />
            <div class="flex-1">
              <span class="label-text font-medium"
                >Request manual validation</span
              >
              <div class="label-text-alt text-xs opacity-70 mt-1">
                Check this if you want an admin to manually review your
                submission, even if OCR confidence is high.
                <br />
                <em
                  >Note: This will be automatically checked if any OCR
                  confidence is below 80%.</em
                >
              </div>
            </div>
          </label>
        </div>

        <!-- Submit Button -->
        <div class="card-actions justify-end">
          <button type="submit" class="btn btn-primary" :disabled="!canSubmit">
            <span
              v-if="isSubmitting"
              class="loading loading-spinner loading-sm"
            ></span>
            <span v-if="isSubmitting">Submitting...</span>
            <span v-else-if="submissionFilesNeedingManualSelection.length > 0">
              Select Puzzles ({{ submissionFilesNeedingManualSelection.length }}
              remaining)
            </span>
            <span v-else>Submit Solution</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import FileUpload from "@/components/FileUpload.vue";
import type { SteamCollectionItem, SubmissionFile } from "@/types";
import { useUploadsStore } from "@/stores/uploads";
import { useSubmissionsStore } from "@/stores/submissions";
import { storeToRefs } from "pinia";

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

const props = defineProps<Props>();

const uploadsStore = useUploadsStore();
const {
  submissionFiles,
  hasLowConfidence,
  submissionFilesNeedingManualSelection,
} = storeToRefs(uploadsStore);
const { clearFiles, processLowConfidenceOCRFiles } = uploadsStore;
const { handleSubmission } = useSubmissionsStore();

const notes = ref("");
const manualValidationRequested = ref(false);
const isSubmitting = ref(false);

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

const canSubmit = computed(() => {
  const hasFiles = submissionFiles.value.length > 0;
  const noManualSelectionNeeded = !submissionFiles.value.some(
    (file) => file.needsManualPuzzleSelection,
  );

  return hasFiles && !isSubmitting.value && noManualSelectionNeeded;
});

watch(hasLowConfidence, (newValue) => {
  if (newValue) {
    manualValidationRequested.value = true;
  }
});

// Group files by detected puzzle
const responsesByPuzzle = computed(() => {
  const grouped: Record<
    string,
    { puzzle: SteamCollectionItem | null; files: SubmissionFile[] }
  > = {};

  submissionFiles.value.forEach((file) => {
    // Use manual puzzle selection if available, otherwise fall back to OCR
    const puzzleName = file.manualPuzzleSelection || file.ocrData?.puzzle;

    if (puzzleName) {
      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 store to handle API submission
    handleSubmission({
      files: submissionFiles.value,
      notes: notes.value.trim() || undefined,
      manualValidationRequested:
        hasLowConfidence.value || manualValidationRequested.value,
    });

    // Reset form
    clearFiles();
    notes.value = "";
    manualValidationRequested.value = false;
  } catch (error) {
    console.error("Submission error:", error);
  } finally {
    isSubmitting.value = false;
  }
};
</script>
