import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { environment } from '../../../environments/environment';
import {CuteLoadingComponent} from "../cute-loading/cute-loading.component";

@Component({
  selector: 'app-api-try-it',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, CuteLoadingComponent],
  templateUrl: './api-try-it.component.html',
  styleUrls: ['./api-try-it.component.css']
})
export class ApiTryItComponent implements OnInit {

  @Input() apiPath: string = '';
  @Input() placeholderValues: { [key: string]: string } = {};
  @Input() requestType: 'GET' | 'POST' = 'GET';
  @Input() postFieldValues: { title: string, type: 'string' | 'number', required: boolean }[] = [];

  form: FormGroup;
  jsonResponse: any;
  errorMessage: string | null = null;
  isLoading = false;

  constructor(private fb: FormBuilder, private http: HttpClient) {
    this.form = this.fb.group({});
  }

  ngOnInit(): void {
    this.createForm();
  }

  createForm(): void {
    const paramRegex = /\{(\w+)\}/g;
    let match;
    while ((match = paramRegex.exec(this.apiPath)) !== null) {
      const placeholderValue = this.placeholderValues[match[1]] || '';
      this.form.addControl(match[1], this.fb.control(placeholderValue, Validators.required));
    }

    if (this.requestType === 'POST') {
      this.postFieldValues.forEach(field => {
        const validators = [];
        if (field.required) {
          validators.push(Validators.required);
        }
        if (field.type === 'number') {
          validators.push(Validators.pattern(/^\d+$/));
        }
        const placeholderValue = this.placeholderValues[field.title] || '';
        this.form.addControl(field.title, this.fb.control(placeholderValue, validators));
      });
    }
  }

  onSubmit(): void {
    this.isLoading = true;
    this.jsonResponse = null;  // Clear any previous response
    let apiUrl = this.apiPath;
    Object.keys(this.form.controls).forEach(key => {
      apiUrl = apiUrl.replace(`{${key}}`, this.form.get(key)?.value);
    });
    const url = `${environment.apiUrl}/${apiUrl}`;

    const headers = new HttpHeaders({
      'X-NISE-API': '20240218',
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    });

    if (this.requestType === 'GET') {
      this.http.get(url, { headers }).subscribe(
        response => {
          this.jsonResponse = response;
          this.errorMessage = null;  // Clear any previous error message
          this.isLoading = false;
        },
        error => {
          this.errorMessage = 'There was an error! ' + error.message;
          console.error('There was an error!', error);
          this.isLoading = false;
        }
      );
    } else if (this.requestType === 'POST') {
      const postData: { [key: string]: any } = {};
      this.postFieldValues.forEach(field => {
        const value = this.form.get(field.title)?.value;
        if (value !== null && value !== '') {
          postData[field.title] = field.type === 'number' ? Number(value) : value;
        }
      });

      let body: any;
      if (postData.hasOwnProperty('body')) {
        body = postData['body'];
      } else {
        body = postData;
      }

      this.http.post(url, body, { headers }).subscribe(
        response => {
          this.jsonResponse = response;
          this.errorMessage = null;  // Clear any previous error message
          this.isLoading = false;
        },
        error => {
          this.errorMessage = 'There was an error! ' + error.message;
          console.error('There was an error!', error);
          this.isLoading = false;
        }
      );
    }
  }
}
