import { defineStore, storeToRefs } from 'pinia'
import { ref } from 'vue'
import type { Submission, SubmissionFile } from '@/types'
import { submissionHelpers } from '@/services/apiService'
import { usePuzzlesStore } from '@/stores/puzzles'
import { errorHelpers } from "@/services/apiService";

export const useSubmissionsStore = defineStore('submissions', () => {
  // State
  const submissions = ref<Submission[]>([])
  const isLoading = ref(false)
  const error = ref<string>('')
  const isSubmissionModalOpen = ref(false)

  const puzzlesStore = usePuzzlesStore()
  const { puzzles } = storeToRefs(puzzlesStore)

  // Actions
  const loadSubmissions = async (limit = 20, offset = 0) => {
    try {
      isLoading.value = true
      error.value = ''

      const loadedSubmissions = await submissionHelpers.loadSubmissions(limit, offset)

      if (offset === 0) {
        submissions.value = loadedSubmissions
      } else {
        submissions.value.push(...loadedSubmissions)
      }
    } catch (err) {
      error.value = 'Failed to load submissions'
      console.error('Error loading submissions:', err)
    } finally {
      isLoading.value = false
    }
  }

  const createSubmission = async (
    files: SubmissionFile[],
    notes?: string,
    manualValidationRequested?: boolean
  ): Promise<Submission | undefined> => {
    try {
      isLoading.value = true
      error.value = ''

      const response = await submissionHelpers.createFromFiles(
        files,
        puzzles.value,
        notes,
        manualValidationRequested
      )

      if (response.error) {
        error.value = response.error
        throw new Error(response.error)
      }

      if (response.data) {
        // Add to local submissions list
        submissions.value.unshift(response.data)
        return response.data
      }

      return undefined
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to create submission'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const openSubmissionModal = () => {
    isSubmissionModalOpen.value = true
  }

  const closeSubmissionModal = () => {
    isSubmissionModalOpen.value = false
  }

  const refreshSubmissions = async () => {
    submissions.value = []
    await loadSubmissions()
  }

  const handleSubmission = async (submissionData: {
    files: any[];
    notes?: string;
    manualValidationRequested?: boolean;
  }) => {
    try {
      isLoading.value = true;
      error.value = "";

      // Create submission via store
      const submission = await createSubmission(
        submissionData.files,
        submissionData.notes,
        submissionData.manualValidationRequested,
      );

      // Show success message
      if (submission) {
        const puzzleNames = submission.responses
          .map((r) => r.puzzle_name)
          .join(", ");

        alert(`Solutions submitted successfully for puzzles: ${puzzleNames}`);

      } else {
        alert("Submission created successfully!");
      }

      // Close modal
      closeSubmissionModal();

    } catch (err) {

      const errorMessage = errorHelpers.getErrorMessage(err);
      error.value = errorMessage;
      alert(`Submission failed: ${errorMessage}`);

      console.error("Submission error:", err);
    } finally {
      isLoading.value = false;
    }
  }

  return {
    // State
    submissions,
    isLoading,
    error,
    isSubmissionModalOpen,

    // Actions
    loadSubmissions,
    createSubmission,
    openSubmissionModal,
    closeSubmissionModal,
    refreshSubmissions,
    handleSubmission
  }
})
