/// <reference types="cypress" />

import makeFakeUser from '../../factories/user';

describe('Leave Session Modal', () => {
  const currentUser = makeFakeUser();

  beforeEach(() => {
    cy.stubAuthenticate({ id: currentUser.id });
    cy.stubGonSubscriptionCodes();
  });

  describe('Leave Session Button', () => {
    it('should display the Leave Session button with correct styling', () => {
      // Mock the session context and other dependencies
      cy.window().then((win) => {
        // Mock the necessary context providers
        win.JK = win.JK || {};
        win.JK.GA = win.JK.GA || { trackSessionMusicians: cy.stub() };
      });

      // Visit a mock session page (this would need to be set up properly in a real scenario)
      cy.visit('/client#/session/test-session-id', {
        onBeforeLoad: (win) => {
          // Mock React context and hooks
          win.React = { useContext: cy.stub(), useState: cy.stub(), useEffect: cy.stub() };
        }
      });

      // The button should be visible and have primary color
      cy.contains('Leave Session').should('be.visible');
      cy.contains('Leave Session').should('have.class', 'btn-primary');
    });
  });

  describe('Leave Session Modal', () => {
    beforeEach(() => {
      // Mock the modal opening by simulating the button click
      cy.window().then((win) => {
        win.JK = win.JK || {};
        win.JK.GA = win.JK.GA || { trackSessionMusicians: cy.stub() };
      });

      cy.visit('/client#/session/test-session-id');
    });

    it('should open modal when Leave Session button is clicked', () => {
      // Mock the sessionModel.handleLeaveSession to resolve immediately
      cy.window().then((win) => {
        if (win.sessionModel && win.sessionModel.handleLeaveSession) {
          cy.stub(win.sessionModel, 'handleLeaveSession').resolves();
        }
      });

      cy.contains('Leave Session').click();

      // Modal should appear
      cy.contains('Rate Your Session').should('be.visible');
      cy.contains('Thank you for using JamKazam!').should('be.visible');
    });

    it('should display rating buttons', () => {
      cy.contains('Leave Session').click();

      // Check thumbs up and thumbs down buttons are present
      cy.get('[data-cy=thumbs-up-btn]').should('be.visible');
      cy.get('[data-cy=thumbs-down-btn]').should('be.visible');
    });

    it('should allow selecting thumbs up rating', () => {
      cy.contains('Leave Session').click();

      // Click thumbs up
      cy.get('[data-cy=thumbs-up-btn]').click();

      // Should be selected (success color)
      cy.get('[data-cy=thumbs-up-btn]').should('have.class', 'btn-success');
      cy.get('[data-cy=thumbs-down-btn]').should('not.have.class', 'btn-danger');
    });

    it('should allow selecting thumbs down rating', () => {
      cy.contains('Leave Session').click();

      // Click thumbs down
      cy.get('[data-cy=thumbs-down-btn]').click();

      // Should be selected (danger color)
      cy.get('[data-cy=thumbs-down-btn]').should('have.class', 'btn-danger');
      cy.get('[data-cy=thumbs-up-btn]').should('not.have.class', 'btn-success');
    });

    it('should allow toggling rating selection', () => {
      cy.contains('Leave Session').click();

      // Click thumbs up
      cy.get('[data-cy=thumbs-up-btn]').click();
      cy.get('[data-cy=thumbs-up-btn]').should('have.class', 'btn-success');

      // Click again to deselect
      cy.get('[data-cy=thumbs-up-btn]').click();
      cy.get('[data-cy=thumbs-up-btn]').should('not.have.class', 'btn-success');
    });

    it('should display comments textarea', () => {
      cy.contains('Leave Session').click();

      cy.get('[data-cy=comments-textarea]').should('be.visible');
      cy.get('[data-cy=comments-textarea]').should('have.attr', 'placeholder', 'Optional feedback...');
    });

    it('should allow typing in comments', () => {
      cy.contains('Leave Session').click();

      const testComment = 'This is a test comment for the session feedback.';
      cy.get('[data-cy=comments-textarea]').type(testComment);
      cy.get('[data-cy=comments-textarea]').should('have.value', testComment);
    });

    it('should disable Send Feedback button when no rating or comments provided', () => {
      cy.contains('Leave Session').click();

      cy.get('[data-cy=send-feedback-btn]').should('be.disabled');
    });

    it('should enable Send Feedback button when rating is selected', () => {
      cy.contains('Leave Session').click();

      cy.get('[data-cy=thumbs-up-btn]').click();
      cy.get('[data-cy=send-feedback-btn]').should('not.be.disabled');
    });

    it('should enable Send Feedback button when comments are provided', () => {
      cy.contains('Leave Session').click();

      cy.get('[data-cy=comments-textarea]').type('Test comment');
      cy.get('[data-cy=send-feedback-btn]').should('not.be.disabled');
    });

    it('should submit feedback successfully', () => {
      // Mock the API call
      cy.intercept('POST', '**/participant_histories/*/rating', {
        statusCode: 200,
        body: { success: true }
      }).as('submitFeedback');

      cy.contains('Leave Session').click();

      // Fill out the form
      cy.get('[data-cy=thumbs-up-btn]').click();
      cy.get('[data-cy=comments-textarea]').type('Great session!');

      // Submit
      cy.get('[data-cy=send-feedback-btn]').click();

      // Should show success toast
      cy.contains('Thank you for your feedback!').should('be.visible');

      // Modal should close
      cy.contains('Rate Your Session').should('not.exist');
    });

    it('should handle feedback submission error', () => {
      // Mock API error
      cy.intercept('POST', '**/participant_histories/*/rating', {
        statusCode: 500,
        body: { error: 'Server error' }
      }).as('submitFeedbackError');

      cy.contains('Leave Session').click();

      cy.get('[data-cy=thumbs-down-btn]').click();
      cy.get('[data-cy=send-feedback-btn]').click();

      // Should show error toast
      cy.contains('Failed to submit feedback').should('be.visible');
    });

    it('should close modal when Cancel button is clicked', () => {
      cy.contains('Leave Session').click();

      cy.get('[data-cy=cancel-btn]').click();

      // Modal should close
      cy.contains('Rate Your Session').should('not.exist');
    });

    it('should close modal when X button is clicked', () => {
      cy.contains('Leave Session').click();

      // Click the modal close button (usually has class 'close' or 'btn-close')
      cy.get('.modal-header .close').click();

      // Modal should close
      cy.contains('Rate Your Session').should('not.exist');
    });
  });

  describe('Form Validation', () => {
    it('should require at least rating or comments to submit', () => {
      cy.contains('Leave Session').click();

      // Button should be disabled initially
      cy.get('[data-cy=send-feedback-btn]').should('be.disabled');

      // Add rating - should enable
      cy.get('[data-cy=thumbs-up-btn]').click();
      cy.get('[data-cy=send-feedback-btn]').should('not.be.disabled');

      // Remove rating, add comments - should enable
      cy.get('[data-cy=thumbs-up-btn]').click(); // deselect
      cy.get('[data-cy=comments-textarea]').type('Test comment');
      cy.get('[data-cy=send-feedback-btn]').should('not.be.disabled');

      // Remove comments - should disable
      cy.get('[data-cy=comments-textarea]').clear();
      cy.get('[data-cy=send-feedback-btn]').should('be.disabled');
    });
  });
});
