import { LightningElement, api, track, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import LEAD_OBJECT from '@salesforce/schema/Opportunity';
import getLeadForId from '@salesforce/apex/LeadController.getLeadForId';
import saveOpportunityData from '@salesforce/apex/OpportunityController.saveOpportunityData';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import strUserId from '@salesforce/user/Id';
import { CurrentPageReference } from 'lightning/navigation';
import { CloseActionScreenEvent } from 'lightning/actions';

export default class PartnerOpportunityCreation extends LightningElement {

  accountId = '';
  @track closeDate = new Date();
  @track opportunityName = '';
  amount = '';
  company ='';
  stageName = 'Prospecting';
  currencyIsoCode = 'EUR - Euro'

  leadOptions = [];
  @api recordId;
  userId = strUserId;

  // Getter and setter for default Close Date
  get defaultCloseDateValue() {
    const today = new Date();
    const twoWeeksFromNow = new Date(today.getTime() + (14 * 24 * 60 * 60 * 1000)); // Adding 2 weeks (14 days) to today’s date
    this.closeDate = twoWeeksFromNow.toISOString().split('T')[0];
    return this.closeDate;
  }

  set defaultCloseDateValue(value) {
    this.closeDate = value;
  }

  // Getter and setter for default Opportunity Name
  get defaultOpportunityNameValue() {
    this.opportunityName = `${this.company} from Partner Account Name`; // Combining Company field from Lead and 'from Partner Account Name'
    return this.opportunityName;
  }

  set defaultOpportunityNameValue(value) {
    this.opportunityName = value;
  }


  handleLookupSelection(event){
    if(event.detail.selectedRecord != undefined){
        console.log('Selected Record Value on Parent Component is ' +
        JSON.stringify(event.detail.selectedRecord));
        //alert(event.detail.selectedRecord.Id + ' '+ event.detail.selectedRecord.Name);
    }
  }

  handleAmountChange(event) {
    this.amount = parseFloat(event.detail.value);
    console.log('this.amount:', this.amount);
  }

  handleCloseDateChange(event) {
    this.closeDate = new Date(event.detail.value);
    console.log('this.closeDate:', this.closeDate);
  }

  handleOpportunityNameChange(event) {
    this.opportunityName = event.detail.value;
    console.log('this.opportunityName:', this.opportunityName);
  }

  @wire(getObjectInfo, { objectApiName: LEAD_OBJECT })
  objectInfo;

  @wire(CurrentPageReference)
  async getStateParameters(currentPageReference) {
    console.log('1-- recordId:', this.recordId);
    try {
      if (currentPageReference) {
        this.recordId = currentPageReference.state.recordId;
        console.log('2-- recordId:', this.recordId);
      }
      const resultLeads = await getLeadForId({ recordId: this.recordId });
      const selectedLead = resultLeads.find(
        (lead) => lead.Id === this.recordId
      );
      console.log('3-- recordId:', this.recordId);
      if (selectedLead) {
        this.company = selectedLead.Company;
        console.error('Company:', this.company);
      } else {
          console.error('Lead not found for recordId:', this.recordId);
      }
    } catch (error) {
        console.error('Error loading data:', error.message);
    }
  }

  // async connectedCallback() {
  //   console.log('recordId:', this.recordId);
  //   try {
  //     if (this.recordId) {
  //       const resultLeads = await getLeadForId({ recordId: this.recordId });
  //       const selectedLead = resultLeads.find(
  //         (lead) => lead.Id === this.recordId
  //       );

  //       if (selectedLead) {
  //         this.company = selectedLead.Company;
  //         console.error('Company:', this.company);
  //       } else {
  //         console.error('Lead not found for recordId:', this.recordId);
  //       }
  //     } else {
  //       console.error('recordId is not available.');
  //     }
  //   } catch (error) {
  //     console.error('Error loading data:', error.message);
  //   }
  // }

  async submitData() {
    try {
      await saveOpportunityData({
        id: this.recordId,
        accountId: this.accountId,
        closeDate: this.closeDate,
        opportunityName: this.opportunityName,
        amount: this.amount,
        stageName: this.stageName,
        currencyIsoCode: this.currencyIsoCode,
      });

      this.showSuccessToast('Opportunity data updated successfully');
    } catch (error) {
      this.showErrorToast(error.body.message);
    }
  }

  handleCancel() {
    this.accountId = '';
    this.company = '';
    this.closeDate = new Date();
    this.opportunityName = '';
    this.amount = '';
    this.dispatchEvent(new CloseActionScreenEvent());
  }

  showSuccessToast(message) {
    this.dispatchEvent(
      new ShowToastEvent({
        title: 'Success',
        message: message,
        variant: 'success',
      })
    );
  }

  showErrorToast(message) {
    this.dispatchEvent(
      new ShowToastEvent({
        title: 'Error',
        message: message,
        variant: 'error',
      })
    );
  }
} Using this code rewrite this (  // Getter and setter for default Opportunity Name
  get defaultOpportunityNameValue() {
    this.opportunityName = `${this.company} from Partner Account Name`; // Combining Company field from Lead and 'from Partner Account Name'
    return this.opportunityName;
  }

  set defaultOpportunityNameValue(value) {
    this.opportunityName = value;
  }
). So in result Opportunity Name should dynamically have value in this format: 'company name value'  from 'partner account name value'