import { Component, OnInit, ViewChild } from '@angular/core';
import { FormService } from '../../../services/FormService.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EnviarInfoService } from '../../../services/enviar-info.service';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';


interface Form {
  id: number;
  title: string;
  configuration: any;
}

interface GetAllFormsResponse {
  success: boolean;
  forms: Form[];
}

@Component({
  selector: 'app-form-selector',
  templateUrl: './form-selector.component.html',
  styleUrl: './form-selector.component.css'
})
export class FormSelectorComponent implements OnInit {
    color: string = '';
  textColor: string = '';
  formTitle: string = '';
  forms: any[] = [];
 dataSource = new MatTableDataSource<any>([]);
displayedColumns: string[] = ['id', 'title', 'ver', 'editar', 'publicar', 'eliminar'];
  selectedFormId: number | null = null;
  isLoading = false;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(private formService: FormService, private _enviarInfo: EnviarInfoService, private router: Router,  private snackBar: MatSnackBar
  ) {}
    get hayFormularioPublicado(): boolean {
    return this.dataSource.data.some(f => f.is_published);
  }

  ngOnInit(): void {
      this._enviarInfo.currentTextColor.subscribe(color => this.textColor = color);
    this._enviarInfo.currentColor.subscribe(color => this.color = color);
    this.loadForms();
  }

loadForms(): void {
    this.isLoading = true;
    this.formService.getAllForms().subscribe({
      next: (res) => {
this.dataSource.data = (res.forms || []).sort((a: { id: number; }, b: { id: number; }) => b.id - a.id);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        this.isLoading = false;
      },
      error: (err) => {
        console.error('Error cargando formularios:', err);
        this.isLoading = false;
      }
    });
  }

  applyFilter(event: any): void {
    const filterValue = (event.target.value || '').trim().toLowerCase();
    this.dataSource.filter = filterValue;
  }

  selectForm(id: number): void {
  this.router.navigate(['homeAdmin/visualizarForm',id]);
  }
deleteForm(id: number) {
  if (confirm('¿Estás seguro de que deseas eliminar este formulario?')) {
    this.formService.deleteForm(id).subscribe({
      next: (res) => {
        console.log('Formulario eliminado:', res);
        this.loadForms();
        this.showMessage('Formulario eliminado correctamente');
      },
      error: (err) => {
        console.error('Error al eliminar formulario:', err);
        this.showMessage('Error al eliminar el formulario');
      }
    });
  }
}

editForm(id: number) {
  this.router.navigate(['homeAdmin/formularios'], { queryParams: { id } });
  this.showMessage('Cargando formulario para editar...');
}

showMessage(message: string) {
  this.snackBar.open(message, 'Cerrar', {
    duration: 3000, // 3 segundos
    horizontalPosition: 'right',
    verticalPosition: 'top'
  });
}publicarFormulario(formId: number): void {
  this.isLoading = true;

  // Primero despublicamos cualquier otro formulario publicado antes de publicar el nuevo
  const formPublicado = this.dataSource.data.find(f => f.is_published);

  const despublicar$ = formPublicado && formPublicado.id !== formId
    ? this.formService.unpublishForm(formPublicado.id)
    : null;

  const publicar$ = () => this.formService.publishForm(formId);

  if (despublicar$) {
    despublicar$.subscribe({
      next: () => {
        publicar$().subscribe({
          next: () => {
            this.updateFormsAfterPublish(formId);
          },
          error: (err) => this.handleError(err, 'Error al publicar el formulario.')
        });
      },
      error: (err) => this.handleError(err, 'Error al despublicar el formulario anterior.')
    });
  } else {
    publicar$().subscribe({
      next: () => {
        this.updateFormsAfterPublish(formId);
      },
      error: (err) => this.handleError(err, 'Error al publicar el formulario.')
    });
  }
}

updateFormsAfterPublish(formId: number) {
  // Actualiza todos los formularios: solo el publicado queda true, los demás false
  this.dataSource.data = this.dataSource.data.map(f => ({
    ...f,
    is_published: f.id === formId
  }));
  this.isLoading = false;
  this.showMessage('Formulario publicado correctamente. Solo uno puede estar publicado a la vez.');
}

despublicarFormulario(formId: number): void {
  this.isLoading = true;
  this.formService.unpublishForm(formId).subscribe({
    next: () => {
      const form = this.dataSource.data.find(f => f.id === formId);
      if (form) {
        form.is_published = false;
      }
      this.dataSource.data = [...this.dataSource.data];
      this.isLoading = false;
      this.showMessage('Formulario despublicado correctamente.');
    },
    error: (err) => {
      this.isLoading = false;
      console.error('Error al despublicar el formulario:', err);
      this.showMessage('Error al despublicar el formulario.');
    }
  });
}

handleError(error: any, message: string) {
  this.isLoading = false;
  console.error(error);
  this.showMessage(message);
}



}
