import { ChangeDetectionStrategy, Component, computed, inject, OnInit, signal, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { startWith } from 'rxjs';

import { CartService } from '../../../../core/services/cart/cart.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { CheckoutService, CreatePurchasePayload } from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartItem } from '../../../../core/services/cart/cart.interface';
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { CheckoutDataStepComponent } from './checkout-data-step.component';
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
import { CheckoutForm } from './checkout-page.models';

@Component({
  selector: 'app-checkout-page',
  standalone: true,
  imports: [
    CartComponent,
    StepperComponent,
    StepComponent,
    CheckoutDataStepComponent,
    CheckoutPaymentStepComponent
  ],
  templateUrl: './checkout-page.component.html',
  styleUrl: './checkout-page.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CheckoutPageComponent implements OnInit {
  private readonly formBuilder = inject(FormBuilder);
  private readonly cartService = inject(CartService);
  private readonly router = inject(Router);
  private readonly tenantService = inject(TenantService);
  private readonly checkoutService = inject(CheckoutService);
  private readonly authService = inject(AuthService);

  @ViewChild(StepperComponent) stepper!: StepperComponent;

  protected readonly form: CheckoutForm = this.formBuilder.nonNullable.group({
    nombre: ['', [Validators.required]],
    email: ['', [Validators.required, Validators.email]],
    dni: ['', [Validators.required]],
    telefono: ['', [Validators.required]]
  });

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

  protected readonly isStep1Valid = signal(this.form.valid);
  protected readonly isCreatingPurchase = signal(false);
  protected readonly createdPurchaseId = signal<number | null>(null);

  constructor() {
    this.form.statusChanges
      .pipe(startWith(this.form.status))
      .subscribe(() => this.isStep1Valid.set(this.form.valid));

    const user = this.authService.user();
    if (user) {
      this.form.patchValue({
        nombre: user.nombre_apellido,
        email: user.email,
        dni: user.dni ?? '',
        telefono: user.telefono ?? ''
      });
      this.form.controls.nombre.disable();
      this.form.controls.email.disable();
    }
  }

  ngOnInit(): void {
    this.cartService.loadCart().subscribe();
  }

  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 async onStep1Continue(): Promise<void> {
    if (this.form.invalid) return;

    const tenant = this.tenantService.tenant();
    if (!tenant) return;

    this.isCreatingPurchase.set(true);

    try {
      const cart = this.cartService.cart();
      if (!cart?.id) {
        throw new Error('No hay un carrito activo para finalizar la compra.');
      }

      const formValue = this.form.getRawValue();
      const payload: CreatePurchasePayload = {
        cart_id: cart.id,
        dni: formValue.dni,
        telefono: formValue.telefono,
        email: formValue.email,
        nombre_apellido: formValue.nombre,
      };

      const response = await this.checkoutService.createPurchase(tenant.codigo, payload);
      this.createdPurchaseId.set(response.id);
      
      this.stepper.next();

    } catch (error) {
      console.error('Failed to create purchase:', error);
      // Here we could show an alert or toast
    } finally {
      this.isCreatingPurchase.set(false);
    }
  }

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

  protected async onComplete(): Promise<void> {
    const purchaseId = this.createdPurchaseId();
    const tenant = this.tenantService.tenant();

    if (!purchaseId || !tenant) {
      return;
    }

    try {
      await this.checkoutService.completePurchase(tenant.codigo, purchaseId);
      this.cartService.clearCart();
      void this.router.navigate(['/checkout/status', purchaseId]);
    } catch (error) {
      console.error('Failed to complete purchase:', error);
    }
  }
}
