// @shared/stores/createSightStore.ts
import {
  Language,
  authInstance,
  languageInstance,
  articlesStore,
  languageStore,
  mediaStore,
} from "@shared";
import { makeAutoObservable } from "mobx";

type SightLanguageInfo = {
  name: string;
  address: string;
  left: {
    heading: string;
    body: string;
    media: {
      id: string;
      filename: string;
      media_name?: string;
      media_type: number;
    }[];
  };
  right: { heading: string; body: string }[];
};

type SightCommonInfo = {
  id: number;
  city_id: number;
  city: string;
  latitude: number;
  longitude: number;
  thumbnail: string | null;
  watermark_lu: string | null;
  watermark_rd: string | null;
  left_article: number;
  preview_media: string | null;
  video_preview: string | null;
};

type SightBaseInfo = SightCommonInfo & {
  [key in Language]: SightLanguageInfo;
};

class CreateSightStore {
  sight: SightBaseInfo = {
    id: 0,
    city_id: 0,
    city: "",
    latitude: 0,
    longitude: 0,
    thumbnail: 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: [],
    },
  };

  uploadMediaOpen = false;
  setUploadMediaOpen = (open: boolean) => {
    this.uploadMediaOpen = open;
  };
  fileToUpload: File | null = null;
  setFileToUpload = (file: File | null) => {
    this.fileToUpload = file;
  };

  constructor() {
    makeAutoObservable(this);
  }

  createNewRightArticle = () => {
    this.sight.ru.right.push({
      heading: "Введите русский заголовок",
      body: "Введите русский текст",
    });
    this.sight.en.right.push({
      heading: "Enter the English heading",
      body: "Enter the English text",
    });
    this.sight.zh.right.push({
      heading: "Введите китайский заголовок",
      body: "Введите китайский текст",
    });
  };

  updateLeftInfo = (language: Language, heading: string, body: string) => {
    this.sight[language].left.heading = heading;
    this.sight[language].left.body = body;
  };

  clearCreateSight = () => {
    this.sight = {
      id: 0,
      city_id: 0,
      city: "",
      latitude: 0,
      longitude: 0,
      thumbnail: 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: [],
      },
    };
  };

  updateSightInfo = (
    content: Partial<SightLanguageInfo | SightCommonInfo>,
    language?: Language
  ) => {
    if (language) {
      this.sight[language] = {
        ...this.sight[language],
        ...content,
      };
    } else {
      this.sight = {
        ...this.sight,
        ...content,
      };
    }
  };

  unlinkLeftArticle = () => {
    this.sight.left_article = 0;
    this.sight.ru.left.heading = "";
    this.sight.en.left.heading = "";
    this.sight.zh.left.heading = "";
    this.sight.ru.left.body = "";
    this.sight.en.left.body = "";
    this.sight.zh.left.body = "";
  };

  updateLeftArticle = async (articleId: number) => {
    this.sight.left_article = articleId;

    if (articleId) {
      const ruArticleData = await languageInstance("ru").get(
        `/article/${articleId}`
      );
      const enArticleData = await languageInstance("en").get(
        `/article/${articleId}`
      );
      const zhArticleData = await languageInstance("zh").get(
        `/article/${articleId}`
      );

      this.sight.ru.left.heading = ruArticleData.data.heading;
      this.sight.en.left.heading = enArticleData.data.heading;
      this.sight.zh.left.heading = zhArticleData.data.heading;

      this.sight.ru.left.body = ruArticleData.data.body;
      this.sight.en.left.body = enArticleData.data.body;
      this.sight.zh.left.body = zhArticleData.data.body;
    } else {
      this.sight.left_article = 0;
      this.sight.ru.left.heading = "";
      this.sight.en.left.heading = "";
      this.sight.zh.left.heading = "";
      this.sight.ru.left.body = "";
      this.sight.en.left.body = "";
      this.sight.zh.left.body = "";
    }
  };

  deleteLeftArticle = async (articleId: number) => {
    await authInstance.delete(`/article/${articleId}`);
    articlesStore.getArticles(languageStore.language);
    this.sight.left_article = 0;
    this.sight.ru.left.heading = "";
    this.sight.en.left.heading = "";
    this.sight.zh.left.heading = "";
    this.sight.ru.left.body = "";
  };

  createLeftArticle = async () => {
    const response = await languageInstance("ru").post("/article", {
      heading: "Новая статья",
      body: "Заполните статью контентом",
    });

    this.sight.left_article = response.data.id;

    this.sight.ru.left.heading = "Новая статья  ";
    this.sight.en.left.heading = "";
    this.sight.zh.left.heading = "";
    this.sight.ru.left.body = "Заполните статью контентом";
    this.sight.en.left.body = "";
    this.sight.zh.left.body = "";
  };

  createSight = async (language: Language) => {
    const rightArticles: number[] = [];

    if (this.sight.left_article !== 0) {
      if (this.sight.left_article == 10000000) {
        const response = await languageInstance("ru").post("/article", {
          heading: this.sight.ru.left.heading,
          body: this.sight.ru.left.body,
        });
        const { id } = response.data;
        await languageInstance("en").patch(`/article/${id}`, {
          heading: this.sight.en.left.heading,
          body: this.sight.en.left.body,
        });

        await languageInstance("zh").patch(`/article/${id}`, {
          heading: this.sight.zh.left.heading,
          body: this.sight.zh.left.body,
        });
        this.sight.left_article = id;
      } else {
        await languageInstance("ru").patch(
          `/article/${this.sight.left_article}`,
          {
            heading: this.sight.ru.left.heading,
            body: this.sight.ru.left.body,
          }
        );

        await languageInstance("en").patch(
          `/article/${this.sight.left_article}`,
          {
            heading: this.sight.en.left.heading,
            body: this.sight.en.left.body,
          }
        );

        await languageInstance("zh").patch(
          `/article/${this.sight.left_article}`,
          {
            heading: this.sight.zh.left.heading,
            body: this.sight.zh.left.body,
          }
        );
      }
    }

    this.sight[language].right.map(async (article, index) => {
      try {
        const response = await languageInstance(language).post("/article", {
          heading: article.heading,
          body: article.body,
        });
        const { id } = response.data;
        const anotherLanguages = ["en", "zh", "ru"].filter(
          (lang) => lang !== language
        );
        await languageInstance(anotherLanguages[0] as Language).patch(
          `/article/${id}`,
          {
            heading:
              this.sight[anotherLanguages[0] as Language].right[index].heading,
            body: this.sight[anotherLanguages[0] as Language].right[index].body,
          }
        );
        await languageInstance(anotherLanguages[1] as Language).patch(
          `/article/${id}`,
          {
            heading:
              this.sight[anotherLanguages[1] as Language].right[index].heading,
            body: this.sight[anotherLanguages[1] as Language].right[index].body,
          }
        );
        rightArticles.push(id);
      } catch (error) {
        console.log(error);
      }
    });
    const response = await languageInstance(language).post("/sight", {
      city_id: this.sight.city_id,
      city: this.sight.city,
      latitude: this.sight.latitude,
      longitude: this.sight.longitude,
      name: this.sight[language].name,
      address: this.sight[language].address,
      thumbnail: this.sight.thumbnail ?? null,
      watermark_lu: this.sight.watermark_lu,
      watermark_rd: this.sight.watermark_rd,
      left_article: this.sight.left_article,
      preview_media: this.sight.preview_media,
      video_preview: this.sight.video_preview,
    });

    const { id } = response.data;
    const anotherLanguages = ["en", "zh", "ru"].filter(
      (lang) => lang !== language
    );

    await languageInstance(anotherLanguages[0] as Language).patch(
      `/sight/${id}`,
      {
        city_id: this.sight.city_id,
        city: this.sight.city,
        latitude: this.sight.latitude,
        longitude: this.sight.longitude,
        name: this.sight[anotherLanguages[0] as Language as Language].name,
        address:
          this.sight[anotherLanguages[0] as Language as Language].address,
        thumbnail: this.sight.thumbnail ?? null,
        watermark_lu: this.sight.watermark_lu,
        watermark_rd: this.sight.watermark_rd,
        left_article: this.sight.left_article,
        preview_media: this.sight.preview_media,
        video_preview: this.sight.video_preview,
      }
    );
    await languageInstance(anotherLanguages[1] as Language).patch(
      `/sight/${id}`,
      {
        city_id: this.sight.city_id,
        city: this.sight.city,
        latitude: this.sight.latitude,
        longitude: this.sight.longitude,
        name: this.sight[anotherLanguages[1] as Language].name,
        address: this.sight[anotherLanguages[1] as Language].address,
        thumbnail: this.sight.thumbnail ?? null,
        watermark_lu: this.sight.watermark_lu,
        watermark_rd: this.sight.watermark_rd,
        left_article: this.sight.left_article,
        preview_media: this.sight.preview_media,
        video_preview: this.sight.video_preview,
      }
    );

    rightArticles.map(async (article, index) => {
      await authInstance.post(`/sight/${id}/article`, {
        article_id: article,
        page_num: index + 1,
      });
    });
    console.log("created");
  };

  updateRightArticleInfo = (
    index: number,
    language: Language,
    heading: string,
    body: string
  ) => {
    this.sight[language].right[index].heading = heading;
    this.sight[language].right[index].body = body;
  };

  uploadMedia = async (
    filename: string,
    type: number,
    file: File,
    media_name?: string
  ) => {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("filename", filename);
    if (media_name) {
      formData.append("media_name", media_name);
    }
    formData.append("type", type.toString());
    try {
      const response = await authInstance.post(`/media`, formData);
      this.fileToUpload = null;
      this.uploadMediaOpen = false;
      mediaStore.getMedia();
      return {
        id: response.data.id,
        filename: filename,
        media_name: media_name,
        media_type: type,
      };
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  createLinkWithArticle = async (media: {
    id: string;
    filename: string;
    media_name?: string;
    media_type: number;
  }) => {
    await authInstance.post(`/article/${this.sight.left_article}/media`, {
      media_id: media.id,
      media_order: 1,
    });

    this.sight.ru.left.media.unshift({
      id: media.id,
      media_type: media.media_type,
      filename: media.filename,
    });

    this.sight.en.left.media.unshift({
      id: media.id,
      media_type: media.media_type,
      filename: media.filename,
    });

    this.sight.zh.left.media.unshift({
      id: media.id,
      media_type: media.media_type,
      filename: media.filename,
    });
  };
}

export const createSightStore = new CreateSightStore();
