import { ref, reactive } from 'vue';
import { UploadSettings } from '@/data/config';
//types import

import type { Ref } from 'vue';
import type { UploadsData, UploadFileData, ThumbnailData } from '@/types';

export function createEmptyThumbnailData(): ThumbnailData {
  return {
    input: ref(null),
    preview: ref(''),
    deleteTrigger: ref(false),
    oldPreviewState: ref(false),
    uploadState: ref(false),
    previewState: ref(false),
    displayedName: ref(''),
  };
}

// For regular files (reactive plain object)
export function createEmptyUploadFileData(): UploadFileData {
  return reactive({
    input: null,
    preview: '',
    deleteTrigger: false,
    oldPreviewState: false,
    uploadState: false,
    previewState: false,
    displayedName: '',
  });
}
// Handle regular file input (PDF, DOC, etc.)
export function onPlainFileChange(event: Event, fileData: UploadFileData) {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (!file) return;

  fileData.input = file;
  fileData.uploadState = true;
  fileData.displayedName = file.name;
  fileData.preview = URL.createObjectURL(file);
  fileData.previewState = true;

  console.log('[onPlainFileChange] Uploaded:', file.name);
}

// Handle thumbnail file input (image only)
export function onThumbnailChange(event: Event, fileData: ThumbnailData) {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (!file) {
    console.warn('[onThumbnailChange] No file selected');
    return;
  }

  fileData.input.value = file;
  fileData.uploadState!.value = true;
  fileData.displayedName!.value = file.name;
  fileData.preview.value = URL.createObjectURL(file);
  fileData.previewState.value = true;
  fileData.oldPreviewState.value = false;

  console.log('[onThumbnailChange] Thumbnail selected:', {
    name: file.name,
    size: file.size,
    type: file.type,
  });
}

// Add a new file slot to the array
export function addFileSlot(files: UploadFileData[]) {
  console.log('[addFileSlot] Adding new file input slot');
  files.push(createEmptyUploadFileData());
}
// Remove a file slot at a given index
export function removeFileSlot(files: UploadFileData[], index: number) {
  if (index >= 0 && index < files.length) {
    console.log(`[removeFileSlot] Removing file slot at index ${index}`);
    files.splice(index, 1);
  } else {
    console.warn(`[removeFileSlot] Invalid index: ${index}`);
  }
}

// Clear all file slots
export function resetFileSlots(files: UploadFileData[]) {
  console.log('[resetFileSlots] Resetting all file slots');
  files = [];
}

// Get current valid files from uploadsData
export const getFilesFromUploads = (uploadsData: UploadsData) => {
  const rawFiles = uploadsData.files || [];

  console.log('[getFilesFromUploads] Raw fileData count:', rawFiles.length);

  const validFiles = rawFiles
    .map((fileData, i) => {
      const file = fileData?.input;
      if (!(file instanceof File)) {
        console.warn(
          `[getFilesFromUploads] Skipped non-File at index ${i}`,
          file
        );
        return null;
      }

      const isValid = UploadSettings.isValidFile(file);
      console.log(`[getFilesFromUploads] File at index ${i}:`, {
        name: file.name,
        valid: isValid,
      });

      return isValid ? file : null;
    })
    .filter((file): file is File => file !== null);

  const rawThumb = uploadsData.thumbnail.input.value;
  const thumbnail =
    rawThumb instanceof File && UploadSettings.isImageFile(rawThumb)
      ? rawThumb
      : null;

  if (thumbnail) {
    console.log('[getFilesFromUploads] Thumbnail is valid:', thumbnail.name);
  } else {
    console.log('[getFilesFromUploads] No valid thumbnail selected');
  }

  return {
    thumbnail,
    files: validFiles,
  };
};

// Identify which file indexes are marked for deletion
export const getDeleteFileIndexesFromUploads = (
  uploadsData: UploadsData
): number[] => {
  const indexes = uploadsData.files
    .map((fileData, i) => (fileData.deleteTrigger ? i : -1))
    .filter((i) => i !== -1);

  console.log(`[getDeleteFileIndexesFromUploads] Indexes to delete:`, indexes);
  return indexes;
};

// Reset a file input and clear optional external state

export const clearThumbnailInput = (
  fileData: ThumbnailData,
  inputElementOrId?: string | HTMLInputElement | null,
  clearExternalState?: () => void
) => {
  const fileName = fileData.displayedName?.value ?? '(unnamed thumbnail)';
  console.log(`[clearThumbnailInput] Clearing thumbnail input: ${fileName}`);

  fileData.deleteTrigger.value = true;
  fileData.uploadState.value = false;
  fileData.previewState.value = false;
  fileData.oldPreviewState.value = false;
  fileData.preview.value = '';
  fileData.displayedName.value = '';
  fileData.input.value = null;

  if (clearExternalState) {
    clearExternalState();
  }

  if (typeof inputElementOrId === 'string') {
    const el = document.getElementById(inputElementOrId) as HTMLInputElement;
    if (el) el.value = '';
  } else if (inputElementOrId instanceof HTMLInputElement) {
    inputElementOrId.value = '';
  }

  console.log('[clearThumbnailInput] Thumbnail input cleared');
};

export const clearFileInput = (
  fileData: UploadFileData,
  inputElementOrId?: string | HTMLInputElement | null,
  clearExternalState?: () => void
) => {
  const fileName = fileData.displayedName ?? '(unnamed file)';
  console.log(`[clearFileInput] Clearing file input: ${fileName}`);

  fileData.deleteTrigger = true;
  fileData.uploadState = false;
  fileData.previewState = false;
  fileData.oldPreviewState = false;
  fileData.preview = '';
  fileData.displayedName = '';
  fileData.input = null;

  if (clearExternalState) {
    clearExternalState();
  }

  if (typeof inputElementOrId === 'string') {
    const el = document.getElementById(inputElementOrId) as HTMLInputElement;
    if (el) el.value = '';
  } else if (inputElementOrId instanceof HTMLInputElement) {
    inputElementOrId.value = '';
  }

  console.log('[clearFileInput] File input cleared');
};
