import { FormApiService, FormConfiguration, FormListItem } from './../../services/FormApiService.service';
import { Component, OnInit } from '@angular/core';
import { EnviarInfoService } from '../../services/enviar-info.service';
import { FormService } from '../../services/FormService.service';
import { ActivatedRoute, Router } from '@angular/router';
import { FormArray } from '@angular/forms';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

interface GridCell {
  row: number;
  col: number;
  selected: boolean;
  element?: FormElement;
}

interface FormElement {
  type: 'text' | 'select' | 'radio' | 'checkbox' | 'textarea' | 'number' | 'email' | 'date';
  label: string;
  placeholder?: string;
  required: boolean;
  options?: string[];
  id?: string;
  name?: string;
  value?: string;
  min?: number;
  max?: number;
  pattern?: string;
  description?: string;
}

interface Tab {
  id: string;
  name: string;
  active: boolean;
  rows: number;
  columns: number;
  grid: GridCell[][];
}

@Component({
  selector: 'app-admin-form',
  templateUrl: './admin-form.component.html',
  styleUrls: ['./admin-form.component.css']
})
export class AdminFormComponent implements OnInit {
  color: string = '';
  textColor: string = '';
  formTitle: string = '';

  // Nuevas propiedades para manejar formularios
  currentFormId: number | null = null;
  savedForms: FormListItem[] = [];
  isLoading = false;
  saveStatus = '';

  defaultRows = 3;
  defaultColumns = 3;
  showTooltip = '';

  tabs: Tab[] = [];
  currentTab: Tab | null = null;
  grid: GridCell[][] = [];
  editingElement: FormElement | null = null;

  showElementSelector = false;
  selectedCell: GridCell | null = null;

  availableElements: FormElement[] = [
    { type: 'text', label: 'Texto Corto', required: false },
    { type: 'number', label: 'Número', required: false },
    { type: 'email', label: 'Correo Electrónico', required: false },
    { type: 'date', label: 'Fecha', required: false },
    { type: 'textarea', label: 'Texto Largo', required: false },
    { type: 'select', label: 'Lista de Opciones', required: false, options: ['Opción 1'] },
    { type: 'radio', label: 'Selección Única', required: false, options: ['A', 'B'] },
    { type: 'checkbox', label: 'Casilla', required: false },
     {
    type: 'select',
    label: 'LADA Telefónica',
    required: false,
    options: ['+52 (MX)', '+1 (US)']
  }
  ];
  formData: any;
  form: any;

constructor(
  private _enviarInfo: EnviarInfoService,
  private formApiService: FormApiService,
  private formService: FormService,
  private route: ActivatedRoute,
  private router: Router,
  private fb: FormBuilder
) {}


  ngOnInit() {
    this._enviarInfo.currentTextColor.subscribe(color => this.textColor = color);
    this._enviarInfo.currentColor.subscribe(color => this.color = color);
    this.addTab();
     this.route.queryParams.subscribe(params => {
    const id = params['id'];
    if (id) {
      this.cargarFormulario(+id);
      console.log('ID recibido:', id);
    }
  });
    // this.loadSavedForms();
  }
  initializeForm(): void {
  const formControls: { [key: string]: FormControl } = {};

  for (const tab of this.tabs) {
    for (let rowIndex = 0; rowIndex < tab.grid.length; rowIndex++) {
      const row = tab.grid[rowIndex];
      for (let colIndex = 0; colIndex < row.length; colIndex++) {
        const cell = row[colIndex];
        if (cell?.element) {
          // Usar tab directamente aquí ya que estamos iterando sobre this.tabs
          const controlName = this.getControlName(tab, { ...cell, row: rowIndex, col: colIndex });
          formControls[controlName] = new FormControl('');
        }
      }
    }
  }

  this.form = this.fb.group(formControls);
}
getSafeControlName(cell: any, rowIndex: number, colIndex: number): string {
  if (!this.currentTab) {
    return `campo_${rowIndex}_${colIndex}`;
  }
  return this.getControlName(this.currentTab, { ...cell, row: rowIndex, col: colIndex });
}


  // MÉTODOS PARA MANEJAR LA API

  loadSavedForms() {
    this.isLoading = true;
    this.formApiService.getForms().subscribe({
      next: (forms) => {
        this.savedForms = forms;
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Error al cargar formularios:', error);
        this.saveStatus = 'Error al cargar formularios';
        this.isLoading = false;
      }
    });
  }

 saveForm() {
  if (!this.formTitle.trim()) {
    alert('Por favor, ingresa un título para el formulario');
    return;
  }



  const tabConError = this.tabs.find(tab => tab.rows < 1 || tab.columns < 1);
  if (tabConError) {
    alert(` La sección "${tabConError.name}" tiene un número inválido de filas o columnas.\n\n
    No se permite 0.\n Usa al menos 1 fila y 1 columna.`);
    return;
  }

  // Guardar la cuadrícula del tab activo actual
  if (this.currentTab) {
    this.currentTab.grid = [...this.grid];
  }

  const config = this.buildFormConfiguration();
  this.isLoading = true;
  this.saveStatus = 'Guardando...';

  this.formApiService.createForm(config).subscribe({
    next: (response) => {
      console.log('Formulario guardado:', response);
      this.currentFormId = response.id;
      this.saveStatus = 'Formulario guardado exitosamente';
      this.isLoading = false;
      this.router.navigate(['/homeAdmin/verFormulario']);
    },
    error: (error) => {
      console.error('Error al guardar formulario:', error);
      this.saveStatus = 'Error al guardar el formulario';
      this.isLoading = false;
    }
  });
}




  loadForm(formId: number) {
    this.isLoading = true;
    this.formApiService.getForm(formId).subscribe({
      next: (formData) => {
        this.loadFormConfiguration(formData);
        this.currentFormId = formId;
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Error al cargar formulario:', error);
        this.saveStatus = 'Error al cargar el formulario';
        this.isLoading = false;
      }
    });
  }

  publishForm(formId: number) {
    if (!confirm('¿Estás seguro de que quieres publicar este formulario?')) {
      return;
    }

    this.isLoading = true;
    this.formApiService.publishForm(formId).subscribe({
      next: (response) => {
        this.saveStatus = 'Formulario publicado exitosamente';
        this.loadSavedForms();
        this.isLoading = false;

        setTimeout(() => {
          this.saveStatus = '';
        }, 3000);
      },
      error: (error) => {
        console.error('Error al publicar formulario:', error);
        this.saveStatus = 'Error al publicar el formulario';
        this.isLoading = false;
      }
    });
  }

  buildFormConfiguration(): FormConfiguration {
    return {
      title: this.formTitle,
      tabs: this.tabs.map(tab => ({
        id: tab.id,
        title: tab.name,
        rows: tab.rows,
        columns: tab.columns,
        elements: this.extractElementsFromGrid(tab.grid)
      }))
    };
  }

  loadFormConfiguration(formData: any) {
    this.formTitle = formData.title || '';
    this.tabs = [];

    if (formData.tabs && formData.tabs.length > 0) {
      formData.tabs.forEach((tabData: any) => {
        const newTab: Tab = {
          id: tabData.id,
          name: tabData.title,
          active: false,
          rows: tabData.rows,
          columns: tabData.columns,
          grid: this.buildNewGrid(tabData.rows, tabData.columns)
        };

        // Cargar elementos en el grid
        if (tabData.elements && tabData.elements.length > 0) {
          tabData.elements.forEach((elementData: any) => {
            const { row, col } = elementData.position;
            if (row < newTab.rows && col < newTab.columns) {
              newTab.grid[row][col].element = { ...elementData.element };
            }
          });
        }

        this.tabs.push(newTab);
      });

      this.switchToTab(this.tabs[0]);
        this.initializeForm();
    } else {
      this.addTab();
    }
  }

  newForm() {
    if (confirm('¿Estás seguro de que quieres crear un nuevo formulario? Se perderán los cambios no guardados.')) {
      this.formTitle = '';
      this.currentFormId = null;
      this.tabs = [];
      this.addTab();
      this.saveStatus = '';
    }
  }

  deleteForm(formId: number) {
    if (!confirm('¿Estás seguro de que quieres eliminar este formulario? Esta acción no se puede deshacer.')) {
      return;
    }

    // Nota: Necesitarás agregar la ruta DELETE en tu API Laravel
    // Por ahora, solo actualizar la lista
    this.loadSavedForms();
  }

  // MÉTODOS EXISTENTES (sin cambios)

  get rows(): number {
    return this.currentTab?.rows ?? this.defaultRows;
  }

  get columns(): number {
    return this.currentTab?.columns ?? this.defaultColumns;
  }

  // TABS
  addTab(rows = this.defaultRows, columns = this.defaultColumns) {
    const newTab: Tab = {
      id: `tab_${this.tabs.length + 1}`,
      name: `Sección ${this.tabs.length + 1}`,
      active: false,
      rows,
      columns,
      grid: this.buildNewGrid(rows, columns)
    };
    this.tabs.push(newTab);
    this.switchToTab(newTab);
  }

  removeTab() {
    if (this.tabs.length <= 1) return;

    const activeIndex = this.tabs.findIndex(tab => tab.active);
    if (activeIndex === -1) return;

    this.tabs.splice(activeIndex, 1);
    const newActiveIndex = activeIndex === 0 ? 0 : activeIndex - 1;
    this.tabs.forEach((tab, index) => {
      tab.active = index === newActiveIndex;
    });
  }

  switchToTab(tab: Tab) {
    if (this.currentTab) this.currentTab.grid = [...this.grid];
    this.tabs.forEach(t => t.active = false);
    tab.active = true;
    this.currentTab = tab;
    this.grid = [...tab.grid];
    this.clearSelection();
  }

  updateTabName(tab: Tab, name: string) {
    tab.name = name;
  }

  // GRID
  buildNewGrid(rows: number, columns: number): GridCell[][] {
    return Array.from({ length: rows }, (_, r) =>
      Array.from({ length: columns }, (_, c) => ({
        row: r, col: c, selected: false
      }))
    );
  }

  updateTabDimensions(tab: Tab, newRows: number, newColumns: number) {
    const oldGrid = tab.grid.map(row => row.map(cell => ({ ...cell, element: cell.element ? { ...cell.element } : undefined })));

    tab.rows = newRows;
    tab.columns = newColumns;
    tab.grid = this.buildNewGrid(newRows, newColumns);

    this.preserveElementsInNewGrid(oldGrid, tab.grid, newRows, newColumns);

    if (this.currentTab?.id === tab.id) {
      this.grid = tab.grid.map(row => row.map(cell => ({ ...cell, element: cell.element ? { ...cell.element } : undefined })));
    }
  }

  preserveElementsInNewGrid(oldGrid: GridCell[][], newGrid: GridCell[][], maxR: number, maxC: number) {
    for (let r = 0; r < oldGrid.length; r++) {
      for (let c = 0; c < oldGrid[r]?.length; c++) {
        const cell = oldGrid[r][c];
        if (cell?.element && r < maxR && c < maxC) {
          newGrid[r][c].element = { ...cell.element };
        }
      }
    }
  }

  onTabDimensionsChange(event: { tab: Tab, rows: number, columns: number }) {
    this.updateTabDimensions(event.tab, event.rows, event.columns);
  }

  buildGrid() {
    if (this.currentTab) {
      this.currentTab.grid = this.grid = this.buildNewGrid(this.currentTab.rows, this.currentTab.columns);
    }
  }

  verifyGridIntegrity(grid: GridCell[][]): boolean {
    return grid.every((row, r) => row.every((cell, c) => {
      cell.row = r;
      cell.col = c;
      return true;
    }));
  }

  // FORM CONFIG
  onFormTitleChange(title: string) {
    this.formTitle = title;
  }

  onRowsChange(rows: number) {
    if (this.currentTab) this.updateTabDimensions(this.currentTab, rows, this.currentTab.columns);
  }

  onColumnsChange(cols: number) {
    if (this.currentTab) this.updateTabDimensions(this.currentTab, this.currentTab.rows, cols);
  }

  onShowTooltipChange(field: string) {
    this.showTooltip = field;
  }

  // SERIALIZACIÓN
  logConfiguration() {
    const config = this.buildFormConfiguration();
    console.log('Configuración completa:', config);
    return config;
  }

  extractElementsFromGrid(grid: GridCell[][]) {
    return grid.flatMap(row => row
      .filter(cell => cell.element)
      .map(cell => ({
        position: { row: cell.row, col: cell.col },
        element: this.serializeElement(cell.element!)
      }))
    );
  }

  serializeElement(el: FormElement) {
    const base: any = {
      type: el.type, label: el.label, required: el.required
    };
    if (el.placeholder) base.placeholder = el.placeholder;
    if (el.id) base.id = el.id;
    if (el.name) base.name = el.name;
    if (el.value) base.value = el.value;
    if (el.description) base.description = el.description;
    if (el.options?.length) base.options = el.options;
    if (el.min !== undefined) base.min = el.min;
    if (el.max !== undefined) base.max = el.max;
    if (el.pattern) base.pattern = el.pattern;
    return base;
  }

  // INTERACCIÓN CON CELDAS Y CAMPOS
  selectCell(cell: GridCell) {
    this.clearSelection();
    cell.selected = true;
    this.selectedCell = cell;
    this.showElementSelector = true;
  }

  clearSelection() {
    this.grid.forEach(row => row.forEach(c => c.selected = false));
    this.selectedCell = null;
    this.showElementSelector = false;
    this.editingElement = null;
  }



addElementToCell(template: FormElement) {
  if (!this.selectedCell || this.selectedCell.element) {
    alert('Esta celda ya tiene un campo. Elimínalo primero.');
    return;
  }

  // Solicita un "nombre clave" legible para el input, ejemplo: "nombre_alumno"
  let nombreClave = prompt('Ingresa el identificador único para este campo (ej. nombre_alumno):');
  if (!nombreClave) {
    alert('Debes ingresar un identificador válido.');
    return;
  }

  // Limpia espacios y pasa a minúsculas para usar como key
  nombreClave = nombreClave.trim().toLowerCase().replace(/\s+/g, '_');

  const element = { ...template };

  element.id = `${this.currentTab?.id}_${nombreClave}`;
  element.name = nombreClave;          // <--- Aquí asignamos el key legible
  element.label = this.capitalizeWords(nombreClave.replace(/_/g, ' ')); // etiqueta legible: "Nombre Alumno"

  // Aplica validaciones según tipo, igual que antes
  switch (element.type) {
    case 'email':
      Object.assign(element, {
        required: true,
        pattern: '^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$',
        placeholder: 'ejemplo@correo.com'
      });
      break;
    case 'number':
      Object.assign(element, { required: true, min: 1, max: 100 });
      break;
    case 'text':
      Object.assign(element, {
        required: true,
        min: 1,
        max: 20,
        pattern: '^\\b(\\w+\\b\\s*){1,20}$'
      });
      break;
  }

  this.selectedCell.element = element;
  this.editingElement = element;
  this.showElementSelector = false;
  this.updateCurrentTabGrid();
}
getControlName(tab: Tab | null, cell: any): string {
  const row = cell.row ?? 0;
  const col = cell.col ?? 0;

  const rawName = cell.element?.name;
  const cleaned = rawName?.trim().replace(/\s+/g, '_').toLowerCase();

  return cleaned && cleaned !== '' ? cleaned : `campo_${row}_${col}`;
}


// Función para capitalizar palabras para label bonito
capitalizeWords(text: string): string {
  return text.replace(/\b\w/g, c => c.toUpperCase());
}


  updateCurrentTabGrid() {
    if (this.currentTab) this.currentTab.grid = [...this.grid];
  }

  removeElementFromCell(cell: GridCell) {
    cell.element = undefined;
    this.updateCurrentTabGrid();
  }

  selectElementForEditing(cell: GridCell) {
    this.editingElement = cell.element || null;
  }

  onEditingElementChange(updated: FormElement) {
    if (this.selectedCell) {
      this.selectedCell.element = updated;
      this.updateCurrentTabGrid();
    }
  }

  onElementChange(updated: FormElement) {
    if (this.editingElement) {
      Object.assign(this.editingElement, updated);
      this.updateCurrentTabGrid();
    }
  }
cargarFormulario(id: number): void {
  this.formService.getFormById(id).subscribe(data => {
    this.formData = data;
    console.log('Form a editar:', this.formData);

    this.loadFormConfiguration(this.formData.form.configuration);
    this.formTitle = this.formData.form.title;
    this.currentFormId = this.formData.form.id;

    // Inicializa el formulario reactivo basado en los campos
    this.initializeForm();
  });
}


  updateForm() {
  if (!this.formTitle.trim()) {
    alert('Por favor, ingresa un título para el formulario');
    return;
  }

  if (!this.currentFormId) {
    alert('No se ha cargado ningún formulario para editar');
    return;
  }

  const tabConError = this.tabs.find(tab => tab.rows < 1 || tab.columns < 1);
  if (tabConError) {
    alert(`La sección "${tabConError.name}" tiene dimensiones inválidas (mínimo 1 fila y 1 columna).`);
    return;
  }

  if (this.currentTab) {
    this.currentTab.grid = [...this.grid];
  }

  const config = this.buildFormConfiguration();
  this.isLoading = true;
  this.saveStatus = 'Actualizando formulario...';

  this.formService.updateForm(this.currentFormId, config).subscribe({
    next: (response) => {
      console.log('Formulario actualizado:', response);
      this.saveStatus = 'Formulario actualizado correctamente';
      this.isLoading = false;
            this.router.navigate(['/homeAdmin/verFormulario']);

    },
    error: (error) => {
      console.error('Error al actualizar formulario:', error);
      this.saveStatus = 'Error al actualizar el formulario';
      this.isLoading = false;
    }
  });
}
saveOrUpdateForm() {
  if (this.currentFormId) {
    this.updateForm();
  } else {
    this.saveForm();
  }
}

 }




