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 { ProductColumnWithImageComponent } from '../../../../shared/components/product-column-with-image/product-column-with-image.component';
import { ProductRowCardComponent } from '../../../../shared/components/product-row-card/product-row-card.component';
import { ProductTicketSelectorComponent } from '../../../../shared/components/product-ticket-selector/product-ticket-selector.component';
import { ProductVerticalWithCartCardComponent } from '../../../../shared/components/product-vertical-with-cart-card/product-vertical-with-cart-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';
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
import { MainCarouselComponent } from '../../../../shared/components/main-carousel/main-carousel.component';
import { AccordionComponent } from '../../../../shared/components/accordion/accordion.component';
import { AccordionItemComponent } from '../../../../shared/components/accordion/accordion-item.component';
import {
  LocationMapComponent,
  MapLocation,
} from '../../../../shared/components/location-map/location-map.component';

interface CarouselProductMock {
  id: number;
  title: string;
  originalPrice: number;
  discount: number | null;
  transferPrice: number;
  imageUrl: string;
}

const ticketOption = (value: string, label: string = value): { value: string; label: string } => ({
  value,
  label,
});

@Component({
  selector: 'app-reutilizables-test-page',
  imports: [
    ButtonComponent,
    CartComponent,
    InputComponent,
    PaginatorComponent,
    ProductColumnWithImageComponent,
    ProductRowCardComponent,
    ProductTicketSelectorComponent,
    ProductVerticalWithCartCardComponent,
    StoreSectionComponent,
    IconButtonComponent,
    CartIconComponent,
    StepperComponent,
    StepComponent,
    CarouselComponent,
    MainCarouselComponent,
    AccordionComponent,
    AccordionItemComponent,
    LocationMapComponent,
  ],
  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 mapLocations: readonly MapLocation[] = [
    {
      id: 'gigante-de-arroyito',
      label: 'Gigante de Arroyito',
      address: 'Av. Génova 640, Rosario',
      latitude: -32.913997,
      longitude: -60.674567,
    },
    {
      id: 'punto-centro',
      label: 'Punto Centro',
      address: 'Centro, Rosario',
      latitude: -32.94682,
      longitude: -60.63932,
    },
    {
      id: 'punto-sur',
      label: 'Punto Sur',
      address: 'Zona sur, Rosario',
      latitude: -32.97151,
      longitude: -60.65064,
    },
  ];
  protected readonly mainCarouselImages = [
    'https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=1600&q=80',
    'https://images.unsplash.com/photo-1529139574466-a303027c1d8b?auto=format&fit=crop&w=1600&q=80',
    'https://images.unsplash.com/photo-1483985988355-763728e1935b?auto=format&fit=crop&w=1600&q=80',
  ];
  protected readonly mainCarouselImageAlts = [
    'Interior de una tienda de indumentaria',
    'Colección de moda en exteriores',
    'Percheros con prendas de distintos colores',
  ];

  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 carouselProducts: CarouselProductMock[] = [
    {
      id: 1,
      title: '01 · Mochila roja',
      originalPrice: 85000,
      discount: 20,
      transferPrice: 68000,
      imageUrl: '/images/carousel-mochila-roja.webp',
    },
    {
      id: 2,
      title: '02 · Auriculares amarillos',
      originalPrice: 120000,
      discount: 15,
      transferPrice: 102000,
      imageUrl: '/images/carousel-auriculares-amarillos.webp',
    },
    {
      id: 3,
      title: '03 · Reloj verde',
      originalPrice: 96000,
      discount: 10,
      transferPrice: 86400,
      imageUrl: '/images/carousel-reloj-verde.webp',
    },
    {
      id: 4,
      title: '04 · Cámara violeta',
      originalPrice: 135000,
      discount: null,
      transferPrice: 128000,
      imageUrl: '/images/carousel-camara-violeta.webp',
    },
    {
      id: 5,
      title: '05 · Zapatillas naranjas',
      originalPrice: 110000,
      discount: 25,
      transferPrice: 82500,
      imageUrl: '/images/carousel-zapatillas-naranjas.webp',
    },
    {
      id: 6,
      title: '06 · Campera azul',
      originalPrice: 142000,
      discount: 12,
      transferPrice: 121000,
      imageUrl: '/images/carousel-campera-azul.webp',
    },
  ];

  protected readonly trackCarouselProduct = (
    _index: number,
    product: CarouselProductMock,
  ): number => product.id;

  protected readonly testRowProduct = {
    title: 'ENTRADA GENERAL',
    description:
      'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
    price: 10000,
    variants: [
      { id: '10-oct-manana', values: { fecha: '10 de Octubre', turno: 'Mañana' } },
      { id: '10-oct-tarde', values: { fecha: '10 de Octubre', turno: 'Tarde' } },
      { id: '11-oct-tarde', values: { fecha: '11 de Octubre', turno: 'Tarde' } },
    ],
  };

  protected readonly testVerticalWithCartProduct = {
    title: 'PANCHO',
    description: 'Pancho con aderezo a elección.',
    price: 11500,
  };

  protected readonly testTicketSelectorProduct = {
    title: 'ENTRADAS DESFILE PURA TENDENCIA',
    description: '',
    price: 40000,
    imageUrl: '/images/ticket-selector-entrada-pasarela.png',
    variants: [
      {
        id: 1001,
        precio: 250000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
          sector: ticketOption('a', 'Sector A'),
          fila: ticketOption('1', 'Fila 1'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1002,
        precio: 250000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
          sector: ticketOption('a', 'Sector A'),
          fila: ticketOption('1', 'Fila 1'),
          asiento: ticketOption('2', 'Asiento 2'),
        },
      },
      {
        id: 1003,
        precio: 250000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
          sector: ticketOption('c', 'Sector C'),
          fila: ticketOption('1', 'Fila 1'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1004,
        precio: 200000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
          sector: ticketOption('a', 'Sector A'),
          fila: ticketOption('2', 'Fila 2'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1005,
        precio: 200000,
        maximum_addable_quantity: 0,
        values: {
          tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
          sector: ticketOption('a', 'Sector A'),
          fila: ticketOption('2', 'Fila 2'),
          asiento: ticketOption('2', 'Asiento 2'),
        },
      },
      {
        id: 1006,
        precio: 100000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('general', 'General'),
          sector: ticketOption('b', 'Sector B'),
          fila: ticketOption('3', 'Fila 3'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1007,
        precio: 100000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('general', 'General'),
          sector: ticketOption('b', 'Sector B'),
          fila: ticketOption('3', 'Fila 3'),
          asiento: ticketOption('2', 'Asiento 2'),
        },
      },
      {
        id: 1008,
        precio: 90000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('general', 'General'),
          sector: ticketOption('d', 'Sector D'),
          fila: ticketOption('3', 'Fila 3'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1009,
        precio: 65000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('general', 'General'),
          sector: ticketOption('d', 'Sector D'),
          fila: ticketOption('4', 'Fila 4'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
      {
        id: 1010,
        precio: 40000,
        maximum_addable_quantity: 1,
        values: {
          tipo: ticketOption('general', 'General'),
          sector: ticketOption('d', 'Sector D'),
          fila: ticketOption('5', 'Fila 5'),
          asiento: ticketOption('1', 'Asiento 1'),
        },
      },
    ],
  };

  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 onTicketBuy(variantIds: number[]): void {
    this.toastService.success(
      `Compra iniciada para ${variantIds.length} entrada/s: ${variantIds.join(', ')}.`,
    );
  }

  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}`;
    });
  }
}
