import { ref as storageRef, deleteObject } from 'firebase/storage';
import { deleteUserFromAuthentication } from '@/utils/firebaseUtils';

//types import
import {
  query,
  where,
  getDocs,
  deleteDoc,
  doc,
  updateDoc,
} from 'firebase/firestore';
//types import
import type { Ref } from 'vue';
import type { FirebaseStorage } from 'firebase/storage';

import type { BoardItem } from '@/types';
import type { CollectionReference } from 'firebase/firestore';

//Selecting
export const toggleSelect = (
  selectedItems: Ref<BoardItem[]>,
  item: BoardItem
) => {
  const index = selectedItems.value.indexOf(item);
  if (index === -1) {
    selectedItems.value.push(item);
  } else {
    selectedItems.value.splice(index, 1);
  }
};

export const setActiveForSelectedUsers = async (
  selectedItems: Ref<BoardItem[]>,
  showSelectBoxes: Ref<boolean>,
  usersCollection: CollectionReference
) => {
  if (selectedItems.value.length === 0) {
    window.alert('활성화할 사용자를 선택하여 주세요.');
    return;
  }

  const confirmed = window.confirm('선택된 사용자를 활성화하시겠습니까?');
  if (!confirmed) {
    return;
  }

  // Set isActive field for selected users to true
  try {
    const promises = selectedItems.value.map((item) => {
      const userRef = doc(usersCollection, item.docId);
      return updateDoc(userRef, { isActive: true });
    });

    await Promise.all(promises);
  } catch (error) {
    console.error('Error setting users to active:', error);
    alert('사용자 활성화를 실패하였습니다');
  }

  selectedItems.value = [];
  showSelectBoxes.value = true;
};

//Deleting
function getStoragePathFromUrl(url: string): string {
  const baseUrl = 'https://firebasestorage.googleapis.com/v0/b/';
  if (!url.includes(baseUrl)) return url;

  const [, pathWithToken] = url.split('/o/');
  if (!pathWithToken) return url;
  const [encodedPath] = pathWithToken.split('?');
  return decodeURIComponent(encodedPath ?? '');
}
async function deleteBoardAssets(
  board: BoardItem,
  deleteFile: (url?: string) => Promise<void>
) {
  const fileTasks = board.files?.map((f) => deleteFile(f.url)) ?? [];
  const thumbnailTask = deleteFile(board.thumbnail?.url);
  return Promise.all([thumbnailTask, ...fileTasks]);
}

function createDeleteFile(storage: FirebaseStorage) {
  return async (url?: string) => {
    if (!url) return;

    const path = getStoragePathFromUrl(url);
    const fileRef = storageRef(storage, path);

    try {
      await deleteObject(fileRef);
      console.log('[deleteFile] Deleted original:', path);
    } catch (err) {
      console.warn('[deleteFile] Could not delete original:', path, err);
    }

    // Only delete resized versions if it's a thumbnail
    console.log('lookhere', path);
    if (path.includes('thumbnails/')) {
      const basePath = path.replace(/\.[^/.]+$/, '');
      const extension = 'webp';
      const sizes = ['200x200', '500x500'];
      const resizedPaths = sizes.map(
        (size) => `${basePath}_${size}.${extension}`
      );

      await Promise.all(
        resizedPaths.map(async (resizedPath) => {
          const resizedRef = storageRef(storage, resizedPath);
          try {
            await deleteObject(resizedRef);
            console.log('[deleteFile] Deleted resized:', resizedPath);
          } catch (err) {
            console.warn(
              '[deleteFile] Could not delete resized:',
              resizedPath,
              err
            );
          }
        })
      );
    }
  };
}

export const deleteuserSelected = async (
  selectedItems: Ref<BoardItem[]>,
  showSelectBoxes: Ref<boolean>,
  currentCollection: CollectionReference,
  storage: FirebaseStorage
) => {
  if (selectedItems.value.length === 0) {
    window.alert('삭제할 글을 선택하여 주세요.');
    return;
  }

  const confirmed = window.confirm('선택된 모든 글을 삭제하시겠습니까?');
  if (!confirmed) return;

  const deleteFile = createDeleteFile(storage);

  try {
    // ✅ Delete files from Storage
    await Promise.all(
      selectedItems.value.map((item) => deleteBoardAssets(item, deleteFile))
    );
  } catch (error) {
    alert('첨부파일 삭제를 실패하였습니다');
    console.error(error);
  }
  const { $firebase } = useNuxtApp();
  const progressesCollection = $firebase.progressesCollection;
  try {
    // ✅ Delete progresses from Firestore
    await Promise.all(
      selectedItems.value.map(async (item) => {
        const progressRef = progressesCollection;
        const q = query(progressRef, where('userId', '==', item.docId));
        const querySnapshot = await getDocs(q);
        return Promise.all(querySnapshot.docs.map((doc) => deleteDoc(doc.ref)));
      })
    );
  } catch (error) {
    console.error('Error deleting progresses:', error);
  }

  try {
    // ✅ Delete board documents
    await Promise.all(
      selectedItems.value.map((item) =>
        deleteDoc(doc(currentCollection, item.docId))
      )
    );
  } catch (error) {
    console.error('Error deleting Boards:', error);
  }

  try {
    // ✅ Delete Firebase users
    await Promise.all(
      selectedItems.value.map((item) =>
        deleteUserFromAuthentication(item.docId)
      )
    );
  } catch (error) {
    alert('Firebase 사용자 삭제 실패');
    console.log(error);
  }

  selectedItems.value = [];
  showSelectBoxes.value = true;
};

export const deleteSingle = async (
  board: BoardItem,
  currentCollection: CollectionReference,
  storage: FirebaseStorage
): Promise<boolean> => {
  const confirmed = window.confirm('해당글을 정말로 삭제하시겠습니까?');
  if (!confirmed) return false;

  const deleteFile = createDeleteFile(storage);

  try {
    await deleteBoardAssets(board, deleteFile);
  } catch (error) {
    console.error('첨부파일 삭제 실패:', error);
    alert('첨부파일 삭제를 실패하였습니다');
    return false;
  }

  try {
    await deleteDoc(doc(currentCollection, board.docId));
    alert('글이 성공적으로 삭제되었습니다.');
    return true;
  } catch (error) {
    console.error('문서 삭제 실패:', error);
    alert('글 삭제에 실패하였습니다.');
    return false;
  }
};

export const deleteSelected = async (
  selectedItems: Ref<BoardItem[]>,
  showSelectBoxes: Ref<boolean>,
  currentCollection: CollectionReference,
  storage: FirebaseStorage
) => {
  if (selectedItems.value.length === 0) {
    showSelectBoxes.value = false;
    window.alert('삭제할 글을 선택하여 주세요.');
    return;
  }

  const confirmed = window.confirm('선택된 모든 글을 삭제하시겠습니까?');
  if (!confirmed) return;

  const deleteFile = createDeleteFile(storage);

  try {
    await Promise.all(
      selectedItems.value.map((item) => deleteBoardAssets(item, deleteFile))
    );
  } catch (error) {
    alert('첨부파일 삭제를 실패하였습니다');
    console.error(error);
  }

  try {
    await Promise.all(
      selectedItems.value.map((item) =>
        deleteDoc(doc(currentCollection, item.docId))
      )
    );
    selectedItems.value = [];
  } catch (error) {
    console.error('Error deleting Boards:', error);
  }

  showSelectBoxes.value = false;
  window.location.reload();
};
