import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  OnDestroy,
  OnInit,
  output,
  signal,
} from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { PaButtonModule, PaTextFieldModule, PaTogglesModule } from '@guillotinaweb/pastanaga-angular';
import { TranslateModule } from '@ngx-translate/core';
import { Session } from '@nuclia/core';
import { ProgressBarComponent } from '@nuclia/sistema';
import {
  resetTestAgent,
  testAgentAnswersByCategory,
  testAgentQuestion,
  testAgentRunning,
  workflowId,
} from '../../workflow.state';
import { AgentBlockComponent, ChipComponent } from './elements';
import { TestPanelService } from './test-panel.service';
import { ParametersTableComponent, SDKService } from '@flaps/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-test-panel',
  imports: [
    ReactiveFormsModule,
    PaButtonModule,
    PaTextFieldModule,
    ChipComponent,
    AgentBlockComponent,
    TranslateModule,
    ProgressBarComponent,
    PaTogglesModule,
    ParametersTableComponent,
    CommonModule,
  ],
  templateUrl: './test-panel.component.html',
  styleUrl: './test-panel.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TestPanelComponent implements OnInit, OnDestroy {
  private service = inject(TestPanelService);
  private sdk = inject(SDKService);
  form = new FormGroup({
    question: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    session: new FormControl('ephemeral', { nonNullable: true, validators: [Validators.required] }),
    useWs: new FormControl(true, { nonNullable: true }),
  });
  headers: { key: string; value: string }[] = [];

  isAragWithMemory = this.sdk.isAragWithMemory;

  get question() {
    return this.form.controls.question;
  }
  get session() {
    return this.form.controls.session;
  }
  get useWs() {
    return this.form.controls.useWs.getRawValue();
  }

  cancel = output();

  // Method for parent to call when closing the panel
  onPanelClose() {
    if (this.runningTest()) {
      this.triggerStop();
    }
    this.resetTestState();
    this.cancel.emit();
  }

  sessions = signal<Session[]>([]);
  runningTest = testAgentRunning;
  runningQuestion = testAgentQuestion;
  rawAnswers = testAgentAnswersByCategory;

  stopDisabled = computed(() => this.runningTest() === false || !this.useWs);

  constructor() {
    effect(() => {
      if (this.runningTest()) {
        this.form.disable();
      } else {
        this.form.enable();
      }
    });
  }

  ngOnInit(): void {
    this.service.getTestSessions().subscribe((sessions) => this.sessions.set(sessions));
  }

  triggerRun() {
    if (this.question.valid) {
      const question = this.question.getRawValue().trim();
      this.service.runTest(
        question,
        this.session.getRawValue(),
        workflowId() || '',
        this.useWs,
        undefined,
        this.headers.reduce(
          (all, current) => {
            all[current.key] = current.value;
            return all;
          },
          {} as { [key: string]: string },
        ),
      );
    }
  }

  triggerStop() {
    this.service.stopTest();
  }

  ngOnDestroy() {
    // Stop the test and reset all state when component is destroyed
    if (this.runningTest()) {
      this.triggerStop();
    }
    this.resetTestState();
  }

  private resetTestState() {
    // Reset the test agent state and form
    resetTestAgent();
    this.form.reset({
      question: '',
      session: 'ephemeral',
      useWs: true,
    });
  }
}
