import { assert } from '@esm-bundle/chai'
import sinon from 'sinon'
import { fixture, html } from '@open-wc/testing'
import { Activity } from '../../src/core/Activity.js'
import { Application } from '../../src/core/Application.js'
import {
  ActivityManager,
  ActivityLifecycle,
  IntentFlags,
  IntentResult,
  type Intent,
} from '../../src/core/ActivityManager.js'

class TestActivity extends Activity {
  static override action = 'test-activity'
  override onCreate = sinon.stub().resolves()
  override onStart = sinon.stub().resolves()
  override onResume = sinon.stub().resolves()
  override onPause = sinon.stub().resolves()
  override onStop = sinon.stub().resolves()
  override onRestart = sinon.stub().resolves()
  override onDestroy = sinon.stub().resolves()
  override onNewIntent = sinon.stub().resolves()
  override onActivityResult = sinon.stub().resolves()

  override setResult = sinon.spy(super.setResult) // Spy on the actual implementation
  override getResult = sinon.spy(super.getResult)
  override hasRequestCode = sinon.spy(super.hasRequestCode)

  // Helper to reset stubs for each test
  resetStubs() {
    this.onCreate.resetHistory()
    this.onStart.resetHistory()
    this.onResume.resetHistory()
    this.onPause.resetHistory()
    this.onStop.resetHistory()
    this.onRestart.resetHistory()
    this.onDestroy.resetHistory()
    this.onNewIntent.resetHistory()
    this.onActivityResult.resetHistory()
    this.setResult.resetHistory()
    this.getResult.resetHistory()
    this.hasRequestCode.resetHistory()
    this.lifecycle = ActivityLifecycle.Initialized
    this.pendingRequestCodes.length = 0
    this.exitCode = IntentResult.RESULT_CANCELED
    this.resultData = undefined
  }
}

class TestActivity2 extends TestActivity {
  static override action = 'test-activity-2'
}

class TestApplication extends Application {
  requestUpdateSpy = sinon.spy(this, 'requestUpdate')

  override async onStart(): Promise<void> {}
}

async function basicFixture(): Promise<HTMLElement> {
  return fixture(html`<div id="app"></div>`)
}

describe('ActivityManager', () => {
  let app: TestApplication
  let manager: ActivityManager
  // let navigateScreenStub: sinon.SinonStub

  beforeEach(async () => {
    const renderRoot = await basicFixture()
    app = new TestApplication(renderRoot)
    manager = app.manager
    manager.registerActivity(TestActivity.action, TestActivity)
    manager.registerActivity(TestActivity2.action, TestActivity2)
    // navigateScreenStub = sinon.stub(ApplicationRoute, 'navigateScreen')
    // Clear any classes added by previous tests
    if (document.documentElement) {
      document.documentElement.className = ''
    }
  })

  afterEach(() => {
    sinon.restore()
  })

  describe('registerActivity()', () => {
    it('registers an activity class', () => {
      const newAction = 'new-test-activity'
      class NewTestActivity extends Activity {
        static override action = newAction
      }
      manager.registerActivity(newAction, NewTestActivity)
      assert.isTrue(manager['activityClasses'].has(newAction))
      assert.strictEqual(manager['activityClasses'].get(newAction), NewTestActivity)
    })

    it('warns if an activity with the same action is already registered', () => {
      const consoleWarnSpy = sinon.stub(console, 'warn')
      manager.registerActivity(TestActivity.action, TestActivity) // Registering again
      consoleWarnSpy.restore()
      assert.isTrue(consoleWarnSpy.calledOnce)
      assert.include(
        consoleWarnSpy.firstCall.args[0],
        `Activity with action "${TestActivity.action}" already registered.`
      )
    })
  })

  describe('createActivity()', () => {
    it('creates an activity and adds it to the stack without starting it', async () => {
      const intent: Intent = { action: TestActivity.action }
      await manager.createActivity(intent)
      assert.equal(manager['activityStack'].length, 1)
      const entry = manager['activityStack'][0]
      assert.instanceOf(entry.activity, TestActivity)
      assert.equal(entry.activity.lifecycle, ActivityLifecycle.Initialized)
      assert.strictEqual(entry.intent, intent)
      assert.isUndefined(manager.getCurrentActivity())
    })

    it('throws if activity class is not registered', async () => {
      const intent: Intent = { action: 'unknown-action' }
      try {
        await manager.createActivity(intent)
        assert.fail('Should have thrown an error')
      } catch (e) {
        assert.equal((e as Error).message, 'No activity class registered for action: unknown-action')
      }
    })
  })

  describe('startActivity()', () => {
    it('starts a new activity, no current activity', async () => {
      const intent: Intent = { action: TestActivity.action }
      await manager.startActivity(intent)

      assert.equal(manager['activityStack'].length, 1)
      const entry = manager['activityStack'][0]
      assert.instanceOf(entry.activity, TestActivity)
      assert.strictEqual(manager.getCurrentActivity(), entry.activity)
      assert.isTrue((entry.activity as TestActivity).onCreate.calledOnceWith(intent))
      assert.isTrue((entry.activity as TestActivity).onStart.calledOnce)
      assert.isTrue((entry.activity as TestActivity).onResume.calledOnce)
      assert.equal(entry.activity.lifecycle, ActivityLifecycle.Resumed)
      // assert.isFalse(navigateScreenStub.called) // No URI in intent
    })

    it('starts a new activity with URI in intent', async () => {
      const uri = '/test/start'
      const intent: Intent = { action: TestActivity.action, data: { uri } }
      await manager.startActivity(intent)
      // assert.isTrue(navigateScreenStub.calledOnceWith(uri))
    })

    it('starts a new activity, with a current activity', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity

      const intent2: Intent = { action: TestActivity2.action }
      await manager.startActivity(intent2)
      const activity2 = manager.getCurrentActivity() as TestActivity
      assert.isTrue(activity1.onPause.calledOnce, 'activity1 onPause should be called once')
      assert.equal(activity1.lifecycle, ActivityLifecycle.Paused, 'activity1 should be paused')

      assert.isTrue(activity2.onCreate.calledOnceWith(intent2), 'activity2 onCreate should be called with intent')
      assert.isTrue(activity2.onStart.calledOnce, 'activity2 onStart should be called once')
      assert.isTrue(activity2.onResume.calledOnce, 'activity2 onResume should be called once')
      assert.equal(activity2.lifecycle, ActivityLifecycle.Resumed, 'activity2 should be resumed')
      assert.equal(manager['activityStack'].length, 2, 'activity stack should have 2 activities')
    })

    it('brings an existing activity from stack to front and calls onNewIntent', async () => {
      const intent1: Intent = { action: TestActivity.action, data: { initial: true } }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity
      activity1.resetStubs()

      const intent2: Intent = { action: TestActivity2.action }
      await manager.startActivity(intent2)
      const activity2 = manager.getCurrentActivity() as TestActivity

      // activity1 is now paused, activity2 is resumed
      assert.equal(activity1.lifecycle, ActivityLifecycle.Paused, 'activity1 should be paused')
      assert.equal(activity2.lifecycle, ActivityLifecycle.Resumed, 'activity2 should be resumed')

      const newIntentForActivity1: Intent = { action: TestActivity.action, data: { updated: true } }
      await manager.startActivity(newIntentForActivity1)

      assert.strictEqual(manager.getCurrentActivity(), activity1)
      assert.isTrue(activity1.onNewIntent.calledOnceWith(newIntentForActivity1), 'activity1 called with new intent')
      assert.isTrue(activity1.onResume.calledOnce, 'activity1 onResume called once') // Should be resumed
      assert.equal(activity1.lifecycle, ActivityLifecycle.Resumed, 'activity1 should be resumed')

      assert.isTrue(activity2.onPause.calledOnce, 'activity2 paused once') // activity2 should be paused
      assert.equal(activity2.lifecycle, ActivityLifecycle.Paused, 'activity2 should be paused')

      assert.equal(manager['activityStack'].length, 2, 'activityStack is the same') // Stack size remains the same
      assert.strictEqual(manager['activityStack'][1].activity, activity1) // activity1 is now at the top
      assert.deepEqual(manager['activityStack'][1].intent, newIntentForActivity1)
    })

    it('starts a modal activity', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity

      const modalIntent: Intent = { action: TestActivity2.action, flags: IntentFlags.Modal }
      await manager.startActivity(modalIntent)

      const modalActivity = manager['modalActivityStack'][0].activity as TestActivity2
      assert.equal(manager['modalActivityStack'].length, 1)
      assert.strictEqual(manager['modalActivityStack'][0].activity, modalActivity)

      assert.isTrue(activity1.onPause.calledOnce)
      assert.equal(activity1.lifecycle, ActivityLifecycle.Paused)
      // For modal, currentActivity in manager should still be the underlying one
      assert.strictEqual(manager.getCurrentActivity(), activity1)

      assert.isTrue(modalActivity.onCreate.calledOnceWith(modalIntent))
      assert.isTrue(modalActivity.onStart.calledOnce)
      assert.isTrue(modalActivity.onResume.calledOnce)
      assert.equal(modalActivity.lifecycle, ActivityLifecycle.Resumed)
    })

    it('throws if activity class is not registered', async () => {
      const intent: Intent = { action: 'unknown-action' }
      try {
        await manager.startActivity(intent)
        assert.fail('Should have thrown an error')
      } catch (e) {
        assert.equal((e as Error).message, 'No activity class registered for action: unknown-action')
      }
    })
  })

  describe('startActivityForResult()', () => {
    it('starts activity with ForResult flag and requestCode', async () => {
      const startActivitySpy = sinon.spy(manager, 'startActivity')
      const intent: Intent = { action: TestActivity.action, data: { test: 1 } }
      const requestCode = 123

      await manager.startActivityForResult(intent, requestCode)

      assert.isTrue(startActivitySpy.calledOnce, 'startActivity should be called once')
      const calledIntent = startActivitySpy.firstCall.args[0]
      assert.equal(calledIntent.action, TestActivity.action, 'Intent action should match')
      assert.deepEqual(calledIntent.data, { test: 1 }, 'Intent data should match')
      assert.equal(calledIntent.requestCode, requestCode, 'Request code should match')
      assert.isNumber(calledIntent.flags, 'Flags should be defined')
      assert.isTrue(!!(calledIntent.flags! & IntentFlags.ForResult), 'ForResult flag should be set')
    })

    it('clones intent data by default', async () => {
      const startActivitySpy = sinon.spy(manager, 'startActivity')
      const originalData = { test: 1 }
      const intent: Intent = { action: TestActivity.action, data: originalData }
      const requestCode = 123

      await manager.startActivityForResult(intent, requestCode)
      const calledIntent = startActivitySpy.firstCall.args[0]
      assert.notStrictEqual(calledIntent.data, originalData)
      assert.deepEqual(calledIntent.data, originalData)
      intent.action = 'other'
      ;(intent.data as { test: number }).test = 2
      assert.equal(calledIntent.action, TestActivity.action, 'Intent action should be cloned, not by reference')
      assert.deepEqual(calledIntent.data, { test: 1 }, 'Intent data should be cloned, not by reference')
    })

    it('passes intent data by reference if ByReference flag is set', async () => {
      const startActivitySpy = sinon.spy(manager, 'startActivity')
      const originalData = { test: 1 }
      const intent: Intent = { action: TestActivity.action, data: originalData, flags: IntentFlags.ByReference }
      const requestCode = 123
      await manager.startActivityForResult(intent, requestCode)
      const calledIntent = startActivitySpy.firstCall.args[0]
      assert.strictEqual(calledIntent.data, originalData, 'data is passed by reference')
      assert.isTrue(!!(calledIntent.flags && calledIntent.flags & IntentFlags.ByReference), 'has the ByReference flag')
      assert.isTrue(!!(calledIntent.flags && calledIntent.flags & IntentFlags.ForResult), 'has the ForResult flag')

      intent.action = 'other'
      originalData.test = 2
      assert.equal(calledIntent.action, TestActivity.action, 'Intent action should be cloned, not by reference')
      assert.deepEqual(calledIntent.data, { test: 2 }, 'Intent data should be passed by reference')
    })
  })

  describe('finishActivity()', () => {
    it('finishes the current activity and resumes the previous one', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity

      const intent2: Intent = { action: TestActivity2.action }
      await manager.startActivity(intent2)
      const activity2 = manager.getCurrentActivity() as TestActivity2
      activity1.resetStubs() // activity1 was paused
      await manager.finishActivity(activity2)

      assert.isTrue(activity2.onPause.calledOnce, 'activity2 onPause should be called once')
      assert.isTrue(activity2.onStop.calledOnce, 'activity2 onStop should be called once')
      assert.isTrue(activity2.onDestroy.calledOnce, 'activity2 onDestroy should be called once')
      assert.equal(activity2.lifecycle, ActivityLifecycle.Destroyed, 'activity2 should be destroyed')

      assert.strictEqual(manager.getCurrentActivity(), activity1)
      assert.isTrue(activity1.onResume.calledOnce, 'activity1 onResume should be called once')
      assert.equal(activity1.lifecycle, ActivityLifecycle.Resumed, 'activity1 should be resumed')
      assert.equal(manager['activityStack'].length, 1, 'activity stack should have 1 activity')
      assert.isTrue(app.requestUpdateSpy.called, 'Application should request update after finishing activity')
    })

    it('finishes a modal activity and resumes the underlying activity', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity

      const modalIntent: Intent = { action: TestActivity2.action, flags: IntentFlags.Modal }
      await manager.startActivity(modalIntent)
      const modalActivity = manager['modalActivityStack'][0].activity as TestActivity2
      activity1.resetStubs() // activity1 was paused

      await manager.finishActivity(modalActivity)

      assert.isTrue(modalActivity.onPause.calledOnce)
      assert.isTrue(modalActivity.onStop.calledOnce)
      assert.isTrue(modalActivity.onDestroy.calledOnce)
      assert.equal(modalActivity.lifecycle, ActivityLifecycle.Destroyed)
      assert.equal(manager['modalActivityStack'].length, 0)

      assert.strictEqual(manager.getCurrentActivity(), activity1) // Current activity should be the underlying one
      assert.isTrue(activity1.onResume.calledOnce)
      assert.equal(activity1.lifecycle, ActivityLifecycle.Resumed)
      assert.equal(manager['activityStack'].length, 1)
    })

    it('manages activity result if activity was started for result', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity
      const requestCode = await activity1.startActivityForResult({ action: TestActivity2.action })
      // activity1 starts activity2

      // manager.startActivityForResult calls manager.startActivity, which sets currentActivity
      // So, activity2 is now the "current" in terms of lifecycle, but activity1 is the one expecting a result.
      const activity2 = manager['activityStack'].find((e) => e.action === TestActivity2.action)
        ?.activity as TestActivity2
      assert.ok(activity2, 'Activity2 should be on stack')

      const resultData = { success: true }
      activity2.setResult(IntentResult.RESULT_OK, resultData)

      await manager.finishActivity(activity2)

      assert.isTrue(activity1.onActivityResult.calledOnce)
      const [calledRequestCode, calledResultCode, calledIntent] = activity1.onActivityResult.firstCall.args
      assert.equal(calledRequestCode, requestCode)
      assert.equal(calledResultCode, IntentResult.RESULT_OK)
      assert.deepEqual(calledIntent.data, resultData)
      assert.equal(calledIntent.action, TestActivity2.action)
    })

    it('handles finishing an activity that was only created (not fully started)', async () => {
      const activity = new TestActivity(app)
      activity.lifecycle = ActivityLifecycle.Created // Manually set for test

      await manager.finishActivity(activity)

      assert.isTrue(activity.onStop.calledOnce, 'onStop should be called for created activity')
      assert.isTrue(activity.onDestroy.calledOnce, 'onDestroy should be called')
      assert.equal(activity.lifecycle, ActivityLifecycle.Destroyed)
      assert.isUndefined(manager.getCurrentActivity()) // Assuming no other activities
    })

    it('finishes the last activity on the stack', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity() as TestActivity

      await manager.finishActivity(activity1)

      assert.isTrue(activity1.onDestroy.calledOnce)
      assert.equal(activity1.lifecycle, ActivityLifecycle.Destroyed)
      assert.isUndefined(manager.getCurrentActivity())
      assert.equal(manager['activityStack'].length, 0)
    })
  })

  describe('getTopActivity()', () => {
    it('returns undefined if no activities are resumed', () => {
      assert.isUndefined(manager.getTopActivity())
    })

    it('returns the top resumed regular activity', async () => {
      await manager.startActivity({ action: TestActivity.action })
      const activity1 = manager['activityStack'][0].activity
      activity1.lifecycle = ActivityLifecycle.Resumed // Ensure it's resumed

      await manager.startActivity({ action: TestActivity2.action })
      const activity2 = manager['activityStack'][1].activity
      activity2.lifecycle = ActivityLifecycle.Resumed // Ensure it's resumed

      assert.strictEqual(manager.getTopActivity(), activity2)
    })

    it('returns the top resumed modal activity if present', async () => {
      await manager.startActivity({ action: TestActivity.action }) // Regular activity
      const regularActivity = manager['activityStack'][0].activity
      regularActivity.lifecycle = ActivityLifecycle.Resumed

      await manager.startActivity({ action: TestActivity2.action, flags: IntentFlags.Modal })
      const modalActivity = manager['modalActivityStack'][0].activity
      modalActivity.lifecycle = ActivityLifecycle.Resumed // Ensure it's resumed

      assert.strictEqual(manager.getTopActivity(), modalActivity)
    })

    it('returns regular activity if modal is not resumed', async () => {
      await manager.startActivity({ action: TestActivity.action })
      const regularActivity = manager['activityStack'][0].activity

      await manager.startActivity({ action: TestActivity2.action, flags: IntentFlags.Modal })
      const modalActivity = manager['modalActivityStack'][0].activity
      modalActivity.lifecycle = ActivityLifecycle.Paused // Not resumed
      regularActivity.lifecycle = ActivityLifecycle.Resumed
      assert.strictEqual(manager.getTopActivity(), regularActivity)
    })
  })

  describe('getCurrentActivity()', () => {
    it('returns undefined initially', () => {
      assert.isUndefined(manager.getCurrentActivity())
    })

    it('returns the current activity after startActivity', async () => {
      const intent: Intent = { action: TestActivity.action }
      await manager.startActivity(intent)
      assert.instanceOf(manager.getCurrentActivity(), TestActivity)
    })
  })

  describe('setupStyles()', () => {
    it('adds activity class name and action to documentElement classList', async () => {
      const intent: Intent = { action: TestActivity.action }
      await manager.startActivity(intent) // This calls setupStyles internally
      const activity = manager.getCurrentActivity()!
      const ctor = activity.constructor as typeof Activity

      assert.isTrue(document.documentElement.classList.contains(ctor.name.toLowerCase()))
      assert.isTrue(document.documentElement.classList.contains(ctor.action!.replace(/\//g, '-')))
    })

    it('removes old activity classes and adds new ones on activity change', async () => {
      const intent1: Intent = { action: TestActivity.action }
      await manager.startActivity(intent1)
      const activity1 = manager.getCurrentActivity()!
      const ctor1 = activity1.constructor as typeof Activity

      const intent2: Intent = { action: TestActivity2.action }
      await manager.startActivity(intent2)
      const activity2 = manager.getCurrentActivity()!
      const ctor2 = activity2.constructor as typeof Activity

      assert.isFalse(document.documentElement.classList.contains(ctor1.name.toLowerCase()))
      assert.isFalse(document.documentElement.classList.contains(ctor1.action!.replace(/\//g, '-')))
      assert.isTrue(document.documentElement.classList.contains(ctor2.name.toLowerCase()))
      assert.isTrue(document.documentElement.classList.contains(ctor2.action!.replace(/\//g, '-')))
    })

    it('does nothing if activity is the same as oldActivity', () => {
      const activity = new TestActivity(app)
      document.documentElement.classList.add('initial-class')
      manager.setupStyles(activity, activity)
      assert.isTrue(document.documentElement.classList.contains('initial-class'))
      assert.equal(document.documentElement.classList.length, 1) // No classes added or removed
    })

    it('clears styles if old activity is provided and new one is not', () => {
      const oldActivity = new TestActivity(app)
      const ctorOld = oldActivity.constructor as typeof Activity
      document.documentElement.classList.add(ctorOld.name.toLowerCase())
      document.documentElement.classList.add(ctorOld.action!.replace(/\//g, '-'))

      manager.setupStyles(undefined, oldActivity)

      assert.isFalse(document.documentElement.classList.contains(ctorOld.name.toLowerCase()))
      assert.isFalse(document.documentElement.classList.contains(ctorOld.action!.replace(/\//g, '-')))
    })
  })

  describe('navigateBack()', () => {
    it('finishes current activity if stack has more than one activity', async () => {
      await manager.startActivity({ action: TestActivity.action })
      await manager.startActivity({ action: TestActivity2.action }) // Now 2 activities

      const finishActivitySpy = sinon.spy(manager, 'finishActivity')
      const activity2 = manager.getCurrentActivity()!

      await manager.navigateBack()

      assert.isTrue(finishActivitySpy.calledOnceWith(activity2))
      assert.instanceOf(manager.getCurrentActivity(), TestActivity) // Back to activity1
    })

    it('does nothing if only one or no activity on stack', async () => {
      const finishActivitySpy = sinon.spy(manager, 'finishActivity')

      await manager.navigateBack() // No activities
      assert.isFalse(finishActivitySpy.called)

      await manager.startActivity({ action: TestActivity.action }) // One activity
      await manager.navigateBack()
      assert.isFalse(finishActivitySpy.called) // Still one activity, finish not called by navigateBack
    })
  })

  describe('createRequestCode()', () => {
    it('generates a random number between 1000 and 9999', () => {
      const code = manager.createRequestCode()
      assert.isNumber(code)
      assert.isAtLeast(code, 1000)
      assert.isAtMost(code, 9999)
    })

    it('generates different codes on subsequent calls (highly likely)', () => {
      const code1 = manager.createRequestCode()
      const code2 = manager.createRequestCode()
      assert.notEqual(code1, code2) // Statistically very unlikely to be equal
    })
  })

  describe('findActiveActivity()', () => {
    it('returns undefined if no activity with the action is found', () => {
      assert.isUndefined(manager.findActiveActivity(TestActivity.action))
    })

    it('returns the activity if found in the stack', async () => {
      const intent: Intent = { action: TestActivity.action }
      await manager.startActivity(intent)
      const activity = manager.getCurrentActivity()
      assert.strictEqual(manager.findActiveActivity(TestActivity.action), activity)
    })
  })
})
