import { Component, computed, inject, OnInit, signal } from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';
import { TenantService } from '../../services/tenant.service';
import { CartService } from '../../services/cart/cart.service';
import { StoreFooterComponent, StoreFooterSection, StoreSocialLink } from './store-footer/store-footer.component';
import { StoreHeaderComponent } from './store-header/store-header.component';
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
import { ButtonComponent } from '../../../shared/components/button/button.component';
import { CartItem } from '../../services/cart/cart.interface';
import { AuthService } from '../../services/auth/auth.service';

@Component({
  selector: 'app-store-layout',
  imports: [RouterOutlet, StoreHeaderComponent, StoreFooterComponent, CartComponent, ButtonComponent],
  templateUrl: './store-layout.component.html',
  styleUrl: './store-layout.component.scss'
})
export class StoreLayoutComponent implements OnInit {
  private readonly tenantService = inject(TenantService);
  private readonly cartService = inject(CartService);
  private readonly authService = inject(AuthService);
  private readonly router = inject(Router);

  protected readonly isCartOpen = signal(false);

  protected readonly cartSubtotal = computed(() => {
    const cart = this.cartService.cart();
    return cart ? parseFloat(cart.subtotal) : 0;
  });

  protected readonly cartDiscount = computed(() => 0);

  protected readonly cartTotal = computed(() => this.cartSubtotal() - this.cartDiscount());

  protected readonly mappedCartItems = computed<CartItemMock[]>(() => {
    const cart = this.cartService.cart();
    if (!cart || !cart.items) return [];
    return cart.items.map((item) => this.mapCartItemToMock(item));
  });

  private mapCartItemToMock(item: CartItem): CartItemMock {
    const fullName = item.product?.nombre ?? '';
    let product = fullName;
    let attributes: { label: string; value: string }[] = [];

    const match = fullName.match(/^(.*?)\s*\((.*?)\)$/);
    if (match) {
      product = match[1];
      const attributesString = match[2];
      attributes = attributesString.split(',').map((attr) => {
        const parts = attr.split(':');
        if (parts.length === 2) {
          return { label: parts[0].trim(), value: parts[1].trim() };
        }
        return { label: '', value: attr.trim() };
      });
    }

    return {
      productVariantId: item.product_variant_id,
      imageUrl: item.product?.imagen ?? null,
      product,
      originalPrice: null,
      discountedPrice: parseFloat(item.precio_unitario),
      discountPercentage: null,
      attributes,
      quantity: item.cantidad
    };
  }

  protected readonly currentYear = new Date().getFullYear();
  protected readonly tenant = this.tenantService.tenant;
  protected readonly user = this.authService.user;
  protected readonly isAuthenticated = this.authService.isAuthenticated;

  protected readonly cartQuantity = computed(() => {
    const cart = this.cartService.cart();
    if (!cart || !cart.items) return 0;
    return cart.items.reduce((total, item) => total + item.cantidad, 0);
  });

  ngOnInit(): void {
    this.cartService.loadCart().subscribe({
      error: (err) => console.error('Error loading cart', err)
    });
  }

  protected onLoginClick(): void {
    void this.router.navigate(['/login']);
  }

  protected onLogoutClick(): void {
    this.authService.logout().subscribe({
      next: () => void this.router.navigate(['/login']),
      error: (err) => console.error('Error logging out', err)
    });
  }

  protected onCheckoutClick(): void {
    this.isCartOpen.set(false);
    void this.router.navigate(['/checkout']);
  }


  protected readonly footerSections: StoreFooterSection[] = [
    {
      heading: 'Cuenta',
      links: ['Mi cuenta', 'Mis compras', 'Cerrar sesion']
    },
    {
      heading: 'Ayuda',
      links: ['Contacto', 'Ayuda', 'Preguntas frecuentes']
    }
  ];

  protected readonly socialLinks: StoreSocialLink[] = [
    {
      label: 'Instagram',
      iconClass: 'fa-brands fa-instagram'
    },
    {
      label: 'WhatsApp',
      iconClass: 'fa-brands fa-whatsapp'
    },
    {
      label: 'Facebook',
      iconClass: 'fa-brands fa-facebook'
    },
    {
      label: 'LinkedIn',
      iconClass: 'fa-brands fa-linkedin-in'
    }
  ];
}
