using UnityEngine;
using UnityEngine.AI;

namespace ServiceSim
{
    /// <summary>
    /// 立ち上がって歩いている客1人。使い回しの体で、GroupManager から用事を1つずつ渡される。
    ///   待合で待つ／ドリンクバーへ／トイレへ／店を出る
    /// 座っている人はこの体を持たない（通路に出ないため）。
    ///
    /// この script は人だけを扱う。どの用事をいつ出すかは GroupManager が決める。
    /// </summary>
    [RequireComponent(typeof(NavMeshAgent))]
    public class GuestAgent : MonoBehaviour
    {
        /// <summary>用事</summary>
        public enum Errand { Waiting, DrinkBar, Toilet, Leave, Pay }

        /// <summary>いまの段</summary>
        public enum Leg { Idle, Going, Dwelling, Returning }

        [Header("設定")]
        public PeopleSpec spec;

        [Tooltip("あきらめたことを残す先（B1）。無くても動く")]
        public ServiceOps ops;

        [Header("いまの様子（読むだけ）")]
        [SerializeField] Errand _errand;
        [SerializeField] Leg _leg = Leg.Idle;
        [SerializeField] float _legS;      // いまの段に入ってから歩いた秒数

        NavMeshAgent _agent;
        PersonRobotYield _yield;      // ロボットをよけている最中は「着いた」と見ない
        Vector3 _target;
        Vector3 _home;
        float _dwellSec;
        float _timer;
        bool _returnHome;
        System.Action _onDone;
        Vector3 _pending;
        bool _needsDestination;
        int _tableId;
        bool _gaveUp;

        public Errand CurrentErrand { get { return _errand; } }
        public Leg CurrentLeg { get { return _leg; } }

        /// <summary>この体が着けずにあきらめたか（字幕と報告が読む）</summary>
        public bool GaveUp { get { return _gaveUp; } }

        /// <summary>どの卓の客か（記録用）。GroupManager が入れる</summary>
        public void SetTable(int tableId) { _tableId = tableId; }

        void Awake()
        {
            _agent = GetComponent<NavMeshAgent>();
            _yield = GetComponent<PersonRobotYield>();
        }

        /// <summary>ロボットをよけている最中か（行き先がよけ場所にすり替わっている）</summary>
        bool Yielding
        {
            get
            {
                if (_yield == null) _yield = GetComponent<PersonRobotYield>();
                return _yield != null && _yield.Intervening;
            }
        }

        /// <summary>体をその場所に置く（用事を渡す前に呼ぶ）</summary>
        public void PlaceAt(Vector3 p)
        {
            if (_agent == null) _agent = GetComponent<NavMeshAgent>();
            transform.position = p;
            if (Application.isPlaying && _agent != null && _agent.enabled && _agent.isOnNavMesh)
                _agent.Warp(p);
        }

        /// <summary>用事を1つ渡す</summary>
        public void Begin(PeopleSpec peopleSpec, Errand kind, Vector3 target, float dwellSec,
                          bool returnHome, Vector3 home, System.Action onDone)
        {
            spec = peopleSpec;
            _errand = kind;
            _target = target;
            _dwellSec = dwellSec;
            _returnHome = returnHome;
            _home = home;
            _onDone = onDone;
            _timer = 0f;
            _legS = 0f;
            _gaveUp = false;

            if (_agent == null) _agent = GetComponent<NavMeshAgent>();
            ApplySpec();

            if (kind == Errand.Waiting)
            {
                _leg = Leg.Dwelling;
                _dwellSec = float.MaxValue;   // 迎えに来るまで立っている
                _needsDestination = false;
                return;
            }
            _leg = Leg.Going;
            Go(_target);
        }

        /// <summary>用事を取り消して止める（体を返すとき）</summary>
        public void Stop()
        {
            _leg = Leg.Idle;
            _onDone = null;
            _needsDestination = false;
            if (_agent != null && _agent.enabled && _agent.isOnNavMesh) _agent.isStopped = true;
        }

        void ApplySpec()
        {
            if (_agent == null || spec == null) return;
            _agent.radius = spec.personRadius;
            _agent.height = spec.personHeight;
            _agent.speed = spec.guestSpeed;
            _agent.acceleration = spec.acceleration;
            _agent.angularSpeed = spec.angularSpeedDegPerSec;
            _agent.stoppingDistance = spec.stoppingDistance;
            _agent.obstacleAvoidanceType = spec.avoidanceQuality;
            _agent.avoidancePriority = spec.avoidancePriority;
            _agent.autoRepath = true;
            // 人は人用の NavMesh（半径 0.2 m）を歩く。ロボットは 0.25 m のまま
            PeopleNav.ApplyAgentType(_agent);
            // 客はレジの内側（店員側）に入れない
            _agent.areaMask = PeopleNav.GuestAreaMask(spec);
        }

        void Go(Vector3 point)
        {
            _pending = point;
            _needsDestination = true;
            if (PeopleNav.EnsureReady(transform, _agent) && PeopleNav.Go(_agent, point))
                _needsDestination = false;
        }

        void Update()
        {
            if (_leg == Leg.Idle || spec == null || _agent == null) return;

            // 歩いている段では、着けないまま時間が過ぎたらあきらめる（B1）。
            // NavMesh に乗れない・行き先を入れられないときも時間が進むように、
            // 下の「まだ用意できていない」で戻る前に数える
            if (_leg == Leg.Going || _leg == Leg.Returning)
            {
                _legS += Time.deltaTime;
                if (GiveUpIfLate()) return;
            }

            if (!PeopleNav.EnsureReady(transform, _agent)) return;
            if (_needsDestination && !PeopleNav.Go(_agent, _pending)) return;
            _needsDestination = false;

            if (_leg == Leg.Dwelling)
            {
                _timer += Time.deltaTime;
                if (_timer < _dwellSec) return;
                _timer = 0f;
                if (_returnHome) { _leg = Leg.Returning; Go(_home); }
                else Finish();
                return;
            }

            // ロボットをよけている最中は、行き先がよけ場所にすり替わっているので
            // 「着いた」と見てはいけない
            if (Yielding) return;

            if (_agent.pathPending) return;
            if (_agent.remainingDistance > _agent.stoppingDistance + 0.05f) return;

            if (_leg == Leg.Going)
            {
                if (_errand == Errand.Leave) { Finish(); return; }
                _leg = Leg.Dwelling;
                _timer = 0f;
            }
            else if (_leg == Leg.Returning)
            {
                Finish();
            }
        }

        /// <summary>
        /// 行き先に着けないまま時間が過ぎたとき。
        ///   行き（Going）→ あきらめて席に戻る。帰る客は入口へ移す
        ///   帰り（Returning）→ 席の位置へ移して座らせる
        /// </summary>
        bool GiveUpIfLate()
        {
            if (_leg == Leg.Going)
            {
                if (spec.guestGiveUpSec <= 0f || _legS < spec.guestGiveUpSec) return false;

                _gaveUp = true;
                Record(_target, spec.guestGiveUpSec, _returnHome ? "あきらめた" : "移した");

                if (!_returnHome)
                {
                    // 帰るところだった客は、入口へ移して出たことにする
                    PlaceAt(_target);
                    Finish();
                    return true;
                }
                _leg = Leg.Returning;
                _legS = 0f;
                Go(_home);
                return true;
            }

            if (_leg == Leg.Returning)
            {
                if (spec.guestWarpHomeSec <= 0f || _legS < spec.guestWarpHomeSec) return false;

                // 席にも戻れない。席の位置へ移して座らせる
                _gaveUp = true;
                Record(_home, spec.guestWarpHomeSec, "移した");
                PlaceAt(_home);
                Finish();
                return true;
            }
            return false;
        }

        void Record(Vector3 to, float waitedS, string action)
        {
            if (ops == null) return;
            ops.AddGiveUp("客", ErrandName(_errand), _tableId, to, transform.position, waitedS, action);
        }

        public static string ErrandName(Errand e)
        {
            switch (e)
            {
                case Errand.DrinkBar: return "ドリンクバー";
                case Errand.Toilet: return "トイレ";
                case Errand.Leave: return "退店";
                case Errand.Pay: return "会計";
                default: return "待合";
            }
        }

        void Finish()
        {
            _leg = Leg.Idle;
            System.Action cb = _onDone;
            _onDone = null;
            if (cb != null) cb();
        }
    }
}
