import { authInstance } from "@shared";
import { v4 as uuidv4 } from "uuid";
import { makeAutoObservable, runInAction } from "mobx";
import {
  articlesStore,
  cityStore,
  countryStore,
  carrierStore,
  stationsStore,
  sightsStore,
  routeStore,
  vehicleStore,
  userStore,
  mediaStore,
  createSightStore,
  editSightStore,
  devicesStore,
  authStore,
} from "@shared";

type Snapshot = {
  ID: string;
  Name: string;
  ParentID: string;
  CreationTime: string;
  occupied_disk_space_gb: number;
};

type SnapshotStatus = {
  ID: string;
  Status: string;
  Progress: number;
  Error: string;
};

type StorageInfo = {
  available_disk_space_gb: number;
  total_disk_space_gb: number;
};

class SnapshotStore {
  snapshots: Snapshot[] = [];
  snapshot: Snapshot | null = null;
  lastRequestId: string | null = null;
  snapshotStatus: SnapshotStatus | null = null;
  storageInfo: StorageInfo | null = null;

  constructor() {
    makeAutoObservable(this);
  }

  clearStoreCache = () => {
    runInAction(() => {
      articlesStore.articleList = {
        ru: { data: [], loaded: false },
        en: { data: [], loaded: false },
        zh: { data: [], loaded: false },
      };
      articlesStore.articlePreview = {};
      articlesStore.articleData = null;
      articlesStore.articleMedia = null;

      carrierStore.carriers = {
        ru: { data: [], loaded: false },
        en: { data: [], loaded: false },
        zh: { data: [], loaded: false },
      };

      stationsStore.stationLists = {
        ru: { data: [], loaded: false },
        en: { data: [], loaded: false },
        zh: { data: [], loaded: false },
      };
      stationsStore.stationPreview = {};

      sightsStore.sights = [];
      sightsStore.sight = null;

      routeStore.routes = { data: [], loaded: false };

      vehicleStore.vehicles = { data: [], loaded: false };

      userStore.users = { data: [], loaded: false };

      mediaStore.media = [];
      mediaStore.oneMedia = null;
    });
  };

  private clearAllCaches = () => {
    articlesStore.articleList = {
      ru: { data: [], loaded: false },
      en: { data: [], loaded: false },
      zh: { data: [], loaded: false },
    };
    articlesStore.articlePreview = {};
    articlesStore.articleData = null;
    articlesStore.articleMedia = null;

    cityStore.cities = {
      ru: { data: [], loaded: false },
      en: { data: [], loaded: false },
      zh: { data: [], loaded: false },
    };
    cityStore.ruCities = { data: [], loaded: false };
    cityStore.city = {};

    countryStore.countries = {
      ru: { data: [], loaded: false },
      en: { data: [], loaded: false },
      zh: { data: [], loaded: false },
    };

    carrierStore.carriers = {
      ru: { data: [], loaded: false },
      en: { data: [], loaded: false },
      zh: { data: [], loaded: false },
    };

    stationsStore.stationLists = {
      ru: { data: [], loaded: false },
      en: { data: [], loaded: false },
      zh: { data: [], loaded: false },
    };
    stationsStore.stationPreview = {};

    sightsStore.sights = [];
    sightsStore.sight = null;

    routeStore.routes = { data: [], loaded: false };

    vehicleStore.vehicles = { data: [], loaded: false };

    userStore.users = { data: [], loaded: false };

    mediaStore.media = [];
    mediaStore.oneMedia = null;

    createSightStore.sight = JSON.parse(
      JSON.stringify({
        city_id: 0,
        city: "",
        latitude: 0,
        longitude: 0,
        is_default_icon: false,
        thumbnail: null,
        icon: null,
        alt_icon: null,
        watermark_lu: null,
        watermark_rd: null,
        left_article: 0,
        preview_media: null,
        video_preview: null,
        ru: {
          name: "",
          address: "",
          left: { heading: "", body: "", media: [] },
          right: [],
        },
        en: {
          name: "",
          address: "",
          left: { heading: "", body: "", media: [] },
          right: [],
        },
        zh: {
          name: "",
          address: "",
          left: { heading: "", body: "", media: [] },
          right: [],
        },
      })
    );
    createSightStore.uploadMediaOpen = false;
    createSightStore.fileToUpload = null;
    createSightStore.needLeaveAgree = false;

    editSightStore.sight = {
      common: {
        id: 0,
        city_id: 0,
        city: "",
        latitude: 0,
        longitude: 0,
        is_default_icon: false,
        thumbnail: null,
        icon: null,
        alt_icon: null,
        watermark_lu: null,
        watermark_rd: null,
        left_article: 0,
        preview_media: null,
        video_preview: null,
      },
      ru: {
        id: 0,
        name: "",
        short_name: "",
        address: "",
        left: { heading: "", body: "", media: [] },
        right: [],
      },
      en: {
        id: 0,
        name: "",
        short_name: "",
        address: "",
        left: { heading: "", body: "", media: [] },
        right: [],
      },
      zh: {
        id: 0,
        name: "",
        short_name: "",
        address: "",
        left: { heading: "", body: "", media: [] },
        right: [],
      },
    };
    editSightStore.hasLoadedCommon = false;
    editSightStore.uploadMediaOpen = false;
    editSightStore.fileToUpload = null;
    editSightStore.needLeaveAgree = false;

    devicesStore.devices = [];
    devicesStore.uuid = null;
    devicesStore.sendSnapshotModalOpen = false;

    authStore.payload = null;
    authStore.error = null;
    authStore.isLoading = false;

    try {
      if (typeof window !== "undefined" && (window as any).mapStore) {
        (window as any).mapStore.routes = [];
        (window as any).mapStore.stations = [];
        (window as any).mapStore.sights = [];
      }

      if (typeof window !== "undefined" && (window as any).mapServiceInstance) {
        (window as any).mapServiceInstance.clearCaches();
      }
    } catch (error) {
      console.warn("Не удалось сбросить кеши карты:", error);
    }

    const token = localStorage.getItem("token");
    const rememberedEmail = localStorage.getItem("rememberedEmail");
    const rememberedPassword = localStorage.getItem("rememberedPassword");

    localStorage.clear();
    sessionStorage.clear();

    if (token) localStorage.setItem("token", token);
    if (rememberedEmail)
      localStorage.setItem("rememberedEmail", rememberedEmail);
    if (rememberedPassword)
      localStorage.setItem("rememberedPassword", rememberedPassword);

    const mapPositionKey = "mapPosition";
    const activeSectionKey = "mapActiveSection";
    if (localStorage.getItem(mapPositionKey)) {
      localStorage.removeItem(mapPositionKey);
    }
    if (localStorage.getItem(activeSectionKey)) {
      localStorage.removeItem(activeSectionKey);
    }

    if ("caches" in window) {
      try {
        caches.keys().then((cacheNames) => {
          return Promise.all(
            cacheNames.map((cacheName) => {
              return caches.delete(cacheName);
            })
          );
        });
      } catch (error) {
        console.warn("Кеш браузера не поддерживается:", error);
      }
    }

    if ("indexedDB" in window) {
      try {
        indexedDB.databases().then((databases) => {
          return Promise.all(
            databases.map((db) => {
              if (db.name) {
                return indexedDB.deleteDatabase(db.name);
              }
              return Promise.resolve();
            })
          );
        });
      } catch (error) {
        console.warn("IndexedDB не поддерживается:", error);
      }
    }
  };

  getSnapshots = async () => {
    const response = await authInstance.get(`/snapshots`);

    runInAction(() => {
      this.snapshots = response.data;
    });
  };

  deleteSnapshot = async (id: string) => {
    const snapshot = this.snapshots.find((s) => s.ID === id);
    await authInstance.delete(`/snapshots/${id}`);

    runInAction(() => {
      this.snapshots = this.snapshots.filter((s) => s.ID !== id);
      if (this.storageInfo && snapshot?.occupied_disk_space_gb) {
        this.storageInfo = {
          ...this.storageInfo,
          available_disk_space_gb: this.storageInfo.available_disk_space_gb + snapshot.occupied_disk_space_gb,
        };
      }
    });
  };

  getSnapshot = async (id: string) => {
    const response = await authInstance.get(`/snapshots/${id}`);

    runInAction(() => {
      this.snapshot = response.data;
    });
  };

  restoreSnapshot = async (id: string) => {
    this.clearAllCaches();

    await authInstance.post(`/snapshots/${id}/restore`);
  };

  createEmptySnapshot = async (name: string) => {
    await authInstance.post(`/snapshots/empty`, {
      name: name.trim(),
    });
  };

  createSnapshot = async (name: string) => {
    this.lastRequestId = uuidv4();

    const response = await authInstance.post(
      `/snapshots`,
      { name: name.trim() },
      { headers: { "X-Request-ID": this.lastRequestId } }
    );

    return response.data.ID;
  };

  getSnapshotStatus = async (id: string) => {
    const response = await authInstance.get(`/snapshots/status/${id}`);

    runInAction(() => {
      this.snapshotStatus = response.data;
    });
  };

  getStorageInfo = async () => {
    const response = await authInstance.get(`/snapshots/storage`);

    runInAction(() => {
      this.storageInfo = response.data;
    });
  };
}

export const snapshotStore = new SnapshotStore();
