import { Component, inject } from '@angular/core';
import { ButtonComponent } from '../../../../shared/components/button/button.component';
import {
  CartComponent,
  CartItemMock
} from '../../../../shared/components/cart/cart.component';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
import { InputComponent } from '../../../../shared/components/input/input.component';
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
import { ProductCardComponent } from '../../../../shared/components/product-card/product-card.component';
import { StoreSectionComponent } from '../../../../shared/components/store-section/store-section.component';
import { ModalService } from '../../../../core/services/modal.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component';

@Component({
  selector: 'app-reutilizables-test-page',
  imports: [
    ButtonComponent,
    CartComponent,
    InputComponent,
    PaginatorComponent,
    ProductCardComponent,
    StoreSectionComponent,
    IconButtonComponent,
    CartIconComponent,
    StepperComponent,
    StepComponent
  ],
  templateUrl: './reutilizables-test-page.component.html',
  styleUrl: './reutilizables-test-page.component.scss'
})
export class ReutilizablesTestPageComponent {
  private readonly tenantService = inject(TenantService);
  private readonly toastService = inject(ToastService);
  private readonly modalService = inject(ModalService);

  protected testStep1Valid = true;
  protected testStep2Valid = false;
  protected readonly tenant = this.tenantService.tenant;
  protected textValue = 'Auriculares';
  protected numberValue = '24';
  protected email = 'usuario@empresa.com';
  protected user = 'Juan Perez';
  protected password = '12345678';
  protected date = '2026-06-24';
  protected amount = '125000';
  protected percent = '12';
  protected period = '2026-06';
  protected editableValue = 'Solo lectura al cargar';
  protected disabledValue = 'No editable';
  protected invalidEmail = 'correo-invalido';
  protected fileName = '';
  protected clearTrigger = 0;
  protected editableDisabled = true;
  protected currentPage = 1;
  protected cartVisible = true;
  protected lastModalResult = 'Todavia no se abrio ningun modal.';
  protected readonly paginatorTotalPages = 8;
  protected readonly cartBackgroundColor = '#ffffff';

  protected readonly testProducts = [
    {
      title: 'Pantalon recto de scuba negro',
      originalPrice: 95000,
      discount: 20,
      transferPrice: 74800,
      imageUrl: '/images/pantalon-scuba.png'
    },
    {
      title: 'Zapatillas de running azul',
      originalPrice: 120000,
      discount: 15,
      transferPrice: 98000,
      imageUrl: '/images/zapatillas-running.png'
    },
    {
      title: 'Remera basica blanca (Sin Descuento)',
      originalPrice: 32000,
      discount: null,
      transferPrice: 30000,
      imageUrl: null
    }
  ];

  protected readonly cartMockItems: CartItemMock[] = [
    {
      imageUrl: null,
      product: 'Calza termica unisex con proceso sense y cintura con mayor agarre',
      originalPrice: 95000,
      discountedPrice: 76000,
      discountPercentage: 20,
      quantity: 1,
      attributes: [
        { label: 'Color', value: 'Beige' },
        { label: 'Talle', value: 'S' }
      ]
    },
    {
      imageUrl: null,
      product: 'Pantalon recto de scuba negro',
      originalPrice: null,
      discountedPrice: 89000,
      discountPercentage: null,
      quantity: 1,
      attributes: [
        { label: 'Color', value: 'Beige' },
        { label: 'Talle', value: 'S' }
      ]
    },
    {
      imageUrl: null,
      product: 'Top de supplex color habano',
      originalPrice: 98000,
      discountedPrice: 85000,
      discountPercentage: 20,
      quantity: 1,
      attributes: [
        { label: 'Color', value: 'Negro' },
        { label: 'Talle', value: 'XL' }
      ]
    },
    {
      imageUrl: null,
      product: 'Buzo oversize canguro gris',
      originalPrice: 72000,
      discountedPrice: 69000,
      discountPercentage: 5,
      quantity: 2,
      attributes: [
        { label: 'Color', value: 'Gris' },
        { label: 'Talle', value: 'M' }
      ]
    }
  ];

  protected onProductBuy(productTitle: string): void {
    console.log(`Comprando: ${productTitle}`);
    alert(`Comprando: ${productTitle}`);
  }

  protected onFileChange(file: File | null): void {
    this.fileName = file?.name ?? '';
  }

  protected clearFile(): void {
    this.fileName = '';
    this.clearTrigger += 1;
  }

  protected showCart(): void {
    this.cartVisible = true;
  }

  protected hideCart(): void {
    this.cartVisible = false;
    this.toastService.info('Se disparo el evento de cerrado del carrito mock.');
  }

  protected triggerToast(type: 'success' | 'danger' | 'info'): void {
    if (type === 'success') {
      this.toastService.success(
        'Operacion exitosa. El producto se ha guardado correctamente.'
      );
    } else if (type === 'danger') {
      this.toastService.danger(
        'Alerta de error. Hubo un problema al procesar la solicitud.'
      );
    } else if (type === 'info') {
      this.toastService.info(
        'Informacion del sistema: Hay una nueva actualizacion disponible.'
      );
    }
  }

  protected triggerPersistentToast(type: 'success' | 'danger' | 'info'): void {
    if (type === 'success') {
      this.toastService.success(
        'Exito persistente. Esta alerta no se cerrara sola.',
        0
      );
    } else if (type === 'danger') {
      this.toastService.danger(
        'Error persistente. Por favor, atienda este problema y cierrelo manualmente.',
        0
      );
    } else if (type === 'info') {
      this.toastService.info(
        'Informacion persistente: Mantendremos este aviso en pantalla.',
        0
      );
    }
  }

  protected openBasicModal(): void {
    this.openConfirmModal({
      title: 'Confirmar accion',
      content:
        'Caso base para verificar apertura, cierre y devolucion de resultado.',
      confirmLabel: 'Confirmar'
    });
  }

  protected openConfirmDeleteModal(): void {
    this.openConfirmDelete({
      title: 'Eliminar producto',
      content:
        'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
      confirmLabel: 'Eliminar'
    });
  }

  protected openLockedModal(): void {
    this.openConfirmModal({
      title: 'Modal bloqueado',
      content:
        'Este modal no se cierra tocando el backdrop ni con la tecla Escape.',
      confirmLabel: 'Entendido',
      closeOnBackdrop: false,
      closeOnEscape: false
    });
  }

  protected openWideModal(): void {
    this.openConfirmModal({
      title: 'Modal ancho',
      content: 'Demuestra una variante visual mas amplia para contenido mas pesado.',
      confirmLabel: 'Seguir',
      size: 'xl'
    });
  }

  protected openSimpleModal(): void {
    this.modalService.openSimple({
      title: 'Mensaje del sistema',
      content: 'Este es un mensaje simple del sistema que no requiere confirmación.',
      buttonLabel: 'Entendido'
    }).subscribe(() => {
      this.lastModalResult = 'Simple modal cerrado';
    });
  }

  private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
    this.modalService.openConfirm(config).subscribe((confirmed) => {
      this.lastModalResult = `Resultado: ${confirmed}`;
    });
  }

  private openConfirmDelete(
    config: Parameters<ModalService['openConfirmDelete']>[0]
  ): void {
    this.modalService.openConfirmDelete(config).subscribe((confirmed) => {
      this.lastModalResult = `Resultado: ${confirmed}`;
    });
  }
}


