using System;
using System.Collections.Generic;
using Managers;
using UniRx;
using UnityEngine;

namespace DialogueSystem.Diary
{
    public enum DiaryLoadMode
    {
        Intro,
        Level1,
        Level2,
        Level3
    }
    
    public class DiaryManager : MonoBehaviour
    {
        public List<DiaryDayScriptableObject> diaryDaysToShow;
        [SerializeField] private DiaryLoadMode loadMode = DiaryLoadMode.Intro;

        public IntReactiveProperty currentDayNumber = new IntReactiveProperty();
        
        public static DiaryManager Instance { get; private set; }

        private void Awake()
        {
            if (Instance != null && Instance != this)
            {
                Destroy(this);
                return;
            }
            
            Instance = this;

            currentDayNumber.Value = 0;
            
            // Load global data
            GlobalData.LoadData();
            int lastCompletedLevel = GlobalData.lastCompletedLevel;
            
            // Load diary pages based on mode
            LoadDiaryPages(lastCompletedLevel);
        }

        private void LoadDiaryPages(int lastCompletedLevel)
        {
            diaryDaysToShow = new List<DiaryDayScriptableObject>();
            
            Debug.Log($"loadMode: {loadMode}");
            
            if (loadMode == DiaryLoadMode.Intro)
            {
                LoadPage("DiaryPage_Day1_Past");
            }
            else if (loadMode == DiaryLoadMode.Level1)
            {
                LoadPage("DiaryPage_Day1_Past");
            }
            else if (loadMode == DiaryLoadMode.Level2)
            {
                LoadPage("DiaryPage_Day1_Past");
                LoadPage("DiaryPage_Day2_Past");
            }
            else if (loadMode == DiaryLoadMode.Level3)
            {
                LoadPage("DiaryPage_Day1_Past");
                LoadPage("DiaryPage_Day2_Past");
                LoadPage("DiaryPage_Day3_Past");
            }
        }

        private void LoadPage(string pageName)
        {
            DiaryDayScriptableObject page = Resources.Load<DiaryDayScriptableObject>("DiaryPages/" + pageName);
            if (page != null)
            {
                diaryDaysToShow.Add(page);
            }
            else
            {
                Debug.LogWarning($"Could not find diary page: {pageName} in Resources/DiaryPages/");
            }
        }

        public bool ReachedLastDayInDiary()
        {
            return currentDayNumber.Value == diaryDaysToShow.Count - 1;
        }
    }
}
