import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Plan } from './pricing.model';
import { pricingData } from './data';
import { BaseService } from 'src/app/shared/service/base.service';
import { StorageService } from 'src/app/shared/service/storage.service';
import { v4 as uuidv4 } from 'uuid';
import { ToastService } from 'src/app/toast/toast-service';


@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit {
  products: Plan[] = [];

  accountuuid:string='';
  tenantuuid:string='';

  fieldsToHide: string[] = [
    'hard_limit', 'stripe_product_id', 'unit_amount', 'interval'
  ];

  constructor(private baseService: BaseService,private storage: StorageService,public toastService: ToastService  ) { }

  ngOnInit() {
    this.baseService.getData('subscriptions/getPlans').subscribe(
      (data: any) => {
        if (data && data.data) {
          this.products = data.data;

          console.log(this.products);
          
        }
      },
      (err) => {
        console.log(err);
      }
    );

    const userid = this.storage.getItem('user');
    this.baseService.getData(`tenants/getbyuserid/${userid}`).subscribe(
      (data:any) => {
        // console.log('Request successful', data.data[0].account.accountUUID);
        this.accountuuid= data.data[0].account.accountUUID
        this.tenantuuid = data.data[0].account.tenantUUID
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  // Check if a feature should be hidden
  shouldHideField(fieldName: string): boolean {
    return this.fieldsToHide.includes(fieldName);
  }

  toggleExpand(event: Event) {
    const cardBody = (event.target as HTMLElement).closest('.card-body');
    if (cardBody) {
      cardBody.classList.toggle('expanded');
      const readMoreLink = cardBody.querySelector('.read-more') as HTMLElement;
      if (cardBody.classList.contains('expanded')) {
        readMoreLink.innerText = 'Read less';
      } else {
        readMoreLink.innerText = 'Read more';
      }
    }
  }

  // Method to get the value of unit_amount
  getUnitAmount(product: Plan): string {
    if (product.attributes) {
      const attribute = product.attributes.find(attr => attr.attrName === 'unit_amount');
      return attribute ? attribute.attrValue : '0';
    }
    return '0';
  }

  addsubscriptions(event:any){
    console.log(event);
    const formData = new URLSearchParams();

    const startDate = new Date();
    const endDate = new Date();
    endDate.setMonth(startDate.getMonth() + 1);

    // Utility function to format date as YYYY-MM-DD
    const formatDate = (date: Date): string => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };




    formData.append('subscriptionuuid', uuidv4());
    formData.append('planid', event.id);
    formData.append('tenantuuid', this.tenantuuid );
    formData.append('acccountuuid', this.accountuuid);
    formData.append('isfree', event.type === 'paid' ? 'false' : 'true');    
    formData.append('iscustom', 'false');
    formData.append('iscancelled', 'false');
    formData.append('startson', formatDate(startDate));
    formData.append('ends_at', formatDate(endDate));
    formData.append('currency', 'USD');
    formData.append('createdon', formatDate(startDate));
    this.baseService.postData('subscriptions/subscription', formData).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          this.toastService.show('Plan added successfully!', { classname: 'bg-success text-light', delay: 3000 });

        }
      },
      (err) => {
      }
    );
  }
}


