import { create } from 'zustand'

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export type MatchStatus =
  | 'unmatched'   // STEP file uploaded but no order item linked yet
  | 'matched'     // STEP file linked to one or more order items
  | 'processing'  // Celery is currently processing the STEP file
  | 'done'        // Processing complete (thumbnail + glTF available)
  | 'error'       // Processing failed

export interface PendingUpload {
  /** UUID returned by POST /api/uploads/step */
  cad_file_id: string
  /** Original filename as shown to the user */
  original_name: string
  /** SHA-256 hash of the file content (for deduplication display) */
  file_hash: string
  /** Whether this was a fresh upload or already existed in the DB */
  upload_status: 'uploaded' | 'already_exists'
  /** Current match state with order items */
  match_status: MatchStatus
  /** IDs of order items that reference this CAD file */
  matched_item_ids: string[]
  /** ISO timestamp of the upload action */
  uploaded_at: string
}

interface UploadState {
  /** All STEP uploads tracked in this browser session */
  pendingUploads: PendingUpload[]

  /** Add or update a tracked upload (keyed by cad_file_id) */
  addUpload: (upload: Omit<PendingUpload, 'matched_item_ids' | 'match_status' | 'uploaded_at'>) => void

  /** Update the match status of a tracked upload */
  setMatchStatus: (cad_file_id: string, status: MatchStatus) => void

  /** Record that a CAD file has been linked to an order item */
  addMatchedItem: (cad_file_id: string, item_id: string) => void

  /** Remove a linked order item from a tracked upload */
  removeMatchedItem: (cad_file_id: string, item_id: string) => void

  /** Remove a tracked upload entirely (e.g. after the order is submitted) */
  removeUpload: (cad_file_id: string) => void

  /** Clear all tracked uploads */
  clearUploads: () => void
}

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

export const useUploadStore = create<UploadState>((set) => ({
  pendingUploads: [],

  addUpload: (upload) =>
    set((state) => {
      const existing = state.pendingUploads.find(
        (u) => u.cad_file_id === upload.cad_file_id,
      )
      if (existing) {
        // Refresh upload_status but keep existing match info
        return {
          pendingUploads: state.pendingUploads.map((u) =>
            u.cad_file_id === upload.cad_file_id
              ? { ...u, upload_status: upload.upload_status }
              : u,
          ),
        }
      }
      const newEntry: PendingUpload = {
        ...upload,
        match_status: 'unmatched',
        matched_item_ids: [],
        uploaded_at: new Date().toISOString(),
      }
      return { pendingUploads: [...state.pendingUploads, newEntry] }
    }),

  setMatchStatus: (cad_file_id, status) =>
    set((state) => ({
      pendingUploads: state.pendingUploads.map((u) =>
        u.cad_file_id === cad_file_id ? { ...u, match_status: status } : u,
      ),
    })),

  addMatchedItem: (cad_file_id, item_id) =>
    set((state) => ({
      pendingUploads: state.pendingUploads.map((u) => {
        if (u.cad_file_id !== cad_file_id) return u
        if (u.matched_item_ids.includes(item_id)) return u
        const matched_item_ids = [...u.matched_item_ids, item_id]
        return {
          ...u,
          matched_item_ids,
          match_status: 'matched' as MatchStatus,
        }
      }),
    })),

  removeMatchedItem: (cad_file_id, item_id) =>
    set((state) => ({
      pendingUploads: state.pendingUploads.map((u) => {
        if (u.cad_file_id !== cad_file_id) return u
        const matched_item_ids = u.matched_item_ids.filter((id) => id !== item_id)
        return {
          ...u,
          matched_item_ids,
          match_status: matched_item_ids.length === 0
            ? ('unmatched' as MatchStatus)
            : u.match_status,
        }
      }),
    })),

  removeUpload: (cad_file_id) =>
    set((state) => ({
      pendingUploads: state.pendingUploads.filter(
        (u) => u.cad_file_id !== cad_file_id,
      ),
    })),

  clearUploads: () => set({ pendingUploads: [] }),
}))
