using UnityEngine;
using UnityEngine.UI;
using System.Collections;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif

public class GalleryMenu : MonoBehaviour
{
    public GameObject galleryPanel;
    public Text faceCountText;
    public Button pickImageButton;
    public Button clearButton;
    public Button playButton;

    private void Start()
    {
        if (pickImageButton != null)
            pickImageButton.onClick.AddListener(PickImageFromGallery);
        if (clearButton != null)
            clearButton.onClick.AddListener(ClearAllFaces);
        if (playButton != null)
            playButton.onClick.AddListener(PlayGame);
        UpdateFaceCount();
    }

    private void PickImageFromGallery()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        try
        {
            string permission = "android.permission.READ_EXTERNAL_STORAGE";
            if (!Permission.HasUserAuthorizedPermission(permission))
            {
                Permission.RequestUserPermission(permission);
            }
            var jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            var jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            var intent = new AndroidJavaObject("android.content.Intent");
            intent.Call<AndroidJavaObject>("setAction", "android.intent.action.PICK");
            intent.Call<AndroidJavaObject>("setType", "image/*");
            jo.Call("startActivityForResult", intent, 1001);
            StartCoroutine(WaitForImageResult());
        }
        catch (System.Exception ex)
        {
            Debug.LogError("Error picking image: " + ex.Message);
        }
#else
        Debug.Log("Image picker only works on Android device");
#endif
    }

    private IEnumerator WaitForImageResult()
    {
        yield return new WaitForSeconds(2f);
        if (ImageGalleryManager.Instance != null)
            ImageGalleryManager.Instance.LoadFacesFromStorage();
        UpdateFaceCount();
    }

    private void ClearAllFaces()
    {
        if (ImageGalleryManager.Instance != null)
            ImageGalleryManager.Instance.ClearAllFaces();
        UpdateFaceCount();
    }

    private void PlayGame()
    {
        if (galleryPanel != null)
            galleryPanel.SetActive(false);
        if (GameManager.Instance != null)
            GameManager.Instance.StartNewGame();
    }

    private void UpdateFaceCount()
    {
        int count = 0;
        if (ImageGalleryManager.Instance != null)
        {
            var faces = ImageGalleryManager.Instance.GetFaces();
            if (faces != null) count = faces.Count;
        }
        if (faceCountText != null)
            faceCountText.text = "Faces loaded: " + count;
    }
}
