import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environments } from '../../../../environments/environments';

export interface FormConfiguration {
  title: string;
  tabs: {
    id: string;
    title: string;
    rows: number;
    columns: number;
    elements: {
      position: { row: number; col: number };
      element: {
        type: string;
        label: string;
        required: boolean;
        placeholder?: string;
        id?: string;
        name?: string;
        value?: string;
        description?: string;
        options?: string[];
        min?: number;
        max?: number;
        pattern?: string;
      };
    }[];
  }[];
}

export interface FormListItem {
  id: number;
  title: string;
  is_published: boolean;
  created_at: string;
  updated_at: string;
}

export interface FormResponse {
  id?: number;
  form_id: number;
  responses: { [key: string]: any };
  created_at?: string;
}

@Injectable({
  providedIn: 'root'
})
export class FormApiService {
  private apiUrl = environments.baseUrl;

  constructor(private http: HttpClient) {}

  // Encabezados reutilizables con token
  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('token') || '';
    return new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': `Bearer ${token}`
    });
  }

  // Obtener todos los formularios
  getForms(): Observable<FormListItem[]> {
    return this.http.get<FormListItem[]>(`${this.apiUrl}/formularios`, {
      headers: this.getHeaders()
    });
  }

  // Crear un nuevo formulario
  createForm(formData: FormConfiguration): Observable<any> {
    return this.http.post<any>(`${this.apiUrl}/createForm`, formData, {
      headers: this.getHeaders()
    });
  }

  // Obtener un formulario específico
  getForm(id: number): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/obtener/${id}`, {
      headers: this.getHeaders()
    });
  }

  // Publicar un formulario
  publishForm(id: number): Observable<any> {
    return this.http.put<any>(`${this.apiUrl}/${id}/publish`, {}, {
      headers: this.getHeaders()
    });
  }

  // Guardar respuesta de un formulario
  saveResponse(formId: number, responses: { [key: string]: any }): Observable<any> {
    const responseData = {
      form_id: formId,
      responses: responses
    };
    return this.http.post<any>(`${this.apiUrl}/${formId}/responses`, responseData, {
      headers: this.getHeaders()
    });
  }

  // Obtener respuestas de un formulario
  getResponses(formId: number): Observable<FormResponse[]> {
    return this.http.get<FormResponse[]>(`${this.apiUrl}/${formId}/responses`, {
      headers: this.getHeaders()
    });
  }
}
