using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class FlappyBirdAllInOne : MonoBehaviour, ITask
{

    [Header("Player")]
    public Rigidbody2D rb;
    public float jumpForce = 5f;
    public bool isDead = false;


    [Header("Pipes")]
    public GameObject pipePrefab;
    public Transform spawnPoint;
    public float spawnRate = 2f;
    public float heightOffset = 2f;
    public float pipeSpeed = 2f;

    private float timer = 0;


    [Header("UI")]
    public TextMeshProUGUI scoreText;
    public GameObject gameOverPanel;

    private int score = 0;

    
    private Action<ITask> _onCompleted;
    private Action<ITask> _onExit;

    public string TaskID { get; set; }
    public TaskType TaskType { get; set; }
    public string TaskName { get; set; }
    public (double, double) TaskLocation { get; set; }
    public bool IsCompleted { get; private set; }

    private bool _isPaused = false;

    void Start()
    {
        _isPaused = false;
        score = 0;
        if (scoreText != null) UpdateScore();
    }

    void Update()
    {
        if (isDead || _isPaused) return;

        HandleInput();
        HandleSpawning();
    }


    void HandleInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Jump();
        }
    }

    void Jump()
    {
        rb.linearVelocity = Vector2.zero;
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }


    void HandleSpawning()
    {
        timer += Time.deltaTime;

        if (timer >= spawnRate)
        {
            SpawnPipe();
            timer = 0;
        }
    }

    void SpawnPipe()
    {
        float yOffset = UnityEngine.Random.Range(-heightOffset, heightOffset);

        GameObject pipe = Instantiate(
            pipePrefab,
            spawnPoint.position + new Vector3(0, yOffset, 0),
            Quaternion.identity
        );

        pipe.AddComponent<PipeMover>().Init(pipeSpeed, this);
    }


    public void AddScore()
    {
        score++;
        UpdateScore();
        if (score >= 10)
        {
            Complete();
        }
    }

    void UpdateScore()
    {
        scoreText.text = score.ToString();
    }


    public void GameOver()
    {
        isDead = true;
        _isPaused = true;
        if (gameOverPanel != null) gameOverPanel.SetActive(true);
        // NOTE: do NOT set Time.timeScale — GPS and network must keep running
    }

    public void Restart()
    {
        // TaskManager will unload and reload via additive loading
        // Calling ExitTask lets TaskManager handle scene lifecycle
        ExitTask(_onExit);
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        GameOver();
    }

    public void Initialize(Action<ITask> onCompleted)
    {
        IsCompleted = false;
        _onCompleted = onCompleted;
    }

    public void Complete()
    {
        if (IsCompleted) return;

        IsCompleted = true;
        _onCompleted?.Invoke(this);
        ExitTask(_onExit);
    }

    public void ExitTask(Action<ITask> onExit)
    {
        onExit?.Invoke(this);
    }
}

public class PipeMover : MonoBehaviour
{
    private float speed;
    private FlappyBirdAllInOne game;

    public void Init(float moveSpeed, FlappyBirdAllInOne gm)
    {
        speed = moveSpeed;
        game = gm;
    }

    void Update()
    {
        transform.position += Vector3.left * speed * Time.deltaTime;

        if (transform.position.x < -10f)
        {
            Destroy(gameObject);
        }
    }
}

public class ScoreTrigger : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        FlappyBirdAllInOne gm = FindObjectOfType<FlappyBirdAllInOne>();

        if (collision.CompareTag("Player") && gm != null)
        {
            gm.AddScore();
        }
    }
}

// =====================
// navod pro desing t�m 
// =====================
/*
1. Player:
   - Sprite + Rigidbody2D (Gravity ~2-3)
   - BoxCollider2D
   - PlayerController script
   - Tag = Player

2. Pipes:
   - Prefab se 2 kolidery (top/bottom)
   - Mezera mezi nimi
   - PipeMove script

3. Score Zone:
   - Trigger collider mezi trubkami
   - ScoreZone script

4. Spawner:
   - Empty GameObject
   - PipeSpawner script

5. UI:
   - TextMeshPro pro score
   - GameOver panel + restart button

6. Mobile:
   - Input.GetMouseButtonDown funguje i na tap
*/