import { create } from 'zustand';

const TOKEN_STORAGE_KEY = 'imgpub_token';
const USER_STORAGE_KEY = 'imgpub_user';

const readStoredAuth = () => {
  if (typeof window === 'undefined') {
    return { token: null, user: null };
  }
  try {
    const token = window.localStorage.getItem(TOKEN_STORAGE_KEY);
    const userRaw = window.localStorage.getItem(USER_STORAGE_KEY);
    const user = userRaw ? JSON.parse(userRaw) : null;
    return { token, user };
  } catch (error) {
    console.warn('Stored auth okunamadı', error);
    return { token: null, user: null };
  }
};

const createEmptyCropConfig = () => ({
  x: 0,
  y: 0,
  zoom: 1,
  width: 0,
  height: 0,
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  cropAreaX: 0,
  cropAreaY: 0,
  imageWidth: 0,
  imageHeight: 0,
  referenceImageId: null,
  selection: null,
});

export const useAppStore = create((set) => ({
  uploadedImages: [],
  cropConfig: createEmptyCropConfig(),
  croppedImages: [],
  coverImageId: null,
  coverCropConfig: createEmptyCropConfig(),
  croppedCoverImage: null,
  ocrText: '',
  translatedText: '',
  translationStatus: 'idle',
  translationError: null,
  translationProgress: 0,
  generatedEpub: null,
  authToken: null,
  currentUser: null,
  error: null,
  setError: (message) => set({ error: message }),
  clearError: () => set({ error: null }),
  setUploadedImages: (images) => set({ uploadedImages: images }),
  updateCropConfig: (config) => set({ cropConfig: { ...config } }),
  updateCoverCropConfig: (config) => set({ coverCropConfig: { ...config } }),
  setCroppedImages: (images) =>
    set((state) => {
      state.croppedImages.forEach((img) => {
        if (img.url) URL.revokeObjectURL(img.url);
      });
      return { croppedImages: images };
    }),
  setCroppedCoverImage: (image) =>
    set((state) => {
      if (state.croppedCoverImage?.url) {
        URL.revokeObjectURL(state.croppedCoverImage.url);
      }
      return { croppedCoverImage: image };
    }),
  setOcrText: (text) => set({ ocrText: text }),
  setTranslatedText: (text) => set({ translatedText: text }),
  setTranslationStatus: (status) => set({ translationStatus: status }),
  setTranslationError: (message) => set({ translationError: message }),
  setTranslationProgress: (value) => set({ translationProgress: value }),
  clearTranslation: () =>
    set({
      translatedText: '',
      translationStatus: 'idle',
      translationError: null,
      translationProgress: 0,
    }),
  setGeneratedEpub: (epub) =>
    set((state) => {
      if (state.generatedEpub?.url) {
        URL.revokeObjectURL(state.generatedEpub.url);
      }
      return { generatedEpub: epub };
    }),
  initializeAuth: () => {
    const { token, user } = readStoredAuth();
    if (token && user) {
      set({ authToken: token, currentUser: user });
    }
  },
  setAuthSession: ({ token, user }) => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
      window.localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
    }
    set({ authToken: token, currentUser: user });
  },
  updateCurrentUser: (user) =>
    set((state) => {
      if (typeof window !== 'undefined' && state.authToken) {
        window.localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
      }
      return { currentUser: user };
    }),
  clearAuthSession: () => {
    if (typeof window !== 'undefined') {
      window.localStorage.removeItem(TOKEN_STORAGE_KEY);
      window.localStorage.removeItem(USER_STORAGE_KEY);
    }
    set({ authToken: null, currentUser: null });
  },
  setCoverImageId: (id) =>
    set((state) => {
      const draft = {
        coverImageId: id,
        coverCropConfig: createEmptyCropConfig(),
      };
      if (state.croppedCoverImage?.url) {
        URL.revokeObjectURL(state.croppedCoverImage.url);
      }
      draft.croppedCoverImage = null;
      if (state.generatedEpub?.url) {
        URL.revokeObjectURL(state.generatedEpub.url);
        draft.generatedEpub = null;
      }
      return draft;
    }),
  resetFromStep: (step) =>
    set((state) => {
      const draft = {};
      if (step === 'upload') {
        draft.cropConfig = createEmptyCropConfig();
        state.croppedImages.forEach((img) => img.url && URL.revokeObjectURL(img.url));
        draft.croppedImages = [];
        if (state.croppedCoverImage?.url) {
          URL.revokeObjectURL(state.croppedCoverImage.url);
        }
        draft.coverImageId = null;
        draft.coverCropConfig = createEmptyCropConfig();
        draft.croppedCoverImage = null;
        draft.ocrText = '';
        draft.translatedText = '';
        draft.translationStatus = 'idle';
        draft.translationError = null;
        draft.translationProgress = 0;
        if (state.generatedEpub?.url) {
          URL.revokeObjectURL(state.generatedEpub.url);
        }
        draft.generatedEpub = null;
      }
      if (step === 'crop') {
        state.croppedImages.forEach((img) => img.url && URL.revokeObjectURL(img.url));
        draft.croppedImages = [];
        draft.ocrText = '';
        draft.translatedText = '';
        draft.translationStatus = 'idle';
        draft.translationError = null;
        draft.translationProgress = 0;
        if (state.generatedEpub?.url) {
          URL.revokeObjectURL(state.generatedEpub.url);
        }
        draft.generatedEpub = null;
      }
      if (step === 'ocr') {
        draft.ocrText = '';
        draft.translatedText = '';
        draft.translationStatus = 'idle';
        draft.translationError = null;
        draft.translationProgress = 0;
        if (state.generatedEpub?.url) {
          URL.revokeObjectURL(state.generatedEpub.url);
        }
        draft.generatedEpub = null;
      }
      if (step === 'epub' || step === 'download') {
        if (state.generatedEpub?.url) {
          URL.revokeObjectURL(state.generatedEpub.url);
        }
        draft.generatedEpub = null;
      }
      return draft;
    }),
}));
